Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | 28x 28x 28x 35x 35x 35x 4x 4x 3x 3x 1x 1x 3x 1x 2x | import { Binding } from '@/core/bindings/Binding'
import { lazySettings } from '@/utils/lazySettings'
import { KVSettings } from '@/types/KVSettings'
import type { CloudflareEnv } from '@/types/CloudflareEnv'
/**
* Accessor for the Workers KV namespace binding (`kv_namespaces` in
* `wrangler.json`).
*
* @example
* ```ts
* const cache = new KVBinding() // binding name and default TTL from the configuration layer
* await cache.putJson(ctx.env, 'session:42', { userId: 42 })
* const session = await cache.getJson<Session>(ctx.env, 'session:42')
* ```
*
* @class
*
* @author Bayu Dwiyan Satria
* @version 1.0.0
* @since 1.0.0
*/
export class KVBinding<E extends CloudflareEnv = CloudflareEnv> extends Binding<KVNamespace, E> {
/**
* This accessor’s settings, resolved on first read.
*/
private readonly settings: () => KVSettings
/**
* Default expiration applied to writes, in seconds.
*/
private readonly expirationTtl?: number
/**
* Constructs a KVBinding instance.
*
* @param settings Resolved settings. Defaults to `resolve('kv')`, so callers
* normally construct this with no arguments at all.
*/
constructor(settings?: KVSettings) {
const settle = lazySettings<KVSettings>('kv', settings)
super(() => settle().binding)
this.settings = settle
}
/**
* Reads a value as text.
*
* @param env The Worker environment.
* @param key The key to read.
* @param cacheTtl How long, in seconds, the edge may serve this read from cache.
* @returns The stored value, or `null` when the key is absent or expired.
* @throws {@link MissingBindingError} When the KV binding is absent.
*/
public async get(env: E, key: string, cacheTtl?: number): Promise<string | null> {
const options = cacheTtl ? { cacheTtl } : undefined
return await this.resolve(env).get(key, options)
}
/**
* Reads a value and parses it as JSON.
*
* @param env The Worker environment.
* @param key The key to read.
* @param cacheTtl How long, in seconds, the edge may serve this read from cache.
* @returns The parsed value, or `null` when the key is absent or expired.
*/
public async getJson<T = unknown>(env: E, key: string, cacheTtl?: number): Promise<T | null> {
const options = cacheTtl ? { type: 'json' as const, cacheTtl } : { type: 'json' as const }
return await this.resolve(env).get<T>(key, options)
}
/**
* Reads a value together with its metadata.
*
* @param env The Worker environment.
* @param key The key to read.
* @returns The value and metadata pair — both `null` when the key is absent.
*/
public async getWithMetadata<Metadata = unknown>(
env: E,
key: string
): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>> {
return await this.resolve(env).getWithMetadata<Metadata>(key)
}
/**
* Writes a value, applying the configured default TTL when none is supplied.
*
* @param env The Worker environment.
* @param key The key to write.
* @param value The value to store.
* @param options Put options — expiration, TTL, and metadata.
*/
public async put(
env: E,
key: string,
value: string | ArrayBuffer | ArrayBufferView | ReadableStream,
options: KVNamespacePutOptions = {}
): Promise<void> {
await this.resolve(env).put(key, value, this.withDefaultTtl(options))
}
/**
* Serialises a value to JSON and writes it.
*
* @param env The Worker environment.
* @param key The key to write.
* @param value The value to serialise and store.
* @param options Put options — expiration, TTL, and metadata.
*/
public async putJson(env: E, key: string, value: unknown, options: KVNamespacePutOptions = {}): Promise<void> {
await this.put(env, key, JSON.stringify(value), options)
}
/**
* Deletes a key.
*
* Deleting a key that does not exist is not an error.
*
* @param env The Worker environment.
* @param key The key to delete.
*/
public async delete(env: E, key: string): Promise<void> {
await this.resolve(env).delete(key)
}
/**
* Lists keys in the namespace.
*
* @remarks
* Results are paginated — check `list_complete` and pass the returned
* `cursor` back in to read the next page.
*
* @param env The Worker environment.
* @param options List options — prefix, limit, and cursor.
* @returns The matched keys and pagination state.
*/
public async list<Metadata = unknown>(
env: E,
options: KVNamespaceListOptions = {}
): Promise<KVNamespaceListResult<Metadata>> {
return await this.resolve(env).list<Metadata>(options)
}
/**
* Applies the configured default TTL to put options that do not set one.
*
* @param options The caller-supplied put options.
* @returns Put options with an expiration applied where appropriate.
*/
private withDefaultTtl(options: KVNamespacePutOptions): KVNamespacePutOptions {
if (!this.settings().expirationTtl || options.expirationTtl || options.expiration) {
return options
}
return { ...options, expirationTtl: this.settings().expirationTtl }
}
}
|