Skip to content

Commit 2e61a72

Browse files
authored
added initAsync function to support external $ref (#135)
1 parent 1382f22 commit 2e61a72

4 files changed

Lines changed: 80 additions & 27 deletions

File tree

README.md

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,26 @@ There are no code changes in `[email protected]` compared to `e
1616
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
1717
**Table of Contents** <!-- *generated with [DocToc](https://github.com/thlorenz/doctoc)* -->
1818

19-
- [Installation](#installation)
20-
- [API](#api)
21-
- [openapi-validator-middleware.validate(fastifyOptions)](#openapi-validator-middlewarevalidatefastifyoptions)
22-
- [fastifyOptions](#fastifyoptions)
23-
- [openapi-validator-middleware.init(pathToSwaggerFile, options)](#openapi-validator-middlewareinitpathtoswaggerfile-options)
24-
- [Options](#options)
25-
- [Usage Example](#usage-example)
26-
- [Express](#express)
27-
- [Koa](#koa)
28-
- [Fastify](#fastify)
29-
- [Important Notes](#important-notes)
30-
- [Schema Objects](#schema-objects)
31-
- [Multipart/form-data (files)](#multipartform-data-files)
32-
- [Fastify support](#fastify-support)
33-
- [Koa support](#koa-support)
34-
- [Koa packages](#koa-packages)
35-
- [Known Issues with OpenAPI 3](#known-issues-with-openapi-3)
36-
- [Running Tests](#running-tests)
19+
- [openapi-validator-middleware](#openapi-validator-middleware)
20+
- [Installation](#installation)
21+
- [API](#api)
22+
- [openapi-validator-middleware.validate(fastifyOptions)](#openapi-validator-middlewarevalidatefastifyoptions)
23+
- [fastifyOptions](#fastifyoptions)
24+
- [openapi-validator-middleware.init(pathToSwaggerFile, options)](#openapi-validator-middlewareinitpathtoswaggerfile-options)
25+
- [openapi-validator-middleware.initAsync(pathToSwaggerFile, options)](#openapi-validator-middlewareinitasyncpathtoswaggerfile-options)
26+
- [Options](#options)
27+
- [Usage Example](#usage-example)
28+
- [Express](#express)
29+
- [Koa](#koa)
30+
- [Fastify](#fastify)
31+
- [Important Notes](#important-notes)
32+
- [Schema Objects](#schema-objects)
33+
- [Multipart/form-data (files)](#multipartform-data-files)
34+
- [Fastify support](#fastify-support)
35+
- [Koa support](#koa-support)
36+
- [Koa packages](#koa-packages)
37+
- [Known Issues with OpenAPI 3](#known-issues-with-openapi-3)
38+
- [Running Tests](#running-tests)
3739

3840
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
3941

@@ -69,7 +71,17 @@ Initialize the middleware using a swagger definition.
6971
The function executes synchronously and does not return anything.
7072

7173
- `pathToSwaggerFile`: Path to the swagger definition.
72-
- `options`: Additional options for the middleware (see below).
74+
- `options`: Additional options for the middleware ([see below](#options)).
75+
76+
### openapi-validator-middleware.initAsync(pathToSwaggerFile, options)
77+
78+
Initialize the middleware using a swagger definition.
79+
The function executes asynchronously and the resolved promise does not return anything.
80+
81+
This Initilaztion function also supports schema with references to external files.
82+
83+
- `pathToSwaggerFile`: Path to the swagger definition.
84+
- `options`: Additional options for the middleware ([see below](#options)).
7385

7486
#### Options
7587

src/middleware.js

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,24 @@ let schemaEndpointResolver;
1313
let validationMiddleware;
1414

1515
function init(swaggerPath, options) {
16+
_baseInit(swaggerPath, options);
17+
// build schema for requests only
18+
const schemaBuilderOptions = Object.assign({}, options, { buildRequests: true, buildResponses: false });
19+
schemas = apiSchemaBuilder.buildSchemaSync(swaggerPath, schemaBuilderOptions);
20+
}
21+
22+
async function initAsync(swaggerPath, options){
23+
_baseInit(swaggerPath, options);
24+
// build schema for requests only
25+
const schemaBuilderOptions = Object.assign({}, options, { buildRequests: true, buildResponses: false });
26+
schemas = await apiSchemaBuilder.buildSchema(swaggerPath, schemaBuilderOptions);
27+
}
28+
29+
function validate(...args) {
30+
return validationMiddleware(...args);
31+
}
32+
33+
function _baseInit(swaggerPath, options) {
1634
middlewareOptions = options || {};
1735
const frameworkToLoad = allowedFrameworks.find((frameworkName) => {
1836
return middlewareOptions.framework === frameworkName;
@@ -21,14 +39,6 @@ function init(swaggerPath, options) {
2139
framework = frameworkToLoad ? require(`./frameworks/${frameworkToLoad}`) : require('./frameworks/express');
2240
validationMiddleware = framework.getValidator(_validateRequest);
2341
schemaEndpointResolver = new SchemaEndpointResolver();
24-
25-
// build schema for requests only
26-
const schemaBuilderOptions = Object.assign({}, options, { buildRequests: true, buildResponses: false });
27-
schemas = apiSchemaBuilder.buildSchemaSync(swaggerPath, schemaBuilderOptions);
28-
}
29-
30-
function validate(...args) {
31-
return validationMiddleware(...args);
3242
}
3343

3444
function _getContentType(headers) {
@@ -90,6 +100,7 @@ function _validateParams(requestOptions) {
90100

91101
module.exports = {
92102
init,
103+
initAsync,
93104
validate,
94105
InputValidationError
95106
};

test/express/middleware-test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
const chai = require('chai'),
44
expect = chai.expect,
5+
assert = chai.assert,
56
chaiSinon = require('sinon-chai'),
67
request = require('supertest');
78
chai.use(chaiSinon);
@@ -20,6 +21,24 @@ describe('input-validation middleware tests - Express', function () {
2021
middleware.init('test/pet-store-swagger.yaml');
2122
});
2223
});
24+
describe('initAsync function tests', async function () {
25+
it('should throw an error in case the file doesn\'t exists', async function () {
26+
const middleware = require('../../src/middleware');
27+
try {
28+
await middleware.initAsync('test/pet-store-swagger1.yaml');
29+
assert.fail('no error was thrown');
30+
} catch (err) { }
31+
});
32+
it('should resolve without formats', async function () {
33+
const rewire = require('rewire');
34+
const middleware = rewire('../../src/middleware');
35+
try {
36+
await middleware.initAsync('test/pet-store-swagger.yaml');
37+
} catch (err){
38+
assert.fail('unexpected error: ' + err.message);
39+
}
40+
});
41+
});
2342
describe('Simple server - no options', function () {
2443
let app;
2544
before(function () {

types/index.d.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@ declare function init(schemaPath: string, options?: ajvValidatorOptions): void;
1010
declare function init(jsonSchema: Object, options?: ajvValidatorOptions): void;
1111
export { init };
1212

13+
/**
14+
* Initialize the input validation middleware by
15+
* providing it with the swagger file path and
16+
* configuration options. This function should be called
17+
* and awaited before using `validate` middleware.
18+
* This init variant support loading of external references.
19+
*/
20+
declare function initAsync(schemaPath: string, options?: ajvValidatorOptions): Promise<void>;
21+
declare function initAsync(jsonSchema: Object, options?: ajvValidatorOptions): Promise<void>;
22+
export { initAsync };
23+
1324
/**
1425
* Middleware that validates the request against the swagger
1526
* file, according to the request method and route

0 commit comments

Comments
 (0)