keyv-dir-store 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 snomiao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+
2
+ # KeyvDIR
3
+
4
+ Store key into a file per value
5
+
6
+ ## Store each value with CSV
7
+
8
+ ```ts
9
+ new Keyv({
10
+ store: new KeyvDirStore("cache/kv", { ext: "csv" }),
11
+ serialize: ({ value }) => csvFormat(value),
12
+ deserialize: (str) => ({ value: csvParse(str), expires: undefined }),
13
+ });
14
+ ```
15
+
16
+ ## Store each value with YAML
17
+
18
+ ```ts
19
+ new Keyv({
20
+ store: new KeyvDirStore("cache/kv", { ext: "yaml" }),
21
+ serialize: ({ value }) => yaml.stringify(value),
22
+ deserialize: (str) => ({ value: yaml.parse(str), expires: undefined }),
23
+ });
24
+ ```
package/index.test.ts ADDED
@@ -0,0 +1,55 @@
1
+ import Keyv from "keyv";
2
+ import { KeyvDirStore } from ".";
3
+
4
+ it("KeyvDirStore works", async () => {
5
+ // store test
6
+ const kv = new Keyv<number | string | { obj: boolean }>({
7
+ store: new KeyvDirStore("cache/test1"),
8
+ deserialize: KeyvDirStore.deserialize,
9
+ serialize: KeyvDirStore.serialize,
10
+ });
11
+ await kv.clear();
12
+ await kv.set("a", 1234, -86400e3); // already expired
13
+ expect(await kv.get("a")).toEqual(undefined); // will delete file before get
14
+ await kv.set("b", 1234); // never expired
15
+ expect(await kv.get("b")).toEqual(1234);
16
+ await kv.set("c", "b", 86400e3); // 1 day
17
+ expect(await kv.get("c")).toEqual("b");
18
+ await kv.set("d", { obj: false }, 86400e3); // obj store
19
+ expect(await kv.get("d")).toEqual({ obj: false });
20
+
21
+ // new instance with no cache Obj, to test file cache
22
+ const kv2 = new Keyv<number | string | { obj: boolean }>({
23
+ store: new KeyvDirStore("cache/test1"),
24
+ deserialize: KeyvDirStore.deserialize,
25
+ serialize: KeyvDirStore.serialize,
26
+ });
27
+ expect(await kv2.get("a")).toEqual(undefined); // will delete file before get
28
+ expect(await kv2.get("b")).toEqual(1234);
29
+ expect(await kv2.get("c")).toEqual("b");
30
+ expect(await kv2.get("d")).toEqual({ obj: false });
31
+ });
32
+ it("KeyvDirStore works with only store", async () => {
33
+ // store test
34
+ const kv = new Keyv<number | string | { obj: boolean }>({
35
+ store: new KeyvDirStore("cache/test2"),
36
+ });
37
+ await kv.clear();
38
+ await kv.set("a", 1234, -86400e3); // already expired
39
+ expect(await kv.get("a")).toEqual(undefined); // will delete file before get
40
+ await kv.set("b", 1234); // never expired
41
+ expect(await kv.get("b")).toEqual(1234);
42
+ await kv.set("c", "b", 86400e3); // 1 day
43
+ expect(await kv.get("c")).toEqual("b");
44
+ await kv.set("d", { obj: false }, 86400e3); // obj store
45
+ expect(await kv.get("d")).toEqual({ obj: false });
46
+
47
+ // new instance with no cache Obj, to test file cache
48
+ const kv2 = new Keyv<number | string | { obj: boolean }>({
49
+ store: new KeyvDirStore("cache/test2"),
50
+ });
51
+ expect(await kv2.get("a")).toEqual(undefined); // will delete file before get
52
+ expect(await kv2.get("b")).toEqual(1234);
53
+ expect(await kv2.get("c")).toEqual("b");
54
+ expect(await kv2.get("d")).toEqual({ obj: false });
55
+ });
package/index.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { stat } from "fs/promises";
2
+ import { writeFile } from "fs/promises";
3
+ import { rm } from "fs/promises";
4
+ import { readFile, mkdir } from "fs/promises";
5
+ import { type default as Keyv, type DeserializedData } from "keyv";
6
+ import md5 from "md5";
7
+ import sanitizeFilename from "sanitize-filename";
8
+ import path from "path";
9
+ import { utimes } from "fs/promises";
10
+ type Value = any;
11
+ type CacheMap<Value> = Map<string, DeserializedData<Value>>;
12
+ /**
13
+ * KeyvDirStore is a Keyv.Store<string> implementation that stores data in files.
14
+ * @example
15
+ * const kv = new Keyv<number | string | { obj: boolean }>({
16
+ * store: new KeyvDirStore("cache/test"),
17
+ * deserialize: KeyvDirStore.deserialize,
18
+ * serialize: KeyvDirStore.serialize,
19
+ * });
20
+ * await kv.set("a", 1234, -86400e3); // already expired
21
+ * expect(await kv.get("a")).toEqual(undefined); // will delete file before get
22
+ * await kv.set("b", 1234); // never expired
23
+ * expect(await kv.get("b")).toEqual(1234);
24
+ */
25
+ export class KeyvDirStore implements Keyv.Store<string> {
26
+ #dir: string;
27
+ #cache: CacheMap<Value>;
28
+ #ready: Promise<unknown>;
29
+ #path: (key: string) => string;
30
+ ext = ".json";
31
+ constructor(
32
+ dir: string,
33
+ {
34
+ cache = new Map(),
35
+ path,
36
+ ext,
37
+ }: {
38
+ cache?: CacheMap<Value>;
39
+ path?: (key: string) => string;
40
+ ext?: string;
41
+ } = {}
42
+ ) {
43
+ this.#ready = mkdir(dir, { recursive: true });
44
+ this.#cache = cache;
45
+ this.#dir = dir;
46
+ this.#path = path ?? this.#defaultPath;
47
+ this.ext = ext ?? this.ext;
48
+ }
49
+ #defaultPath(key: string) {
50
+ // use dir as hash salt to avoid collisions
51
+ const readableName = sanitizeFilename(key).slice(4, 16);
52
+ const hashName = md5(this.#dir + key).slice(0, 16);
53
+ const name = readableName + "-" + hashName + this.ext;
54
+ return path.join(this.#dir, name);
55
+ }
56
+ async get(key: string) {
57
+ // read memory
58
+ const cached = this.#cache.get(key);
59
+ if (cached) {
60
+ // console.log("memory cache hit but expired", key, cached.expires, Date.now());
61
+ if (cached.expires && cached.expires < Date.now()) {
62
+ await this.delete(key);
63
+ } else {
64
+ return cached.value;
65
+ }
66
+ }
67
+ // read file cache
68
+ const stats = await stat(this.#path(key)).catch(() => null);
69
+ if (!stats) return undefined; // stat not found
70
+ const expires = +stats.mtime;
71
+ if (expires !== 0) {
72
+ const expired = +stats.mtime < +Date.now();
73
+ if (expired) {
74
+ // console.log("file cache hit expired", key, expires, Date.now(), expired);
75
+ await this.delete(key);
76
+ return undefined;
77
+ }
78
+ }
79
+ // return this.#parse(await readFile(this.#path(key), "utf8"));
80
+ return await readFile(this.#path(key), "utf8").catch(() => undefined);
81
+ }
82
+ async set(key: string, value: Value, ttl?: number) {
83
+ if (!value) return await this.delete(key);
84
+ // const { value, expires } = JSON.parse(stored) as DeserializedData<Value>;
85
+ const expires = ttl ? Date.now() + ttl : 0;
86
+ // save to memory
87
+ this.#cache.set(key, { value, expires });
88
+ // save to file
89
+ await this.#ready;
90
+ // console.log({ key, value, expires });
91
+ await writeFile(this.#path(key), value); // create a expired file
92
+ await utimes(this.#path(key), +new Date(), new Date(expires ?? 0)); // set a future expires time (0 as never expired)
93
+ return true;
94
+ }
95
+ async delete(key: string) {
96
+ // delete memory
97
+ this.#cache.delete(key);
98
+ await rm(this.#path(key), { force: true });
99
+ return true;
100
+ }
101
+ async clear() {
102
+ await rm(this.#dir, { recursive: true }).catch(() => void 0);
103
+ await mkdir(this.#dir, { recursive: true });
104
+ }
105
+ async has(key: string) {
106
+ return undefined !== (await this.get(key));
107
+ }
108
+
109
+ // Save expires into mtime, and value into file
110
+ static serialize({ value }: DeserializedData<Value>): string {
111
+ return JSON.stringify(value, null, 2);
112
+ }
113
+ static deserialize(str: string): DeserializedData<Value> {
114
+ return { value: JSON.parse(str), expires: undefined };
115
+ }
116
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "keyv-dir-store",
3
+ "version": "0.0.1",
4
+ "author": "snomiao <snomiao@gmail.com>",
5
+ "type": "module",
6
+ "exports": {
7
+ "import": "./dist/index.js",
8
+ "types": "./index.ts"
9
+ },
10
+ "module": "index.ts",
11
+ "files": [
12
+ "*.ts",
13
+ "dist"
14
+ ],
15
+ "scripts": {
16
+ "build": "bun build index.ts --outdir=dist",
17
+ "release": "bunx standard-version && git push --follow-tags && npm publish",
18
+ "test": "bun test"
19
+ },
20
+ "devDependencies": {
21
+ "@types/bun": "^1.1.3",
22
+ "@types/jest": "^29.5.12",
23
+ "@types/md5": "^2.3.5",
24
+ "typescript": "^5.4.5"
25
+ },
26
+ "peerDependencies": {
27
+ "keyv": "^4.5.4"
28
+ },
29
+ "dependencies": {
30
+ "md5": "^2.3.0",
31
+ "sanitize-filename": "^1.6.3"
32
+ }
33
+ }