/
openapi.spec.loader.ts
75 lines (68 loc) 路 2.11 KB
/
openapi.spec.loader.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
import * as _ from 'lodash';
import OpenAPIFramework, {
OpenAPIFrameworkArgs,
OpenAPIFrameworkConstructorArgs,
} from './framework';
import { OpenAPIFrameworkAPIContext } from './framework/types';
export class OpenApiSpecLoader {
private opts: OpenAPIFrameworkArgs;
constructor(opts: OpenAPIFrameworkArgs) {
this.opts = opts;
}
load() {
const framework = this.createFramework(this.opts);
const apiDoc = framework.apiDoc;
const routes = this.discoverRoutes(framework);
return {
apiDoc,
routes,
};
}
private createFramework(args: OpenAPIFrameworkArgs): OpenAPIFramework {
const frameworkArgs: OpenAPIFrameworkConstructorArgs = {
featureType: 'middleware',
name: 'express-middleware-openapi',
...(args as OpenAPIFrameworkArgs),
};
console.log(frameworkArgs);
const framework = new OpenAPIFramework(frameworkArgs);
return framework;
}
private discoverRoutes(framework) {
const routes = [];
const toExpressParams = this.toExpressParams;
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;
}
private toExpressParams(part) {
return part.replace(/\{([^}]+)}/g, ':$1');
}
}