/
index.ts
150 lines (136 loc) 路 4.87 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { Application, ErrorRequestHandler, RequestHandler } from 'express';
import * as fs from 'fs';
import * as path from 'path';
const util = require('util');
const jsYaml = require('js-yaml');
import OpenAPIFramework, {
BasePath,
OpenAPIFrameworkArgs,
OpenAPIFrameworkConstructorArgs,
} from './fw';
import OpenAPISchemaValidator from 'openapi-schema-validator';
import OpenAPIRequestValidator, {
OpenAPIRequestValidatorError,
} from 'openapi-request-validator';
import OpenAPIRequestCoercer from 'openapi-request-coercer';
import { OpenAPIResponseValidatorError } from 'openapi-response-validator';
import { SecurityHandlers } from 'openapi-security-handler';
import { OpenAPI, OpenAPIV3 } from 'openapi-types';
import {
OpenAPIFrameworkVisitor,
OpenAPIFrameworkAPIContext,
} from './fw/types';
// import BasePath from './fw/base.path';
export interface OpenApiMiddlewareOpts extends OpenAPIFrameworkArgs {
name: string;
apiSpecPath: string;
}
export function OpenApiMiddleware(opts: OpenApiMiddlewareOpts) {
if (!opts.apiSpecPath) throw new Error('apiSpecPath required');
const apiContents = loadSpecFile(opts.apiSpecPath);
if (!apiContents)
throw new Error(`spec could not be read at ${opts.apiSpecPath}`);
const apiDoc = handleYaml(apiContents);
const framework = createFramework({ ...opts, apiDoc });
this.apiDoc = framework.apiDoc;
this.opts = opts;
this.opts.name = this.opts.name || 'express-middleware-openapi';
this.routeMap = buildRouteMap(framework);
console.log(JSON.stringify(framework.apiDoc, null, 4), framework.basePaths);
console.log(opts);
}
OpenApiMiddleware.prototype.middleware = function() {
return (req, res, next) => {
const { path, method } = req;
if (path && method) {
// TODO add option to enable undocumented routes to pass through without 404
const documentedRoute = this.routeMap[path];
if (!documentedRoute) return res.status(404).end();
// TODO add option to enable undocumented methods to pass through
const schema = documentedRoute[method.toUpperCase()];
if (!schema) return res.status(415).end();
// TODO coercer and request validator fail on null parameters
if (!schema.parameters) {
schema.parameters = [];
}
// Check if route is in map (throw error - option to ignore)
if (this.opts.enableObjectCoercion) {
// this modifies the request object with coerced types
new OpenAPIRequestCoercer({
loggingKey: this.opts.name,
enableObjectCoercion: this.opts.enableObjectCoercion,
parameters: schema.parameters,
}).coerce(req);
}
const validationResult = new OpenAPIRequestValidator({
errorTransformer: this.errorTransformer,
parameters: schema.parameters || [],
requestBody: schema.requestBody,
// schemas: this.apiDoc.definitions, // v2
componentSchemas: this.apiDoc.components // v3
? this.apiDoc.components.schemas
: undefined,
}).validate(req);
if (validationResult && validationResult.errors.length > 0) {
const { errors, status } = validationResult;
console.log('----provide to custom error handler', errors, status);
return res.status(status).json(errors);
}
}
next();
};
};
function createFramework(args: OpenApiMiddlewareOpts): OpenAPIFramework {
const frameworkArgs: OpenAPIFrameworkConstructorArgs = {
featureType: 'middleware',
name: args.name,
...(args as OpenAPIFrameworkArgs),
};
console.log(frameworkArgs);
const framework = new OpenAPIFramework(frameworkArgs);
return framework;
}
function buildRouteMap(framework) {
const routeMap = {};
framework.initialize({
visitApi(ctx: OpenAPIFrameworkAPIContext) {
const apiDoc = ctx.getApiDoc();
for (const bp of ctx.basePaths) {
for (const path of Object.keys(apiDoc.paths)) {
for (const [method, schema] of Object.entries(apiDoc.paths[path])) {
const pathKey = `${bp.path}${path}`;
const methodKey = method.toUpperCase();
const routeMethod = routeMap[pathKey];
if (routeMethod) {
// add a new method
routeMethod[methodKey] = schema;
} else {
// create the path key and add first method
routeMap[pathKey] = { [methodKey]: schema };
}
}
}
}
},
});
return routeMap;
}
function loadSpecFile(filePath) {
if (typeof filePath === 'string') {
const absolutePath = path.resolve(process.cwd(), filePath);
if (fs.existsSync(absolutePath)) {
try {
// json or module
return require(absolutePath);
} catch (e) {
return fs.readFileSync(absolutePath, 'utf8');
}
}
}
return null;
}
function handleYaml(apiDoc) {
return typeof apiDoc === 'string'
? jsYaml.safeLoad(apiDoc, { json: true })
: apiDoc;
}