UNPKG

@sentclose/sentc-nodejs

Version:

End-to-end encryption sdk

107 lines (106 loc) 3.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileSystemStorage = void 0; const fs = require("fs/promises"); const path = require("path"); class FileSystemStorage { constructor(dbName = "sentc_encrypt_files") { this.dbName = dbName; this.isInit = false; this.storageDir = path.join(process.cwd(), this.dbName); } async init() { try { // Create a directory structure if it doesn't exist await fs.mkdir(this.storageDir, { recursive: true }); this.isInit = true; return { status: true }; } catch (e) { return { status: false, err: `FileSystem storage initialization failed: ${e.message}` }; } } // eslint-disable-next-line require-await async getDownloadUrl() { throw new Error("Not implemented"); } // eslint-disable-next-line require-await async cleanStorage() { throw new Error("Not implemented"); } // eslint-disable-next-line require-await async storePart(chunk) { throw new Error("Not implemented"); } async delete(key) { try { const filePath = path.join(this.storageDir, key); // Check if a file exists before trying to delete try { await fs.access(filePath); await fs.unlink(filePath); } catch (accessError) { // File doesn't exist, ignore } } catch (e) { console.error(`Failed to delete item with key ${key}:`, e); throw e; } } async getItem(key) { try { const filePath = path.join(this.storageDir, key); try { await fs.access(filePath); const content = await fs.readFile(filePath, "utf8"); return deserializeWithMaps(content); } catch (accessError) { // File doesn't exist return null; } } catch (e) { console.error(`Failed to get item with key ${key}:`, e); throw e; } } async set(key, item) { try { const filePath = path.join(this.storageDir, key); await fs.writeFile(filePath, serializeWithMaps(item)); } catch (e) { console.error(`Failed to set item with key ${key}:`, e); throw e; } } } exports.FileSystemStorage = FileSystemStorage; function serializeWithMaps(obj) { const replacer = (key, value) => { if (value instanceof Map) { return { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "Map", entries: Array.from(value.entries()) }; } return value; }; return JSON.stringify(obj, replacer); } function deserializeWithMaps(jsonString) { const reviver = (key, value) => { if (value && value.__type === "Map" && Array.isArray(value.entries)) { return new Map(value.entries); } return value; }; return JSON.parse(jsonString, reviver); }