UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

54 lines (53 loc) 2.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidateHeader = ValidateHeader; const core_1 = require("../../core"); const get_ajv_instance_1 = require("./get-ajv-instance"); const helpers_1 = require("./helpers"); /** * Hook - Validate a specific header against an AJV schema. * * @export * @param {string} name - Header name. * @param {(object | ((controller: any) => object))} [schema={ type: 'string' }] - Schema used to * validate the header. * @param {{ openapi?: boolean, required?: boolean }} [options={}] - Options. * @param {boolean} [options.openapi] - Add OpenApi metadata. * @param {boolean} [options.required] - Specify is the header is optional. * @returns {HookDecorator} The hook. */ function ValidateHeader(name, schema = { type: 'string' }, options = {}) { // tslint:disable-next-line const required = options.required ?? true; name = name.toLowerCase(); 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({ components, properties: { [name]: ajvSchema }, required: required ? [name] : [], type: 'object', }); } if (!validateSchema(ctx.request.headers)) { return new core_1.HttpResponseBadRequest({ headers: validateSchema.errors }); } } const param = { in: 'header', name }; if (required) { param.required = required; } const openapi = [ (0, core_1.ApiParameter)((c) => ({ ...param, schema: (0, helpers_1.isFunction)(schema) ? schema(c) : schema })), (0, core_1.ApiResponse)(400, { description: 'Bad request.' }) ]; return (0, core_1.Hook)(validate, openapi, options); }