@foal/core
Version:
Full-featured Node.js framework, with no complexity
49 lines (48 loc) • 1.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidatePathParam = ValidatePathParam;
// FoalTS
const core_1 = require("../../core");
const get_ajv_instance_1 = require("./get-ajv-instance");
const helpers_1 = require("./helpers");
/**
* Hook - Validate a specific path parameter against an AJV schema.
*
* @export
* @param {string} name - Path parameter name.
* @param {(object | ((controller: any) => object))} schema - Schema used to
* validate the path parameter.
* @param {{ openapi?: boolean }} [options={}] - Options.
* @param {boolean} [options.openapi] - Add OpenApi metadata.
* @returns {HookDecorator} The hook.
*/
function ValidatePathParam(name, 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({
components,
properties: {
[name]: ajvSchema
},
required: [name],
type: 'object',
});
}
if (!validateSchema(ctx.request.params)) {
return new core_1.HttpResponseBadRequest({ pathParams: validateSchema.errors });
}
}
const openapi = [
(0, core_1.ApiParameter)((c) => ({
in: 'path',
name,
required: true,
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);
}