You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `getOrSet` factory function accepts an `options` object as argument that can be used to dynamically set some cache options. This can be particulary useful when caching options depends on the value itself.
84
+
The `getOrSet` factory function accepts an `ctx` object as argument that can be used to do multiple things:
85
+
86
+
### ctx.setTtl
87
+
88
+
`setTtl` allows you to set the TTL of the key dynamically. This is useful when the TTL depends on the value itself.
85
89
86
90
```ts
87
91
const products =awaitbento.getOrSet({
88
92
key: 'token',
89
-
factory: async (options) => {
93
+
factory: async (ctx) => {
90
94
const token =awaitfetchAccessToken()
91
-
95
+
92
96
options.setTtl(token.expiresIn)
93
-
97
+
94
98
returntoken
95
99
}
96
100
})
97
101
```
98
102
99
-
Auth tokens are a perfect example of this use case. The cached token should expire when the token itself expires. And we know the expiration time only after fetching the token.
103
+
Auth tokens are a perfect example of this use case. The cached token should expire when the token itself expires. And we know the expiration time only after fetching the token. See [Adaptive Caching docs](./adaptive_caching.md) for more information.
104
+
105
+
### ctx.skip
106
+
107
+
Returning `skip` in a factory will not cache the value, and `getOrSet` will returns `undefined` even if there is a stale item in cache.
108
+
It will force the key to be recalculated on the next call.
109
+
110
+
```ts
111
+
cache.getOrSet({
112
+
key: 'foo',
113
+
factory: ({ skip, fail }) => {
114
+
const item =awaitgetFromDb()
115
+
if (!item) {
116
+
returnskip()
117
+
}
118
+
119
+
returnitem
120
+
}
121
+
})
122
+
```
123
+
124
+
### ctx.fail
125
+
126
+
Returning `fail` in a factory will not cache the value and will throw an error. If there is a stale item in cache, it will be used.
127
+
128
+
```ts
129
+
cache.getOrSet({
130
+
key: 'foo',
131
+
factory: ({ skip, fail }) => {
132
+
const item =awaitgetFromDb()
133
+
if (!item) {
134
+
returnskip()
135
+
}
136
+
137
+
if (item.isInvalid) {
138
+
returnfail('Item is invalid')
139
+
}
140
+
141
+
returnitem
142
+
}
143
+
})
144
+
```
100
145
101
-
###getOrSetForever
146
+
## getOrSetForever
102
147
103
148
Same as `getOrSet`, but the value will never expire.
Clear the cache. This will delete all the keys in the cache if called from the "root" instance. If called from a namespace, it will only delete the keys in that namespace.
155
200
156
201
```ts
157
202
awaitbento.clear();
158
203
```
159
204
160
-
###disconnect
205
+
## disconnect
161
206
162
207
Disconnect from the cache. This will close the connection to the cache server, if applicable.
0 commit comments