UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

44 lines (43 loc) 1.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidateBody = ValidateBody; // FoalTS const core_1 = require("../../core"); const get_ajv_instance_1 = require("./get-ajv-instance"); const helpers_1 = require("./helpers"); /** * Hook factory validating the body of the request against a AJV schema. * * @export * @param {(object | ((controller: any) => object))} schema - Schema used to validate the request body. * @param {{ openapi?: boolean }} [options] - Options to add openapi metadata * @returns {HookDecorator} - The hook. */ function ValidateBody(schema, options) { let validateSchema; function validate(ctx, services) { if (!validateSchema) { const ajvSchema = (0, helpers_1.isFunction)(schema) ? schema(this) : schema; const components = services.get(core_1.OpenApi).getComponents(this); validateSchema = (0, get_ajv_instance_1.getAjvInstance)().compile({ ...ajvSchema, components }); } if (!validateSchema(ctx.request.body)) { return new core_1.HttpResponseBadRequest({ body: validateSchema.errors }); } } const openapi = [ (0, core_1.ApiRequestBody)((c) => ({ content: { 'application/json': { schema: (0, helpers_1.isFunction)(schema) ? schema(c) : schema } }, required: true })), (0, core_1.ApiResponse)(400, { description: 'Bad request.' }) ]; return (0, core_1.Hook)(validate, openapi, options); }