@cloud-cli/cli
Version:
CLI for the Cloud CLI project
54 lines (53 loc) • 1.55 kB
JavaScript
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { readJson, writeJson } from './utils.js';
import { createHash } from 'node:crypto';
const extension = '.json';
const sha256 = (string) => createHash('sha256').update(string).digest('hex');
export function getStorage(prefix, computeKey = sha256) {
const dataPath = join(process.cwd(), 'data');
const storagePath = join(dataPath, prefix + extension);
mkdirSync(dataPath, { recursive: true });
let store;
const save = () => writeJson(storagePath, store);
const load = () => (store = readJson(storagePath) || {});
load();
const get = (key) => {
load();
return store[computeKey(key)] || null;
};
const has = (key) => {
load();
return computeKey(key) in store;
};
const set = (key, value) => {
load();
store[computeKey(key)] = value;
save();
return true;
};
const reset = () => {
store = {};
save();
return true;
};
const update = (key, values) => {
load();
const previous = get(key);
const next = Object.assign({}, previous, values);
store[computeKey(key)] = next;
save();
return true;
};
const getAll = () => {
load();
return Object.values(store);
};
const remove = (key) => {
load();
delete store[computeKey(key)];
save();
return true;
};
return { get, set, reset, has, update, getAll, remove };
}