Initial import NDC_1C
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.validateNormalized = validateNormalized;
|
||||
exports.assertNormalized = assertNormalized;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const _2020_1 = __importDefault(require("ajv/dist/2020"));
|
||||
const config_1 = require("../config");
|
||||
const validators = new Map();
|
||||
function schemaPath(version) {
|
||||
if (version === "v1") {
|
||||
return path_1.default.resolve(config_1.SCHEMAS_DIR, "normalized_query_v1.json");
|
||||
}
|
||||
if (version === "v2_0_1") {
|
||||
return path_1.default.resolve(config_1.SCHEMAS_DIR, "normalized_query_v2_0_1.json");
|
||||
}
|
||||
if (version === "v2_0_2") {
|
||||
return path_1.default.resolve(config_1.SCHEMAS_DIR, "normalized_query_v2_0_2.json");
|
||||
}
|
||||
return path_1.default.resolve(config_1.SCHEMAS_DIR, "normalized_query_v2.json");
|
||||
}
|
||||
function loadValidator(version) {
|
||||
const cached = validators.get(version);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const raw = fs_1.default.readFileSync(schemaPath(version), "utf-8");
|
||||
const schema = JSON.parse(raw);
|
||||
const ajv = new _2020_1.default({ allErrors: true, strict: false });
|
||||
const compiled = ajv.compile(schema);
|
||||
validators.set(version, compiled);
|
||||
return compiled;
|
||||
}
|
||||
function normalizeAjvErrors(errors) {
|
||||
if (!errors || errors.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return errors.map((item) => `${item.instancePath || "/"} ${item.message ?? "validation error"}`.trim());
|
||||
}
|
||||
function validateNormalized(payload, schemaVersion = "v1") {
|
||||
const check = loadValidator(schemaVersion);
|
||||
const passed = check(payload);
|
||||
return {
|
||||
passed: Boolean(passed),
|
||||
errors: passed ? [] : normalizeAjvErrors(check.errors)
|
||||
};
|
||||
}
|
||||
function assertNormalized(payload, schemaVersion = "v1") {
|
||||
const validation = validateNormalized(payload, schemaVersion);
|
||||
if (!validation.passed) {
|
||||
throw new Error(`Invalid normalized JSON: ${validation.errors.join("; ")}`);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
Reference in New Issue
Block a user