express-openapi-validator
Advanced tools
Comparing version 4.12.4 to 4.12.5
@@ -490,8 +490,12 @@ import * as ajv from 'ajv'; | ||
} | ||
interface ErrorHeaders { | ||
Allow?: string; | ||
} | ||
export declare class HttpError extends Error implements ValidationError { | ||
status: number; | ||
path?: string; | ||
name: string; | ||
message: string; | ||
headers?: ErrorHeaders; | ||
errors: ValidationErrorItem[]; | ||
path?: string; | ||
name: string; | ||
constructor(err: { | ||
@@ -502,2 +506,3 @@ status: number; | ||
message?: string; | ||
headers?: ErrorHeaders; | ||
errors?: ValidationErrorItem[]; | ||
@@ -530,2 +535,3 @@ }); | ||
message?: string; | ||
headers?: ErrorHeaders; | ||
overrideStatus?: number; | ||
@@ -532,0 +538,0 @@ }); |
@@ -23,2 +23,3 @@ "use strict"; | ||
constructor(err) { | ||
var _a; | ||
super(err.name); | ||
@@ -29,11 +30,9 @@ this.name = err.name; | ||
this.message = err.message; | ||
this.errors = | ||
err.errors == undefined | ||
? [ | ||
{ | ||
path: err.path, | ||
message: err.message, | ||
}, | ||
] | ||
: err.errors; | ||
this.headers = err.headers; | ||
this.errors = (_a = err.errors) !== null && _a !== void 0 ? _a : [ | ||
{ | ||
path: err.path, | ||
message: err.message, | ||
}, | ||
]; | ||
} | ||
@@ -93,2 +92,3 @@ static create(err) { | ||
message: err.message, | ||
headers: err.headers, | ||
}); | ||
@@ -95,0 +95,0 @@ } |
@@ -7,2 +7,3 @@ "use strict"; | ||
const types_1 = require("../framework/types"); | ||
const schema_preprocessor_1 = require("./parsers/schema.preprocessor"); | ||
function applyOpenApiMetadata(openApiContext, responseApiDoc) { | ||
@@ -24,2 +25,7 @@ return (req, res, next) => { | ||
message: `${req.method} method not allowed`, | ||
headers: { | ||
Allow: Object.keys(openApiContext.openApiRouteMap[openApiRoute]) | ||
.filter((key) => schema_preprocessor_1.httpMethods.has(key.toLowerCase())) | ||
.join(', '), | ||
}, | ||
}); | ||
@@ -26,0 +32,0 @@ } |
@@ -75,7 +75,7 @@ "use strict"; | ||
} | ||
const schemaPoperties = validator.allSchemaProperties; | ||
const mutator = new req_parameter_mutator_1.RequestParameterMutator(this.ajv, apiDoc, path, schemaPoperties); | ||
const schemaProperties = validator.allSchemaProperties; | ||
const mutator = new req_parameter_mutator_1.RequestParameterMutator(this.ajv, apiDoc, path, schemaProperties); | ||
mutator.modifyRequest(req); | ||
if (!allowUnknownQueryParameters) { | ||
this.processQueryParam(req.query, schemaPoperties.query, securityQueryParam); | ||
this.processQueryParam(req.query, schemaProperties.query, securityQueryParam); | ||
} | ||
@@ -93,6 +93,6 @@ const cookies = req.cookies | ||
const discriminator = (_d = (_c = schemaBody === null || schemaBody === void 0 ? void 0 : schemaBody.properties) === null || _c === void 0 ? void 0 : _c.body) === null || _d === void 0 ? void 0 : _d._discriminator; | ||
const discriminatorValdiator = this.discriminatorValidator(req, discriminator); | ||
const validatorBody = discriminatorValdiator !== null && discriminatorValdiator !== void 0 ? discriminatorValdiator : validator.validatorBody; | ||
const discriminatorValidator = this.discriminatorValidator(req, discriminator); | ||
const validatorBody = discriminatorValidator !== null && discriminatorValidator !== void 0 ? discriminatorValidator : validator.validatorBody; | ||
const valid = validator.validatorGeneral(data); | ||
const validBody = validatorBody(discriminatorValdiator ? data.body : data); | ||
const validBody = validatorBody(discriminatorValidator ? data.body : data); | ||
if (valid && validBody) { | ||
@@ -119,3 +119,3 @@ next(); | ||
const { options, property, validators } = discriminator; | ||
const discriminatorValue = req.body[property]; // TODO may not alwasy be in this position | ||
const discriminatorValue = req.body[property]; // TODO may not always be in this position | ||
if (options.find((o) => o.option === discriminatorValue)) { | ||
@@ -122,0 +122,0 @@ return validators[discriminatorValue]; |
@@ -9,3 +9,3 @@ "use strict"; | ||
var _d, _e, _f; | ||
// TODO move the folllowing 3 check conditions to a dedicated upstream middleware | ||
// TODO move the following 3 check conditions to a dedicated upstream middleware | ||
if (!req.openapi) { | ||
@@ -18,3 +18,3 @@ // this path was not found in open api and | ||
const openapi = req.openapi; | ||
// use the local security object or fallbac to api doc's security or undefined | ||
// use the local security object or fallback to api doc's security or undefined | ||
const securities = (_d = openapi.schema.security) !== null && _d !== void 0 ? _d : apiDoc.security; | ||
@@ -111,3 +111,3 @@ const path = openapi.openApiRoute; | ||
if (Util.isEmptyObject(s)) { | ||
// anonumous security | ||
// anonymous security | ||
return [{ success: true }]; | ||
@@ -114,0 +114,0 @@ } |
@@ -60,3 +60,3 @@ "use strict"; | ||
else if (style === 'deepObject') { | ||
this.handleDeepObject(req, queryString, name); | ||
this.handleDeepObject(req, queryString, name, schema); | ||
} | ||
@@ -80,6 +80,29 @@ else { | ||
} | ||
handleDeepObject(req, qs, name) { | ||
handleDeepObject(req, qs, name, schema) { | ||
var _a; | ||
const getDefaultSchemaValue = () => { | ||
let defaultValue; | ||
if (schema.default !== undefined) { | ||
defaultValue = schema.default; | ||
} | ||
else { | ||
['allOf', 'oneOf', 'anyOf'].forEach((key) => { | ||
if (schema[key]) { | ||
schema[key].forEach((s) => { | ||
if (s.$ref) { | ||
const compiledSchema = this.ajv.getSchema(s.$ref); | ||
// as any -> https://stackoverflow.com/a/23553128 | ||
defaultValue = defaultValue === undefined ? compiledSchema.schema.default : defaultValue; | ||
} | ||
else { | ||
defaultValue = defaultValue === undefined ? s.default : defaultValue; | ||
} | ||
}); | ||
} | ||
}); | ||
} | ||
return defaultValue; | ||
}; | ||
if (!((_a = req.query) === null || _a === void 0 ? void 0 : _a[name])) { | ||
req.query[name] = {}; | ||
req.query[name] = getDefaultSchemaValue(); | ||
} | ||
@@ -86,0 +109,0 @@ this.parseJsonAndMutateRequest(req, 'query', name); |
import { OpenAPIV3, Options, ValidateResponseOpts } from '../../framework/types'; | ||
export declare const httpMethods: Set<string>; | ||
export declare class SchemaPreprocessor { | ||
@@ -3,0 +4,0 @@ private ajv; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SchemaPreprocessor = void 0; | ||
exports.SchemaPreprocessor = exports.httpMethods = void 0; | ||
const cloneDeep = require("lodash.clonedeep"); | ||
@@ -27,3 +27,3 @@ const _get = require("lodash.get"); | ||
} | ||
const httpMethods = new Set([ | ||
exports.httpMethods = new Set([ | ||
'get', | ||
@@ -81,3 +81,3 @@ 'put', | ||
for (const method of Object.keys(pathItem)) { | ||
if (httpMethods.has(method)) { | ||
if (exports.httpMethods.has(method)) { | ||
const operation = pathItem[method]; | ||
@@ -84,0 +84,0 @@ // Adds path declared parameters to the schema's parameters list |
@@ -13,3 +13,3 @@ import { Application, Router } from 'express'; | ||
installPathParams(app: Application | Router, context: OpenApiContext): void; | ||
private metadataMiddlware; | ||
private metadataMiddleware; | ||
private multipartMiddleware; | ||
@@ -16,0 +16,0 @@ private securityMiddleware; |
@@ -123,3 +123,3 @@ "use strict"; | ||
.then(({ context, responseApiDoc }) => { | ||
metamw = metamw || this.metadataMiddlware(context, responseApiDoc); | ||
metamw = metamw || this.metadataMiddleware(context, responseApiDoc); | ||
return metamw(req, res, next); | ||
@@ -208,3 +208,3 @@ }) | ||
} | ||
metadataMiddlware(context, responseApiDoc) { | ||
metadataMiddleware(context, responseApiDoc) { | ||
return middlewares.applyOpenApiMetadata(context, responseApiDoc); | ||
@@ -293,6 +293,6 @@ } | ||
base_serdes_1.defaultSerDes.forEach((currentDefaultSerDes) => { | ||
let defautSerDesOverride = options.serDes.find((currentOptionSerDes) => { | ||
let defaultSerDesOverride = options.serDes.find((currentOptionSerDes) => { | ||
return currentDefaultSerDes.format === currentOptionSerDes.format; | ||
}); | ||
if (!defautSerDesOverride) { | ||
if (!defaultSerDesOverride) { | ||
options.serDes.push(currentDefaultSerDes); | ||
@@ -299,0 +299,0 @@ } |
{ | ||
"name": "express-openapi-validator", | ||
"version": "4.12.4", | ||
"version": "4.12.5", | ||
"description": "Automatically validate API requests and responses with OpenAPI 3 and Express.", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
@@ -99,3 +99,2 @@ # 🦋 express-openapi-validator | ||
const path = require('path'); | ||
const bodyParser = require('body-parser'); | ||
const http = require('http'); | ||
@@ -109,5 +108,5 @@ const app = express(); | ||
// Must be specified prior to endpoints in 5. | ||
app.use(bodyParser.json()); | ||
app.use(bodyParser.text()); | ||
app.use(bodyParser.urlencoded({ extended: false })); | ||
app.use(express.json()); | ||
app.use(express.text()); | ||
app.use(express.urlencoded({ extended: false })); | ||
@@ -178,3 +177,3 @@ // 3. (optionally) Serve the OpenAPI spec | ||
- First, specifiy the `operationHandlers` option to set the base directory that contains your operation handler files. | ||
- First, specify the `operationHandlers` option to set the base directory that contains your operation handler files. | ||
@@ -212,3 +211,3 @@ ```javascript | ||
module.exports = { | ||
// the express handler implementaiton for ping | ||
// the express handler implementation for ping | ||
ping: (req, res) => res.status(200).send('pong'), | ||
@@ -283,3 +282,3 @@ }; | ||
# x-eov-operation-id may be used to specify the operation id | ||
# Used when operationId is omiited. Overrides operationId when both are specified | ||
# Used when operationId is omitted. Overrides operationId when both are specified | ||
x-eov-operation-id: ping | ||
@@ -527,3 +526,3 @@ # specifies the path to the operation handler. | ||
Specifies the path to an OpenAPI 3 specification or a JSON object representing the OpenAPI 3 specificiation | ||
Specifies the path to an OpenAPI 3 specification or a JSON object representing the OpenAPI 3 specification | ||
@@ -610,3 +609,3 @@ ```javascript | ||
Determines whether to keep or remove additional properties in request body or to fail validation if schema has `additionalProperties` set to `false`. For futher details, refer to [AJV documentation](https://ajv.js.org/docs/validation.html#removing-additional-properties) | ||
Determines whether to keep or remove additional properties in request body or to fail validation if schema has `additionalProperties` set to `false`. For further details, refer to [AJV documentation](https://ajv.js.org/docs/validation.html#removing-additional-properties) | ||
@@ -694,3 +693,3 @@ - `false` (**default**) - not to remove additional properties | ||
*Warning:* e certain your spec is valid. And be sure you know what you're doing! express-openapi-validator _*expects*_ are valid spec. If incorrect, the validator will behave erradically and/or throw Javascript errors. | ||
*Warning:* Be certain your spec is valid. And be sure you know what you're doing! express-openapi-validator _*expects*_ a valid spec. If incorrect, the validator will behave erratically and/or throw Javascript errors. | ||
@@ -702,3 +701,3 @@ - `true` (**default**) - validate the OpenAPI specification. | ||
Defines a list of custome formats. | ||
Defines a list of custom formats. | ||
@@ -741,3 +740,3 @@ - `[{ ... }]` - array of custom format objects. Each object must have the following properties: | ||
- `"fast"` (**default**) - only validate syntax, but not semantics. E.g. `2010-13-30T23:12:35Z` will pass validation eventhough it contains month 13. | ||
- `"fast"` (**default**) - only validate syntax, but not semantics. E.g. `2010-13-30T23:12:35Z` will pass validation even though it contains month 13. | ||
- `"full"` - validate both syntax and semantics. Illegal dates will not pass. | ||
@@ -810,3 +809,3 @@ - `false` - do not validate formats at all. | ||
Additionally, if you want to change how modules are resolved e.g. use dot deliminted operation ids e.g. `path.to.module.myFunction`, you may optionally add a custom `resolver`. See [documentation and example](https://github.com/cdimascio/express-openapi-validator/tree/master/examples/5-custom-operation-resolver) | ||
Additionally, if you want to change how modules are resolved e.g. use dot delimited operation ids e.g. `path.to.module.myFunction`, you may optionally add a custom `resolver`. See [documentation and example](https://github.com/cdimascio/express-openapi-validator/tree/master/examples/5-custom-operation-resolver) | ||
@@ -848,3 +847,3 @@ - `string` - the base directory containing operation handlers | ||
# x-eov-operation-id may be used to specify the operation id | ||
# Used when operationId is omiited. Overrides operationId when both are specified | ||
# Used when operationId is omitted. Overrides operationId when both are specified | ||
x-eov-operation-id: ping | ||
@@ -925,3 +924,3 @@ # specifies the path to the operation handler. | ||
Determines whether the validator should coerce value types to match the those defined in the OpenAPI spec. This option applies **only** to path params, query strings, headers, and cookies. _It is **highly unlikley** that will want to disable this. As such this option is deprecated and will be removed in the next major version_ | ||
Determines whether the validator should coerce value types to match the those defined in the OpenAPI spec. This option applies **only** to path params, query strings, headers, and cookies. _It is **highly unlikely** that you will want to disable this. As such this option is deprecated and will be removed in the next major version_ | ||
@@ -956,3 +955,3 @@ - `true` (**default**) - coerce scalar data types. | ||
> **Note:** security `handlers` are an optional component. security `handlers` provide a convenience, whereby the request, declared scopes, and the security schema itself are provided as parameters to each security `handlers` callback that you define. The code you write in each callback can then perform authentication and authorization checks. **_Note that the same can be achieved using standard Express middleware_. The difference** is that security `handlers` provide you the OpenAPI schema data described in your specification\_. Ulimately, this means, you don't have to duplicate that information in your code. | ||
> **Note:** security `handlers` are an optional component. security `handlers` provide a convenience, whereby the request, declared scopes, and the security schema itself are provided as parameters to each security `handlers` callback that you define. The code you write in each callback can then perform authentication and authorization checks. **_Note that the same can be achieved using standard Express middleware_. The difference** is that security `handlers` provide you the OpenAPI schema data described in your specification\_. Ultimately, this means, you don't have to duplicate that information in your code. | ||
@@ -1162,3 +1161,3 @@ > All in all, security `handlers` are purely optional and are provided as a convenience. | ||
Using the following OpenAPI 3.x defintion | ||
Using the following OpenAPI 3.x definition | ||
@@ -1176,3 +1175,3 @@ ```yaml | ||
With the following Express route defintion | ||
With the following Express route definition | ||
@@ -1214,6 +1213,2 @@ ```javascript | ||
**Q:** I upgraded from from v2 to v3 and validation no longer works. How do I fix it? | ||
**A**: In version 2.x.x, the `install` method was executed synchronously, in 3.x it's executed asynchronously. To get v2 behavior in v3, use the `installSync` method. See the [synchronous](#synchronous) section for details. | ||
**Q:** Can I use `express-openapi-validator` with `swagger-ui-express`? | ||
@@ -1220,0 +1215,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
279889
5700
1323