/************************************************************************* * * Troven CONFIDENTIAL * __________________ * * (c) 2017-2020 Troven Ventures Pty Ltd * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Troven Pty Ltd and its licensors, * if any. The intellectual and technical concepts contained * herein are proprietary to Troven Pty Ltd * and its suppliers and may be covered by International and Regional Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Troven Pty Ltd. */ import {IOperation, IChassisPolicy} from "../interfaces"; import { Response, NextFunction } from "express"; import { ISchemaValidated } from "../interfaces/ISchemaValidated"; import { Validator } from "jsonschema"; import { OpenAPIPlugin } from "../plugins"; export default class Validate implements IChassisPolicy { name = "api.validate"; title = "Validate policy"; fn(_op: IOperation, _options: any): Function { return function (_req: any, _res: Response, next: NextFunction) { let model = _req.json || _req.body; let invalid = this.validateBody(_op, model); if (invalid) { _res.status(400); _res.send( { code: "api:body:invalid", errors: invalid.errors } ); return; } return next(); }; } static validateBody(_op: IOperation, model: any): ISchemaValidated { let openapi = _op.context.plugins.get("openapi") as OpenAPIPlugin; let raw_schema = _op.getRequestSchema(); let body_schema = openapi.openapi.schemas.deref(raw_schema, { id: true }); return this.validate(model, body_schema); } static validate(model: any, schema: any): ISchemaValidated { if (!schema) return null; // console.log("validateModel.schema: %s @ %s --> %j", op.actionId, op.resource, schema); let validator = new Validator(); let valid: ISchemaValidated = validator.validate(model, schema); if (!valid.errors || valid.errors.length==0) return null; return { errors: valid.errors }; } }