-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcontroller-spec.ts
217 lines (187 loc) · 6.05 KB
/
controller-spec.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
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/openapi-v3
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {MetadataInspector, DecoratorFactory} from '@loopback/context';
import {
OperationObject,
ParameterObject,
PathObject,
ComponentsObject,
RequestBodyObject,
} from '@loopback/openapi-v3-types';
import {getJsonSchema} from '@loopback/repository-json-schema';
import {OAI3Keys} from './keys';
import {jsonToSchemaObject} from './json-to-schema';
import * as _ from 'lodash';
const debug = require('debug')('loopback:openapi3:metadata');
// tslint:disable:no-any
export interface ControllerSpec {
/**
* The base path on which the Controller API is served.
* If it is not included, the API is served directly under the host.
* The value MUST start with a leading slash (/).
*/
basePath?: string;
/**
* The available paths and operations for the API.
*/
paths: PathObject;
/**
* OpenAPI components.schemas generated from model metadata
*/
components?: ComponentsObject;
}
/**
* Data structure for REST related metadata
*/
export interface RestEndpoint {
verb: string;
path: string;
spec?: OperationObject;
}
/**
* Build the api spec from class and method level decorations
* @param constructor Controller class
*/
function resolveControllerSpec(constructor: Function): ControllerSpec {
debug(`Retrieving OpenAPI specification for controller ${constructor.name}`);
let spec = MetadataInspector.getClassMetadata<ControllerSpec>(
OAI3Keys.CLASS_KEY,
constructor,
);
if (spec) {
debug(' using class-level spec defined via @api()', spec);
spec = DecoratorFactory.cloneDeep(spec);
} else {
spec = {paths: {}};
}
let endpoints =
MetadataInspector.getAllMethodMetadata<RestEndpoint>(
OAI3Keys.METHODS_KEY,
constructor.prototype,
) || {};
endpoints = DecoratorFactory.cloneDeep(endpoints);
for (const op in endpoints) {
debug(' processing method %s', op);
const endpoint = endpoints[op];
const verb = endpoint.verb!;
const path = endpoint.path!;
let endpointName = '';
/* istanbul ignore if */
if (debug.enabled) {
const className = constructor.name || '<AnonymousClass>';
const fullMethodName = `${className}.${op}`;
endpointName = `${fullMethodName} (${verb} ${path})`;
}
let operationSpec = endpoint.spec;
if (!operationSpec) {
// The operation was defined via @operation(verb, path) with no spec
operationSpec = {
responses: {},
};
endpoint.spec = operationSpec;
}
debug(' operation for method %s: %j', op, endpoint);
debug(' processing parameters for method %s', op);
let params = MetadataInspector.getAllParameterMetadata<ParameterObject>(
OAI3Keys.PARAMETERS_KEY,
constructor.prototype,
op,
);
debug(' parameters for method %s: %j', op, params);
if (params != null) {
params = DecoratorFactory.cloneDeep<ParameterObject[]>(params);
/**
* If a controller method uses dependency injection, the parameters
* might be sparsed. For example,
* ```ts
* class MyController {
* greet(
* @inject('prefix') prefix: string,
* @param.query.string('name) name: string) {
* return `${prefix}`, ${name}`;
* }
* ```
*/
operationSpec.parameters = params.filter(p => p != null);
}
debug(' processing requestBody for method %s', op);
let requestBodies = MetadataInspector.getAllParameterMetadata<
RequestBodyObject
>(OAI3Keys.REQUEST_BODY_KEY, constructor.prototype, op);
if (requestBodies != null)
requestBodies = requestBodies.filter(p => p != null);
let requestBody: RequestBodyObject;
if (requestBodies) {
if (requestBodies.length > 1)
throw new Error(
'An operation should only have one parameter decorated by @requestBody',
);
requestBody = requestBodies[0];
debug(' requestBody for method %s: %j', op, requestBody);
if (requestBody) {
operationSpec.requestBody = requestBody;
}
}
operationSpec['x-operation-name'] = op;
if (!spec.paths[path]) {
spec.paths[path] = {};
}
if (spec.paths[path][verb]) {
// Operations from subclasses override those from the base
debug(` Overriding ${endpointName} - endpoint was already defined`);
}
debug(` adding ${endpointName}`, operationSpec);
spec.paths[path][verb] = operationSpec;
debug(` inferring schema object for method %s`, op);
const opMetadata = MetadataInspector.getDesignTypeForMethod(
constructor.prototype,
op,
);
const paramTypes = opMetadata.parameterTypes;
const isComplexType = (ctor: Function) =>
!_.includes([String, Number, Boolean, Array, Object], ctor);
for (const p of paramTypes) {
if (isComplexType(p)) {
if (!spec.components) {
spec.components = {};
}
if (!spec.components.schemas) {
spec.components.schemas = {};
}
const jsonSchema = getJsonSchema(p);
const openapiSchema = jsonToSchemaObject(jsonSchema);
if (openapiSchema.definitions) {
for (const key in openapiSchema.definitions) {
spec.components.schemas[key] = openapiSchema.definitions[key];
}
delete openapiSchema.definitions;
}
spec.components.schemas[p.name] = openapiSchema;
break;
}
}
}
return spec;
}
/**
* Get the controller spec for the given class
* @param constructor Controller class
*/
export function getControllerSpec(constructor: Function): ControllerSpec {
let spec = MetadataInspector.getClassMetadata<ControllerSpec>(
OAI3Keys.CONTROLLER_SPEC_KEY,
constructor,
{ownMetadataOnly: true},
);
if (!spec) {
spec = resolveControllerSpec(constructor);
MetadataInspector.defineMetadata(
OAI3Keys.CONTROLLER_SPEC_KEY.key,
spec,
constructor,
);
}
return spec;
}