-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache-utils.js
More file actions
64 lines (52 loc) · 2.13 KB
/
Copy pathcache-utils.js
File metadata and controls
64 lines (52 loc) · 2.13 KB
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
import { readFile, writeFile } from "fs/promises";
import { isCacheIndexing, cachePath } from "./data/variables.js";
/**
* @description Resets the cache file, indexes the file if config option is true.
*/
export const resetCache = async () => {
const content = {};
if (isCacheIndexing) {
"abcdefghijklmnopqrstuvwxyz0123456789".split("").forEach((value) => (content[value] = {}));
}
await writeFile(cachePath, JSON.stringify(content)).catch((error) => console.error("Error encountered: ", error));
};
/**
* @param {string} hash16byte
* @description Add a hash into the json cache. If hash
* already exists in the cache, the expiration time has
* passed, refresh it.
*/
export const addIntoCache = async (hash16byte) => {
const timestamp = Date.now();
const fileContent = await readFile(cachePath).then((response) => JSON.parse(response));
const cache = isCacheIndexing ? fileContent[hash16byte[hash16byte.length - 1]] : fileContent;
Object.keys(cache).forEach((key) => (cache[key] === hash16byte ? delete cache[key] : null));
cache[timestamp] = hash16byte;
await writeFile(cachePath, JSON.stringify(fileContent)).catch((error) => new Error(error));
};
/**
* @param {string} hash16byte
* @returns {Error | void}
*/
export const removeFromCache = async (hash16byte) => {
const fileContent = await readFile(cachePath).then((response) => JSON.parse(response));
const cache = isCacheIndexing ? fileContent[hash16byte[hash16byte.length - 1]] : fileContent;
let deleted = false;
Object.keys(cache).forEach((key) => {
if (cache[key] === hash16byte) {
delete cache[key];
deleted = true;
}
});
if (!deleted) return new Error("Value does not exist in cache");
await writeFile(cachePath, JSON.stringify(fileContent)).catch((error) => new Error(error));
};
/**
* @param {string} hash16byte
* @returns {boolean}
*/
export const checkInCache = async (hash16byte) => {
const fileContent = await readFile(cachePath).then((response) => JSON.parse(response));
const cache = isCacheIndexing ? fileContent[hash16byte[hash16byte.length - 1]] : fileContent;
return Object.values(cache).includes(hash16byte);
};