Skip to content

Commit

Permalink
openapi-request-validator: Allow to use request validation without pa…
Browse files Browse the repository at this point in the history
…rameters (kogosoftwarellc#382)

* openapi-request-validator: Not throw an error if parameters are not defined

Closes kogosoftwarellc#381

* openapi-request-validator: add a test to check that works without parameters
  • Loading branch information
Javier Blanco Martinez authored and jsdevel committed Mar 8, 2019
1 parent 2759976 commit 2d5cfc5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 15 deletions.
37 changes: 22 additions & 15 deletions packages/openapi-request-validator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,34 @@ export default class OpenAPIRequestValidator
throw new Error(`${loggingKey}missing args argument`);
}

if (!Array.isArray(args.parameters)) {
throw new Error(`${loggingKey}args.parameters must be an Array`);
}

const schemas = convertParametersToJSONSchema(args.parameters);
const errorTransformer =
typeof args.errorTransformer === 'function' && args.errorTransformer;
const errorMapper = errorTransformer
? extendedErrorMapper(errorTransformer)
: toOpenapiValidationError;
const bodySchema = schemas.body;
let bodyValidationSchema;
const headersSchema = lowercasedHeaders(schemas.headers);
const formDataSchema = schemas.formData;
const pathSchema = schemas.path;
const querySchema = schemas.query;
let bodySchema;
let headersSchema;
let formDataSchema;
let pathSchema;
let querySchema;
let isBodyRequired;

if (args.parameters !== undefined) {
if (Array.isArray(args.parameters)) {
const schemas = convertParametersToJSONSchema(args.parameters);
bodySchema = schemas.body;
headersSchema = lowercasedHeaders(schemas.headers);
formDataSchema = schemas.formData;
pathSchema = schemas.path;
querySchema = schemas.query;
isBodyRequired =
// @ts-ignore
args.parameters.filter(byRequiredBodyParameters).length > 0;
} else {
throw new Error(`${loggingKey}args.parameters must be an Array`);
}
}

const v = new Ajv({
allErrors: true,
Expand All @@ -78,13 +90,8 @@ export default class OpenAPIRequestValidator
logger: false
});

let isBodyRequired;
if (args.requestBody) {
isBodyRequired = args.requestBody.required || false;
} else {
isBodyRequired =
// @ts-ignore
args.parameters.filter(byRequiredBodyParameters).length > 0;
}

if (args.customFormats) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module.exports = {
validateArgs: {
requestBody: {
description: 'a test body',
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Test1'
}
}
}
},
schemas: {
Test1: {
properties: {
foo: {
type: 'string'
}
},
required: ['foo']
}
}
},
request: {
body: {
foo: 'asdf'
},
headers: {
'content-type': 'application/json'
}
}
};

0 comments on commit 2d5cfc5

Please sign in to comment.