Public
Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// SPDX-License-Identifier: 0BSD
import { type Store } from "npm:@keyvhq/core";
import { type Adapter, Low } from "npm:lowdb";
export type Keyv<T> = Map<string, T>;
export type KeyvLowOptions<TValue> = {
adapter: Adapter<Record<string, TValue>>;
};
class MapAdapter<TValue> implements Adapter<Keyv<TValue>> {
constructor(
private adapter: Adapter<Record<string, TValue>>,
) {}
read = async () => {
const obj = await this.adapter.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.adapter.write(obj);
};
}
export class KeyvLow<TValue> implements Store<TValue> {
private adapter: MapAdapter<TValue>;
private db: Low<Keyv<TValue>>;
constructor(options: KeyvLowOptions<TValue>) {
this.adapter = new MapAdapter(options.adapter);
this.db = new Low(this.adapter, new Map());
}
clear = async (namespace = "") => {
await this.db.read();
const keysToDelete = [];
for (const key of this.db.data.keys()) {
if (key.startsWith(namespace)) {
keysToDelete.push(key);
}
}
keysToDelete.forEach(key => this.db.data.delete(key));
return this.db.write();
};
delete = async (key: string) => {
await this.db.read();
const result = this.db.data.delete(key);
await this.db.write();
return result;
};
has = async (key: string) => {
await this.db.read();
return this.db.data.has(key);
};
get = async (key: string) => {
await this.db.read();
return this.db.data.get(key);
};
set = async (key: string, value: TValue) => {
await this.db.read();
this.db.data.set(key, value);
return this.db.write();
};
async *iterator(namespace = "") {
await this.db.read();
for (const key of this.db.data.keys()) {
if (key.startsWith(namespace)) {
const value = this.db.data.get(key);
yield [key, value];
}
}
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 1, 2024