UNPKG

cf-workers-kv

Version:

Cloudflare workers KV with customizable backing store for testing.

63 lines 2.4 kB
export class KV { constructor(backend) { this.data = backend; } async get(key, options) { const data = await this.data.get(key); if (!data) return null; const { value } = data; const type = typeof options === 'string' ? options : options && options.type ? options.type : 'text'; if (type === 'text') return value; if (type === 'json') return JSON.parse(value); throw new Error(`type not supported: ${type}`); } async getWithMetadata(key, type) { const data = await this.data.get(key); if (!data) return { value: null, metadata: null }; const { value, metadata } = data; type = type || 'text'; if (type === 'text') return { value, metadata }; if (type === 'json') return { value: JSON.parse(value), metadata }; throw new Error(`type not supported: ${type}`); } async put(key, value, options) { if (typeof value !== 'string') throw new Error('value type not supported'); if (options != null && (options.expiration != null || options.expirationTtl != null)) { throw new Error('expiration and TTL not supported'); } await this.data.set(key, { value, metadata: options && options.metadata ? options.metadata : null }); } async delete(key) { await this.data.delete(key); } async list(options) { options = options || {}; const prefix = options.prefix || ''; const limit = options.limit == null ? 1000 : options.limit; const skip = options.cursor ? parseInt(options.cursor) : 0; const allKeys = []; for await (const e of this.data.entries()) { allKeys.push(e); } const filteredKeys = prefix ? allKeys.filter(([k]) => k.startsWith(prefix)) : allKeys; const keys = filteredKeys .sort((a, b) => a[0] === b[0] ? 0 : a[0] < b[0] ? -1 : 1) .slice(skip, skip + limit) .map(([name, { metadata }]) => ({ name, metadata })); const complete = skip + limit >= allKeys.length; const cursor = complete ? undefined : `${skip + limit}`; return { keys, list_complete: complete, cursor }; } } //# sourceMappingURL=KV.js.map