UNPKG

koas-core

Version:

> [Koa][] + [OpenAPI Specification][] = Koas

83 lines (82 loc) 3.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createValidator = exports.SchemaValidationError = void 0; const jsonschema_1 = require("jsonschema"); const jsonRefs_1 = require("./jsonRefs"); /** * Iterate over object entries. * * @param object - The object to iterate over. This may be null. * @param iterator - A function which will be called with the key and value. */ function iter(object, iterator) { if (object) { for (const [key, value] of Object.entries(object)) { iterator(key, value); } } } /** * An error that’s thrown if JSON schema validation fails. */ class SchemaValidationError extends Error { /** * @param message - The error message to throw. * @param options - The error options. */ constructor(message, { result, status = 400 }) { super(message); this.name = 'SchemaValidationError'; this.status = status; this.result = result; } } exports.SchemaValidationError = SchemaValidationError; /** * @param document - THe OpenAPI document to create a JSON schema validator for. * @returns A configured JSON schema validator. */ function createValidator({ components = {} }) { const validator = new jsonschema_1.Validator(); // Register OpenAPI formats validator.customFormats.int32 = () => true; validator.customFormats.int64 = () => true; validator.customFormats.float = () => true; validator.customFormats.double = () => true; validator.customFormats.byte = () => true; validator.customFormats.binary = () => true; validator.customFormats.password = () => true; /** * Add schemas from a record of JSON schema property wrappers. * * @param wrappers - The rescord that holds the JSON schema wrappers * @param prefix - The prefix of the wrapper. */ function procesSchemaWrapper(wrappers, prefix) { iter(wrappers, (key, wrapper) => { if ('schema' in wrapper) { validator.addSchema(wrapper.schema, `${prefix}/${(0, jsonRefs_1.escapeJsonPointer)(key)}/schema`); } }); } iter(components.schemas, (key, schema) => { validator.addSchema(schema, `#/components/schemas/${(0, jsonRefs_1.escapeJsonPointer)(key)}`); }); procesSchemaWrapper(components.headers, '#/components/headers'); procesSchemaWrapper(components.parameters, '#/components/parameters'); iter(components.requestBodies, (key, requestBody) => { if ('content' in requestBody) { procesSchemaWrapper(requestBody.content, `#/components/requestBodies/${(0, jsonRefs_1.escapeJsonPointer)(key)}/content`); } }); iter(components.responses, (key, response) => { if ('headers' in response) { procesSchemaWrapper(response.headers, `#/components/responses/${(0, jsonRefs_1.escapeJsonPointer)(key)}/headers`); } if ('content' in response) { procesSchemaWrapper(response.content, `#/components/responses/${(0, jsonRefs_1.escapeJsonPointer)(key)}/content`); } }); return validator; } exports.createValidator = createValidator;