jsonion
Version:
A lightweight JSON file-based database with nested data access and manipulation capabilities.
82 lines • 2.84 kB
JavaScript
import * as fs from "fs";
import * as path from "path";
import { dbError } from "./types.js";
export function validateOperation(operation, allowedOperations) {
if (!allowedOperations.includes(operation)) {
return {
isValid: false,
error: `Operation '${operation}' is not allowed. Allowed operations: ${allowedOperations.join(", ")}`,
};
}
return { isValid: true };
}
export function validateJsonExtension(filePath, operation = "validation") {
if (!filePath.endsWith(".json")) {
throw new dbError(operation, `File path must end with .json extension: ${filePath}`);
}
}
export function sanitizePath(userPath, baseDir, operation = "validation") {
const resolvedPath = baseDir
? path.resolve(baseDir, userPath)
: path.resolve(userPath);
if (baseDir) {
const resolvedBase = path.resolve(baseDir);
if (!resolvedPath.startsWith(resolvedBase)) {
throw new dbError(operation, `Path traversal detected: ${userPath}`);
}
}
return resolvedPath;
}
export function readJSONFile(filePath, operation = "read") {
try {
const data = fs.readFileSync(filePath, "utf8");
if (!data.trim()) {
return {};
}
return JSON.parse(data);
}
catch (error) {
if (error instanceof SyntaxError) {
throw new dbError(operation, `Invalid JSON in file: ${filePath}`, error);
}
throw new dbError(operation, `Failed to read file: ${filePath}`, error);
}
}
export function writeJSONFile(filePath, data, operation = "write") {
try {
const jsonData = JSON.stringify(data, null, 2);
fs.writeFileSync(filePath, jsonData, { encoding: "utf8", flag: "w" });
}
catch (error) {
throw new dbError(operation, `Failed to write file: ${filePath}`, error);
}
}
export function ensureDirectoryExists(filePath, operation = "create") {
try {
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
catch (error) {
throw new dbError(operation, `Failed to create directory for: ${filePath}`, error);
}
}
export function checkFileExists(filePath, shouldExist, operation) {
const exists = fs.existsSync(filePath);
if (shouldExist && !exists) {
throw new dbError(operation, `File does not exist: ${filePath}`);
}
if (!shouldExist && exists) {
throw new dbError(operation, `File already exists: ${filePath}`);
}
}
export function fileExists(filePath, operation = "validation") {
try {
return fs.existsSync(filePath);
}
catch (error) {
throw new dbError(operation, `Failed to check file existence: ${filePath}`, error);
}
}
//# sourceMappingURL=utils.js.map