UNPKG

@sentzunhat/zacatl

Version:

A modular, high-performance TypeScript microservice framework for Node.js, featuring layered architecture, dependency injection, and robust validation for building scalable APIs and distributed systems.

47 lines 1.68 kB
import { readFileSync } from 'fs'; import { BadRequestError, NotFoundError, ValidationError } from '../error/index.js'; import { isNodeError, isSyntaxError, isZodError } from '../utils/index.js'; export const loadJSON = (filePath, schema) => { try { const content = readFileSync(filePath, 'utf-8'); const cleanContent = filePath.endsWith('.jsonc') ? content.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '') : content; const data = JSON.parse(cleanContent); if (schema) { return schema.parse(data); } return data; } catch (error) { if (isNodeError(error) && error.code === 'ENOENT') { throw new NotFoundError({ message: `JSON file not found: ${filePath}`, component: 'JSONLoader', operation: 'loadJSON', }); } if (isSyntaxError(error)) { throw new BadRequestError({ message: `Invalid JSON in file: ${filePath}`, reason: error.message, component: 'JSONLoader', operation: 'loadJSON', }); } if (isZodError(error)) { throw new ValidationError({ message: `JSON validation failed for file: ${filePath}`, reason: "Data doesn't match the expected schema", component: 'JSONLoader', operation: 'loadJSON', metadata: { filePath, issues: error.issues, }, }); } throw error; } }; //# sourceMappingURL=json.js.map