@graphql-mesh/cache-cfw-kv
Version:
35 lines (34 loc) • 1.17 kB
JavaScript
import { handleMaybePromise } from '@whatwg-node/promise-helpers';
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 handleMaybePromise(() => 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) {
return handleMaybePromise(() => this.kvNamespace?.delete(key), () => true, () => false);
}
}