Skip to content

Commit

Permalink
Merge fd014dd into fc70897
Browse files Browse the repository at this point in the history
  • Loading branch information
cdimascio committed Jul 20, 2019
2 parents fc70897 + fd014dd commit ee6626c
Show file tree
Hide file tree
Showing 13 changed files with 1,551 additions and 197 deletions.
25 changes: 1 addition & 24 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
{
"name": "express-openapi-validator",
"version": "1.3.0-rc.3",
"version": "1.3.0-rc.4",
"description": "Automatically validate API requests using an OpenAPI 3 and Express.",
"main": "dist/index.js",
"scripts": {
"compile": "rm -rf dist/ && tsc",
"test": "mocha -r source-map-support/register -r ts-node/register --recursive test/**/*.spec.ts",
"test:coverage": "nyc mocha -r source-map-support/register -r ts-node/register --recursive test/**/*.spec.ts",
"coveralls": "cat coverage/lcov.info | coveralls -v",
"codacy": "cat coverage/lcov.info | codacy-coverage"
"codacy": "cat coverage/lcov.info | codacy-coverage",
"publish": "npm run compile && npm test && npm publish"
},
"repository": {
"url": "https://github.com/cdimascio/express-openapi-validator"
Expand All @@ -27,9 +28,9 @@
"ajv": "^6.10.2",
"js-yaml": "^3.13.1",
"lodash": "^4.17.15",
"lodash.merge": "^4.6.2",
"multer": "^1.4.2",
"ono": "^5.0.1",
"openapi-schema-validator": "^3.0.3",
"openapi-types": "^1.3.5",
"path-to-regexp": "^3.0.0",
"ts-log": "^2.1.4"
Expand Down
50 changes: 12 additions & 38 deletions src/framework/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import OpenAPISchemaValidator from 'openapi-schema-validator';
import { OpenAPIV2, OpenAPIV3 } from 'openapi-types';
import OpenAPISchemaValidator from './openapi.schema.validator';
import BasePath from './base.path';
import {
ConsoleDebugAdapterLogger,
Expand Down Expand Up @@ -44,58 +43,35 @@ export default class OpenAPIFramework implements IOpenAPIFramework {
this.featureType = args.featureType;
this.loggingPrefix = args.name ? `${this.name}: ` : '';
this.logger = args.logger ? args.logger : new ConsoleDebugAdapterLogger();
// monkey patch for node v6:
if (!this.logger.debug) {
this.logger.debug = this.logger.info;
}

[
{ name: 'apiDoc', required: true },
{ name: 'errorTransformer', type: 'function' },
{ name: 'externalSchemas', type: 'object' },
{ name: 'featureType', required: true },
{ name: 'name', required: true },
].forEach(arg => {
if (arg.required && !(arg.name in args)) {
throw new Error(`${this.loggingPrefix}args.${arg.name} is required`);
}

if (arg.type && arg.name in args && typeof args[arg.name] !== arg.type) {
throw new Error(
`${this.loggingPrefix}args.${arg.name} must be a ${
arg.type
} when given`,
);
}

});

// this.enableObjectCoercion = !!args.enableObjectCoercion;
const apiDoc = (typeof args.apiDoc === 'string')
? handleYaml(loadSpecFile(args.apiDoc))
: args.apiDoc
const apiDoc =
typeof args.apiDoc === 'string'
? handleYaml(loadSpecFile(args.apiDoc))
: args.apiDoc;

this.originalApiDoc = apiDoc;

if (!this.originalApiDoc) {
throw new Error(`spec could not be read at ${args.apiDoc}`);
}
this.apiDoc = copy(this.originalApiDoc);

this.basePaths = this.apiDoc.openapi
? getBasePathsFromServers(this.apiDoc.servers)
: [
new BasePath({
url: (this.apiDoc.basePath || '').replace(/\/$/, ''),
}),
];

this.validateApiDoc =
'validateApiDoc' in args ? !!args.validateApiDoc : true;

this.validator = new OpenAPISchemaValidator({
version:
(this.apiDoc as OpenAPIV3.Document).openapi ||
(this.apiDoc as OpenAPIV2.Document).swagger,
version: this.apiDoc.openapi,
extensions: this.apiDoc[`x-${this.name}-schema-extension`],
});

if (this.validateApiDoc) {
const apiDocValidation = this.validator.validate(this.apiDoc);

Expand Down Expand Up @@ -133,9 +109,7 @@ export default class OpenAPIFramework implements IOpenAPIFramework {
JSON.stringify(apiDocValidation.errors, null, ' '),
);
throw new Error(
`${
this.loggingPrefix
}args.apiDoc was invalid after populating paths. See the output.`,
`${this.loggingPrefix}args.apiDoc was invalid after populating paths. See the output.`,
);
}
}
Expand Down
35 changes: 35 additions & 0 deletions src/framework/openapi.schema.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as Ajv from 'ajv';
import * as merge from 'lodash.merge'
import * as draftSchema from 'ajv/lib/refs/json-schema-draft-04.json';
// https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v3.0/schema.json
import * as openapi3Schema from './openapi.v3.schema.json';

export default class OpenAPISchemaValidator{
private validator: Ajv.ValidateFunction;
constructor({
version,
extensions,
}) {
const v = new Ajv({ schemaId: 'auto', allErrors: true });
v.addMetaSchema(draftSchema);
const ver = (version && parseInt(String(version), 10));
if (!ver) throw Error('version missing from OpenAPI specification.');
if (ver != 3) throw Error('OpenAPI v3 specification version is required.')
const schema = merge(
{},
openapi3Schema,
extensions || {}
);
v.addSchema(schema);
this.validator = v.compile(schema);
}

public validate(openapiDoc) {
const valid = this.validator(openapiDoc);
if (!valid) {
return { errors: this.validator.errors };
} else {
return { errors: [] };
}
}
}

0 comments on commit ee6626c

Please sign in to comment.