-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathopen-api.ts
182 lines (171 loc) · 6.05 KB
/
open-api.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
import { Class } from '../interfaces';
import { Handler } from '../handler';
import { Message } from '../interfaces';
import { Metadata } from '../interfaces';
import { Route } from '../interfaces';
import { getMetadata } from '../metadata';
import { resolveMetadata } from '../metadata';
import { ContentObject } from 'openapi3-ts';
import { InfoObject } from 'openapi3-ts';
import { Injectable } from 'injection-js';
import { Observable } from 'rxjs';
import { OpenApiBuilder } from 'openapi3-ts';
import { OperationObject } from 'openapi3-ts';
import { ParameterLocation } from 'openapi3-ts';
import { PathItemObject } from 'openapi3-ts';
import { PathsObject } from 'openapi3-ts';
import { SchemaObject } from 'openapi3-ts';
import { tap } from 'rxjs/operators';
/**
* OpenAPI YML generator
*/
@Injectable()
export class OpenAPI extends Handler {
/**
* Generate OpenAPI from routes
*
* TODO: refactor if it gets any bigger
*/
static fromRoutes(info: InfoObject, flattened: Route[]): OpenApiBuilder {
const openAPI = new OpenApiBuilder().addInfo(info);
// create each path from a corresponding route
const paths = flattened.reduce((acc, route) => {
const item: PathItemObject = acc[route.path] || {};
// skeleton operation object
const operation: OperationObject = {
description: route.description || '',
responses: {},
summary: route.summary || '',
parameters: []
};
// handle request body
if (route.request && route.request.body) {
const content: ContentObject = Object.entries(route.request.body)
.map(([contentType, clazz]) => ({
contentType,
schema: OpenAPI.makeSchemaObject(clazz)
}))
.reduce((acc, { contentType, schema }) => {
acc[contentType] = { schema };
return acc;
}, {});
operation.requestBody = { content };
}
// handle request parameters
if (route.request) {
['header', 'path', 'query']
.map((type) => ({ type, clazz: route.request[type] }))
.filter(({ clazz }) => !!clazz)
.map(({ type, clazz }) => ({ type, metadata: getMetadata(clazz) }))
.forEach(({ type, metadata }) => {
metadata.forEach((metadatum) => {
operation.parameters.push({
name: metadatum.name,
in: type as ParameterLocation,
// NOTE: path params are always required
required: metadatum.opts.required || type === 'path',
schema: { type: OpenAPI.typeFor(metadatum) as any }
});
});
});
}
// handle responses
if (route.responses) {
Object.keys(route.responses).forEach((statusCode) => {
const content: ContentObject = Object.entries(
route.responses[statusCode]
)
.map(([contentType, clazz]) => ({
contentType,
schema: OpenAPI.makeSchemaObject(clazz)
}))
.reduce((acc, { contentType, schema }) => {
acc[contentType] = { schema };
return acc;
}, {});
operation.responses[statusCode] = { content };
});
}
// redirect gets a special response
if (route.redirectTo) {
const statusCode = route.redirectAs || 301;
operation.responses[String(statusCode)] = {
// eslint-disable-next-line @typescript-eslint/naming-convention
headers: { Location: { schema: { type: 'string' } } }
};
}
// NOTE: we allow multiple methods to alias to the same "operation"
// while OpenAPI does not directly, so this looks a little weird
route.methods.forEach(
(method) => (item[method.toLowerCase()] = operation)
);
acc[route.path] = item;
return acc;
}, {} as PathsObject);
// add the paths back into the OpenAPI object
Object.entries(paths).forEach(([pathName, path]) =>
openAPI.addPath(pathName, path)
);
return openAPI;
}
/**
* Make an OpenAPI schema from a class's metadata
*
* @see https://swagger.io/docs/specification/data-models/data-types
*/
static makeSchemaObject(tgt: Class): SchemaObject {
const metadata = resolveMetadata(getMetadata(tgt));
const schema: SchemaObject = {
properties: {},
required: [],
type: 'object'
};
return OpenAPI.makeSchemaObjectImpl(metadata, schema);
}
private static makeSchemaObjectImpl(
metadata: Metadata[],
schema: SchemaObject
): SchemaObject {
metadata.forEach((metadatum) => {
// this is the normal case - we keep coded properties to a minimum
const subschema: SchemaObject = {
type: OpenAPI.typeFor(metadatum) as any
};
// for arrays
if (metadatum.isArray) {
subschema.items = { type: OpenAPI.typeFor(metadatum) as any };
subschema.type = 'array';
// for arrays of objects
if (metadatum.metadata.length > 0) {
subschema.items.properties = {};
subschema.items.required = [];
subschema.items.type = 'object';
OpenAPI.makeSchemaObjectImpl(metadatum.metadata, subschema.items);
}
}
// for objects
else if (metadatum.metadata.length > 0) {
subschema.properties = {};
subschema.required = [];
subschema.type = 'object';
OpenAPI.makeSchemaObjectImpl(metadatum.metadata, subschema);
}
schema.properties[metadatum.name] = subschema;
if (metadatum.opts.required) schema.required.push(metadatum.name);
});
return schema;
}
private static typeFor(metadata: Metadata): string {
if (metadata.type === 'Number')
return metadata.opts.float ? 'number' : 'integer';
else return metadata.type.toLowerCase();
}
handle(message$: Observable<Message>): Observable<Message> {
return message$.pipe(
tap(({ context, response }) => {
const flattened = context.router.flatten();
response.body = OpenAPI.fromRoutes(context.info, flattened).getSpec();
})
);
}
}