UNPKG

@graphql-mesh/cache-cfw-kv

Version:
40 lines (39 loc) 1.23 kB
import { mapMaybePromise } from '@graphql-mesh/utils'; export default class CFWorkerKVCache { constructor(config) { if (typeof config.namespace === 'string') { this.kvNamespace = globalThis[config.namespace]; } else { this.kvNamespace = config.namespace; } if (this.kvNamespace === undefined) { // We don't use mocks because they increase the bundle size. config.logger?.warn(`Make sure KV Namespace: ${config.namespace} exists.`); } } get(key) { return this.kvNamespace?.get(key, 'json'); } getKeysByPrefix(prefix) { return mapMaybePromise(this.kvNamespace?.list({ prefix }), result => { if (!result) { return []; } return result.keys.map(keyEntry => keyEntry.name); }); } set(key, value, options) { return this.kvNamespace?.put(key, JSON.stringify(value), { expirationTtl: options?.ttl, }); } delete(key) { try { return mapMaybePromise(this.kvNamespace?.delete(key), () => true, () => false); } catch (e) { return false; } } }