Back

Version 5

4/1/2024
import { Blob } from "https://esm.town/v/pomdtr/lowdb?v=17";
import { type Store } from "npm:@keyvhq/core";
import { type Adapter, Low } from "npm:lowdb";

export type Keyv<T> = Map<string, T>;
export type KeyvLowOptions = {
key?: string;
};

class MapBlob<TValue> implements Adapter<Keyv<TValue>> {
constructor(
private blob: Blob<Record<string, TValue>>,
) {}

read = async () => {
const obj = await this.blob.read() ?? {};
const entries = Object.entries(obj);
return new Map(entries);
};

write = async (data: Keyv<TValue>) => {
const entries = data.entries();
const obj = Object.fromEntries(entries);
return this.blob.write(obj);
};
}

export class KeyvLow<TValue> implements Store<TValue> {
private adapter: MapBlob<TValue>;
private db: Low<Keyv<TValue>>;

constructor(options?: KeyvLowOptions) {
const key = options?.key ?? "keyv";
this.adapter = new MapBlob(new Blob(key));
this.db = new Low(this.adapter, new Map());
}
Updated: April 1, 2024