@sinkingsheep/jsondb
Version:
A lightweight JSON-based database for Node.js
49 lines • 2.4 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadCollection = loadCollection;
exports.saveCollection = saveCollection;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
function loadCollection(directory, collectionName) {
return __awaiter(this, void 0, void 0, function* () {
const filePath = path_1.default.join(directory, `${collectionName}.json`);
try {
yield fs_1.promises.mkdir(directory, { recursive: true });
const data = yield fs_1.promises.readFile(filePath, 'utf-8');
const jsonData = JSON.parse(data);
return new Map(Object.entries(jsonData));
}
catch (error) {
if (error.code === 'ENOENT') {
return new Map();
}
throw new Error(`Failed to load collection ${collectionName}: ${error}`);
}
});
}
function saveCollection(directory, collectionName, collection, prettyPrint) {
return __awaiter(this, void 0, void 0, function* () {
const filePath = path_1.default.join(directory, `${collectionName}.json`);
try {
yield fs_1.promises.mkdir(directory, { recursive: true });
const jsonData = JSON.stringify(Object.fromEntries(collection), null, prettyPrint ? 2 : 0);
yield fs_1.promises.writeFile(filePath, jsonData, 'utf-8');
}
catch (error) {
throw new Error(`Failed to save collection ${collectionName}: ${error}`);
}
});
}
//# sourceMappingURL=fileOperations.js.map