@mojaloop/ml-schema-transformer-lib
Version:
Shared component for ML schemas translation
58 lines • 2.18 kB
JavaScript
// src/lib/validation/validator.ts
import SwaggerParser from "@apidevtools/swagger-parser";
import { OpenAPIValidator } from "openapi-backend";
import stringify from "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 SwaggerParser.validate(this.apiDoc);
this.apiValidator = new 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: ${stringify(validation.errors)}`);
}
return true;
}
validateBody(partialRequest, returnErrors = false) {
const { body, path, method } = partialRequest;
const validation = this.apiValidator.validateRequest({ path, 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: ${stringify(bodyErrors)}`);
}
}
return true;
}
validateHeaders(partialRequest, returnErrors = false) {
const { headers, path, method } = partialRequest;
const validation = this.apiValidator.validateRequest({ path, 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: ${stringify(headersErrors)}`);
}
}
return true;
}
};
export {
Validator
};
//# sourceMappingURL=validator.mjs.map