/
index.ts
264 lines (239 loc) 路 7.64 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import * as _ from 'lodash';
import {
// Application,
// ErrorRequestHandler,
// RequestHandler,
ExpressApp,
} 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 from 'openapi-request-validator'; // OpenAPIRequestValidatorError,
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 { ValidationError } from 'ajv';
export interface ErrorResponse {
statusCode: number;
error: any;
}
export interface OpenApiMiddlewareOpts extends OpenAPIFrameworkArgs {
name: string;
apiSpecPath: string;
errorTransform?: (validationResult: any) => ErrorResponse;
}
const unsupportedMediaTypeError = {
statusCode: 415,
errors: [
{
status: 415,
message: 'unsupported media type',
},
],
};
const notFoundError = {
status: 404,
errors: [
{
status: 404,
message: 'not found',
},
],
};
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}`);
opts.enableObjectCoercion = opts.enableObjectCoercion || true;
opts.name = opts.name || 'express-middleware-openapi';
const apiDoc = handleYaml(apiContents);
const framework = createFramework({ ...opts, apiDoc });
this.opts = opts;
this.apiDoc = framework.apiDoc;
this.routes = buildRoutes(framework);
this.routeMap = this.routes.reduce((a, r) => {
const routeMethod = a[r.expressRoute];
if (routeMethod) {
routeMethod[r.method] = r.schema;
} else {
a[r.expressRoute] = { [r.method]: r.schema };
}
return a;
}, {});
// console.log(JSON.stringify(framework.apiDoc, null, 4), framework.basePaths);
console.log(opts);
}
OpenApiMiddleware.prototype.install = function(app: ExpressApp) {
const noPathParamRoutes = [];
const pathParms = [];
for (const route of this.routes) {
if (route.pathParams.length === 0) {
noPathParamRoutes.push(route.expressRoute);
} else {
pathParms.push(...route.pathParams);
}
}
// install param on routes with paths
for (const p of _.uniq(pathParms)) {
app.param(p, this.middleware()); //pathParamMiddleware);
}
// install use on routes without paths
app.all(_.uniq(noPathParamRoutes), this.middleware());
// app.use(_.uniq(noPathParamRoutes), this.middleware());
};
OpenApiMiddleware.prototype.middleware = function() {
return (req, res, next) => {
const { path: rpath, method, route } = req;
var path = Array.isArray(route.path)
? route.path.find(() => rpath)
: route.path || rpath;
if (path && method) {
// TODO add option to enable undocumented routes to pass through without 404
const documentedRoute = this.routeMap[path];
if (!documentedRoute) {
const { statusCode, error } = this._transformValidationResult(
notFoundError
);
return res.status(statusCode).json(error);
// return res.status(404).end();
}
// TODO add option to enable undocumented methods to pass through
const schema = documentedRoute[method.toUpperCase()];
if (!schema) {
const { statusCode, error } = this._transformValidationResult(
unsupportedMediaTypeError
);
return res.status(statusCode).json(error);
}
// 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 { statusCode, error } = this._transformValidationResult(
validationResult
);
return res.status(statusCode).json(error);
// const { errors, status } = validationResult;
// const transform =
// this.opts.errorTransform ||
// (v => ({
// statusCode: v.status,
// error: { errors: v.errors },
// }));
// const { statusCode, error } = transform(validationResult);
// return res.status(statusCode).json(error);
}
}
next();
};
};
OpenApiMiddleware.prototype._transformValidationResult = function(
validationResult
) {
if (validationResult && validationResult.errors.length > 0) {
const transform =
this.opts.errorTransform ||
(v => ({
statusCode: v.status,
error: { errors: v.errors },
}));
return transform(validationResult);
}
};
function toExpressParams(part) {
return part.replace(/\{([^}]+)}/g, ':$1');
}
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 buildRoutes(framework) {
const routes = [];
framework.initialize({
visitApi(ctx: OpenAPIFrameworkAPIContext) {
const apiDoc = ctx.getApiDoc();
for (const bp of ctx.basePaths) {
for (const [path, methods] of Object.entries(apiDoc.paths)) {
for (const [method, schema] of Object.entries(methods)) {
const pathParams = new Set();
for (const param of schema.parameters || []) {
if (param.in === 'path') {
pathParams.add(param.name);
}
}
const openApiRoute = `${bp.path}${path}`;
const expressRoute = openApiRoute
.split('/')
.map(toExpressParams)
.join('/');
routes.push({
expressRoute,
openApiRoute,
method: method.toUpperCase(),
pathParams: Array.from(pathParams),
schema,
});
}
}
}
},
});
return routes;
}
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;
}