@mojaloop/ml-schema-transformer-lib
Version:
Shared component for ML schemas translation
157 lines (153 loc) • 6.22 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/lib/validation/index.ts
var validation_exports = {};
__export(validation_exports, {
applyTargetValidation: () => applyTargetValidation,
getApiSpecPath: () => getApiSpecPath,
validateBody: () => validateBody
});
module.exports = __toCommonJS(validation_exports);
var import_path = __toESM(require("path"));
var import_node_cache = __toESM(require("node-cache"));
// src/types/index.ts
var logLevelsMap = {
error: "error",
warn: "warn",
info: "info",
verbose: "verbose",
debug: "debug",
silly: "silly",
audit: "audit",
trace: "trace",
perf: "perf"
};
var logLevelValues = Object.values(logLevelsMap);
// src/lib/validation/validator.ts
var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser"));
var import_openapi_backend = require("openapi-backend");
var import_fast_safe_stringify = __toESM(require("fast-safe-stringify"));
var Validator = class {
apiDoc;
apiSpec;
apiValidator;
ajvOpts = { allErrors: true, coerceTypes: true, strict: false };
/**
* @param apiDoc - The path to the OpenAPI document or the document itself
*/
constructor(apiDoc) {
this.apiDoc = apiDoc;
this.apiSpec = {};
this.apiValidator = {};
}
async initialize() {
this.apiSpec = await import_swagger_parser.default.validate(this.apiDoc);
this.apiValidator = new import_openapi_backend.OpenAPIValidator({ definition: this.apiSpec, ajvOpts: this.ajvOpts });
}
validateRequest(request, returnErrors = false) {
const validation = this.apiValidator.validateRequest(request);
if (validation.errors && validation.errors.length > 0) {
if (returnErrors) return validation.errors;
throw new Error(`Validation errors: ${(0, import_fast_safe_stringify.default)(validation.errors)}`);
}
return true;
}
validateBody(partialRequest, returnErrors = false) {
const { body, path: path2, method } = partialRequest;
const validation = this.apiValidator.validateRequest({ path: path2, method, body, headers: {} });
if (validation.errors) {
const bodyErrors = validation.errors.filter((error) => error.instancePath === "/requestBody");
if (bodyErrors && bodyErrors.length > 0) {
if (returnErrors) return bodyErrors;
throw new Error(`Validation errors: ${(0, import_fast_safe_stringify.default)(bodyErrors)}`);
}
}
return true;
}
validateHeaders(partialRequest, returnErrors = false) {
const { headers, path: path2, method } = partialRequest;
const validation = this.apiValidator.validateRequest({ path: path2, method, headers, body: {} });
if (validation.errors) {
const headersErrors = validation.errors.filter((error) => error.instancePath === "/header");
if (headersErrors && headersErrors.length > 0) {
if (returnErrors) return headersErrors;
throw new Error(`Validation errors: ${(0, import_fast_safe_stringify.default)(headersErrors)}`);
}
}
return true;
}
};
// src/lib/validation/index.ts
var validatorsCache = new import_node_cache.default();
var getApiSpecPath = (apiName, version) => {
let specFile;
switch (apiName) {
case "fspiop" /* FSPIOP */:
specFile = `../docs/fspiop-rest-v${version}-openapi3-snippets.yaml`;
break;
case "iso" /* ISO20022 */:
specFile = `../docs/fspiop-rest-v${version}-ISO20022-openapi3-snippets.yaml`;
break;
default:
throw new Error(`Invalid API name: ${apiName} in getApiSpecPath`);
}
const specPath = import_path.default.join(import_path.default.dirname(require.resolve("@mojaloop/api-snippets")), specFile);
return specPath;
};
var validateBody = async (body, spec) => {
const apiSpecPath = getApiSpecPath(spec.name, spec.version);
let validator = validatorsCache.get(apiSpecPath);
if (!validator) {
validator = new Validator(apiSpecPath);
await validator.initialize();
validatorsCache.set(apiSpecPath, validator);
}
return validator.validateBody({ body, path: spec.path, method: spec.method });
};
var applyTargetValidation = async (params) => {
const { target, options, logger } = params;
if (!options.validateTarget) {
logger.debug("Skipping target validation", { target, options });
return target;
}
const targetSpec = options.applyTargetValidation?.targetSpec;
if (!targetSpec || !targetSpec.name || !targetSpec.path || !targetSpec.method) {
logger.error("Missing or invalid targetSpec in applyTargetValidation options", { target, targetSpec });
throw new Error("Missing or invalid targetSpec in applyTargetValidation options");
}
await validateBody(target.body, targetSpec);
return target;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
applyTargetValidation,
getApiSpecPath,
validateBody
});
//# sourceMappingURL=index.js.map