* Set a value in the cache. * * @experimental **UNSTABLE**: New API, yet to be vetted. * * @param key The cache key. * @param value The value to set. * @param options Options for this entry. * @returns `this` for chaining. * * @example Usage * ```ts * import { TtlCac
(
key: K,
value: V,
options?: TtlCacheSetOptions,
)
| 154 | * ``` |
| 155 | */ |
| 156 | override set( |
| 157 | key: K, |
| 158 | value: V, |
| 159 | options?: TtlCacheSetOptions, |
| 160 | ): this { |
| 161 | if (options?.absoluteExpiration !== undefined && !this.#slidingExpiration) { |
| 162 | throw new TypeError( |
| 163 | "Cannot set entry in TtlCache: absoluteExpiration requires slidingExpiration to be enabled", |
| 164 | ); |
| 165 | } |
| 166 | |
| 167 | const ttl = options?.ttl ?? this.#defaultTtl; |
| 168 | if (!(ttl >= 0) || !Number.isFinite(ttl)) { |
| 169 | throw new RangeError( |
| 170 | `Cannot set entry in TtlCache: ttl must be a finite, non-negative number: received ${ttl}`, |
| 171 | ); |
| 172 | } |
| 173 | |
| 174 | const abs = options?.absoluteExpiration; |
| 175 | if (abs !== undefined && (!(abs >= 0) || !Number.isFinite(abs))) { |
| 176 | throw new RangeError( |
| 177 | `Cannot set entry in TtlCache: absoluteExpiration must be a finite, non-negative number: received ${abs}`, |
| 178 | ); |
| 179 | } |
| 180 | |
| 181 | const existing = this.#timeouts.get(key); |
| 182 | if (existing !== undefined) clearTimeout(existing); |
| 183 | super.set(key, value); |
| 184 | this.#timeouts.set(key, setTimeout(() => this.delete(key), ttl)); |
| 185 | |
| 186 | if (this.#slidingExpiration) { |
| 187 | this.#entryTtls!.set(key, ttl); |
| 188 | if (abs !== undefined) { |
| 189 | this.#absoluteDeadlines!.set(key, Date.now() + abs); |
| 190 | } else { |
| 191 | this.#absoluteDeadlines!.delete(key); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | return this; |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * Gets the value associated with the specified key. |