diff --git a/src/context.ts b/src/context.ts new file mode 100644 index 0000000..187f483 --- /dev/null +++ b/src/context.ts @@ -0,0 +1,54 @@ +import { prefixStorage, Storage } from "unstorage"; + +var appStorage: Storage; + +var ContextStore = function (storageSettings) { + appStorage = prefixStorage(storageSettings.storage, storageSettings.appName); +}; + +ContextStore.prototype.open = () => {}; + +ContextStore.prototype.close = () => {}; + +ContextStore.prototype.get = (scope: string, key: string | string[]) => { + if (Array.isArray(key)) { + return Promise.all(key.map((el) => appStorage.getItem(scope + ":" + el))); + } + + return appStorage.getItem(scope + ":" + key); +}; + +ContextStore.prototype.set = ( + scope: string, + key: string | string[], + value: string | string[] +) => { + if (Array.isArray(key)) { + const values = [...value]; + return Promise.all( + key.map((el, index) => + appStorage.setItem(scope + ":" + el, values[index] || null) + ) + ); + } + + return appStorage.setItem(scope + ":" + key, value); +}; + +ContextStore.prototype.keys = (scope: string) => + appStorage + .getKeys(scope) + .then((result) => result.map((el) => el.split(":")[1])); + +ContextStore.prototype.delete = (scope: string) => + appStorage + .getKeys(scope) + .then((result) => + Promise.all(result.map((key) => appStorage.removeItem(key))) + ); + +ContextStore.prototype.clean = (activeNodes) => {}; + +export function contextModule(config) { + return new ContextStore(config); +} diff --git a/src/index.ts b/src/index.ts index 288595e..c62c4d2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from "url"; import { storageModule } from "./storage.js"; import { createStorage } from "unstorage"; import mongodbDriver from "unstorage/drivers/mongodb"; +import { contextModule } from "./context.js"; dotenv.config(); @@ -31,12 +32,15 @@ const settings: LocalSettings = { uiHost: "0.0.0.0", uiPort: parseInt(process.env.PORT) || 8080, credentialSecret: process.env.CREDENTIAL_SECRET || "secret", + //@ts-ignore storageModule: storageModule, + storageSettings: { storage: storage, appName: process.env.APP_NAME || "default", }, + adminAuth: { type: "credentials", users: [ @@ -50,6 +54,17 @@ const settings: LocalSettings = { }, ], }, + + contextStorage: { + unstorage: { + //@ts-ignore + module: contextModule, + config: { + storage: storage, + appName: process.env.APP_NAME || "default", + }, + }, + }, }; const app = express();