v3/packages/api/utils/kv.ts
Katalina 2ff6588030
Refactor node packages to yarn workspaces & ditch next.js for CRA. (#161)
* chore: restructure project into yarn workspaces, remove next

* fix tests, remove webapp from terraform

* remove more ui deployment bits

* remove pages, fix FUNDING.yml

* remove isomorphism

* remove next providers

* fix linting issues

* feat: start basis of new web ui system on CRA

* chore: move types to @roleypoly/types package

* chore: move src/common/utils to @roleypoly/misc-utils

* chore: remove roleypoly/ path remappers

* chore: renmove vercel config

* chore: re-add worker-types to api package

* chore: fix type linting scope for api

* fix(web): craco should include all of packages dir

* fix(ci): change api webpack path for wrangler

* chore: remove GAR actions from CI

* chore: update codeql job

* chore: test better github dar matcher in lint-staged
2021-03-12 18:04:49 -05:00

90 lines
2.4 KiB
TypeScript

export class WrappedKVNamespace {
constructor(private kvNamespace: KVNamespace) {}
async get<T>(key: string): Promise<T | null> {
const data = await this.kvNamespace.get(key, 'text');
if (!data) {
return null;
}
return JSON.parse(data) as T;
}
async put<T>(key: string, value: T, ttlSeconds?: number) {
await this.kvNamespace.put(key, JSON.stringify(value), {
expirationTtl: ttlSeconds,
});
}
list = this.kvNamespace.list;
getWithMetadata = this.kvNamespace.getWithMetadata;
delete = this.kvNamespace.delete;
}
class EmulatedKV implements KVNamespace {
constructor() {
console.warn('EmulatedKV used. Data will be lost.');
}
private data: Map<string, any> = new Map();
async get<T>(key: string): Promise<T | null> {
if (!this.data.has(key)) {
return null;
}
return this.data.get(key);
}
async getWithMetadata<T, Metadata = unknown>(
key: string
): KVValueWithMetadata<T, Metadata> {
return {
value: await this.get<T>(key),
metadata: {} as Metadata,
};
}
async put(key: string, value: string | ReadableStream<any> | ArrayBuffer | FormData) {
this.data.set(key, value);
}
async delete(key: string) {
this.data.delete(key);
}
async list(options?: {
prefix?: string;
limit?: number;
cursor?: string;
}): Promise<{
keys: { name: string; expiration?: number; metadata?: unknown }[];
list_complete: boolean;
cursor: string;
}> {
let keys: { name: string }[] = [];
for (let key of this.data.keys()) {
if (options?.prefix && !key.startsWith(options.prefix)) {
continue;
}
keys.push({ name: key });
}
return {
keys,
cursor: '0',
list_complete: true,
};
}
}
const kvOrLocal = (namespace: KVNamespace | null): KVNamespace =>
namespace || new EmulatedKV();
const self = (global as any) as Record<string, any>;
export const Sessions = new WrappedKVNamespace(kvOrLocal(self.KV_SESSIONS ?? null));
export const GuildData = new WrappedKVNamespace(kvOrLocal(self.KV_GUILD_DATA ?? null));
export const Guilds = new WrappedKVNamespace(kvOrLocal(self.KV_GUILDS ?? null));