-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathroute-helper.js
298 lines (260 loc) · 10.1 KB
/
route-helper.js
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
'use strict';
/**
* Module dependencies.
*/
var debug = require('debug')('loopback:explorer:routeHelpers');
var _assign = require('lodash').assign;
var typeConverter = require('./type-converter');
var schemaBuilder = require('./schema-builder');
/**
* Export the routeHelper singleton.
*/
var routeHelper = module.exports = {
/**
* Given a route, generate an API description and add it to the doc.
* If a route shares a path with another route (same path, different verb),
* add it as a new operation under that path entry.
*
* Routes can be translated to API declaration 'operations',
* but they need a little massaging first. The `accepts` and
* `returns` declarations need some basic conversions to be compatible.
*
* This method will convert the route and add it to the doc.
*
* @param {Route} route Strong Remoting Route object.
* @param {Class} classDef Strong Remoting class.
* @param {TypeRegistry} typeRegistry Registry of types and models.
* @param {Object} operationIdRegistry Registry of operationIds mapping
* operationId to an operation object.
* @param {Object} paths Swagger Path Object,
* see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathsObject
*/
addRouteToSwaggerPaths: function(route, classDef, typeRegistry,
operationIdRegistry, paths) {
var entryToAdd = routeHelper.routeToPathEntry(route, classDef,
typeRegistry,
operationIdRegistry);
if (!(entryToAdd.path in paths)) {
paths[entryToAdd.path] = {};
}
paths[entryToAdd.path][entryToAdd.method] = entryToAdd.operation;
},
/**
* Massage route.accepts.
* @param {Object} route Strong Remoting Route object.
* @param {Class} classDef Strong Remoting class.
* @param {TypeRegistry} typeRegistry Registry of types and models.
* @return {Array} Array of param docs.
*/
convertAcceptsToSwagger: function(route, classDef, typeRegistry) {
var accepts = route.accepts || [];
var split = route.method.split('.');
if (classDef && classDef.sharedCtor &&
classDef.sharedCtor.accepts && split.length > 2 /* HACK */) {
accepts = accepts.concat(classDef.sharedCtor.accepts);
}
// Filter out parameters that are generated from the incoming request,
// or generated by functions that use those resources.
accepts = accepts.filter(function(arg) {
if (!arg.http) return true;
// Don't show derived arguments.
if (typeof arg.http === 'function') return false;
// Don't show arguments set to the incoming http request.
// Please note that body needs to be shown, such as User.create().
if (arg.http.source === 'req' ||
arg.http.source === 'res' ||
arg.http.source === 'context') {
return false;
}
return true;
});
// Turn accept definitions in to parameter docs.
accepts = accepts.map(
routeHelper.acceptToParameter(route, classDef, typeRegistry));
return accepts;
},
/**
* Massage route.returns.
* @param {Object} route Strong Remoting Route object.
* @return {Object} A single returns param doc.
*/
convertReturnsToSwagger: function(route, typeRegistry) {
var routeReturns = route.returns;
if (!routeReturns || !routeReturns.length) {
// An operation that returns nothing will have
// no schema declaration for its response.
return undefined;
}
if (routeReturns.length === 1 && routeReturns[0].root) {
if (routeReturns[0].model)
return { $ref: typeRegistry.reference(routeReturns[0].model) };
return schemaBuilder.buildFromLoopBackType(routeReturns[0], typeRegistry);
}
// Convert `returns` into a single object for later conversion into an
// operation object.
// TODO ad-hoc model definition in the case of multiple return values.
// It is enough to replace 'object' with an anonymous type definition
// based on all routeReturn items. The schema converter should take
// care of the remaning conversions.
var def = { type: 'object' };
return schemaBuilder.buildFromLoopBackType(def, typeRegistry);
},
/**
* Converts from an sl-remoting-formatted "Route" description to a
* Swagger-formatted "Path Item Object"
* See swagger-spec/2.0.md#pathItemObject
*/
routeToPathEntry: function(route, classDef,
typeRegistry, operationIdRegistry) {
// Some parameters need to be altered; eventually most of this should
// be removed.
var accepts = routeHelper.convertAcceptsToSwagger(route, classDef,
typeRegistry);
var returns = routeHelper.convertReturnsToSwagger(route, typeRegistry);
var defaultCode = route.returns && route.returns.length ? 200 : 204;
// TODO - support strong-remoting's option for a custom response code
var responseMessages = {};
responseMessages[defaultCode] = {
description: 'Request was successful',
schema: returns,
// TODO - headers, examples
};
if (route.errors) {
// TODO define new LDL syntax that is status-code-indexed
// and which allow users to specify headers & examples
route.errors.forEach(function(msg) {
responseMessages[msg.code] = {
description: msg.message,
schema: schemaBuilder.buildFromLoopBackType(msg.responseModel,
typeRegistry),
// TODO - headers, examples
};
});
}
debug('route %j', route);
var path = routeHelper.convertPathFragments(route.path);
var verb = routeHelper.convertVerb(route.verb);
var tags = [];
if (classDef && classDef.name) {
tags.push(classDef.name);
}
var operationId = createUniqueOperationId(route.method, verb, path,
operationIdRegistry);
var entry = {
path: path,
method: verb,
operation: {
tags: tags,
summary: typeConverter.convertText(route.description),
description: typeConverter.convertText(route.notes),
operationId: operationId,
// [bajtos] we are omitting consumes and produces, as they are same
// for all methods and they are already specified in top-level fields
parameters: accepts,
responses: responseMessages,
deprecated: !!route.deprecated,
// TODO: security
}
};
operationIdRegistry[operationId] = entry;
return entry;
},
convertPathFragments: function convertPathFragments(path) {
return path.split('/').map(function (fragment) {
if (fragment.charAt(0) === ':') {
return '{' + fragment.slice(1) + '}';
}
return fragment;
}).join('/');
},
convertVerb: function convertVerb(verb) {
if (verb.toLowerCase() === 'all') {
return 'post';
}
if (verb.toLowerCase() === 'del') {
return 'delete';
}
return verb.toLowerCase();
},
/**
* A generator to convert from an sl-remoting-formatted "Accepts" description
* to a Swagger-formatted "Parameter" description.
*/
acceptToParameter: function acceptToParameter(route, classDef, typeRegistry) {
var DEFAULT_TYPE =
route.verb.toLowerCase() === 'get' ? 'query' : 'formData';
return function (accepts) {
var name = accepts.name || accepts.arg;
var paramType = DEFAULT_TYPE;
// TODO: Regex. This is leaky.
if (route.path.indexOf(':' + name) !== -1) {
paramType = 'path';
}
// Check the http settings for the argument
if (accepts.http && accepts.http.source) {
paramType = accepts.http.source;
}
// TODO: ensure that paramType has a valid value
// path, query, header, body, formData
// See swagger-spec/2.0.md#parameterObject
var paramObject = {
name: name,
in: paramType,
description: typeConverter.convertText(accepts.description),
required: !!accepts.required
};
var schema = schemaBuilder.buildFromLoopBackType(accepts, typeRegistry);
if (paramType === 'body') {
// HACK: Derive the type from model
if (paramObject.name === 'data' && schema.type === 'object') {
paramObject.schema = { $ref: typeRegistry.reference(classDef.name) };
} else {
paramObject.schema = schema;
}
} else {
var isComplexType = schema.type === 'object' ||
schema.type === 'array' ||
schema.$ref;
if (isComplexType) {
paramObject.type = 'string';
paramObject.format = 'JSON';
// TODO support array of primitive types
// and map them to Swagger array of primitive types
} else {
_assign(paramObject, schema);
}
}
return paramObject;
};
},
};
function createUniqueOperationId(methodName, verb, path, operationIdRegistry) {
// [bajtos] We used to remove leading model name from the operation
// name for Swagger Spec 1.2. Swagger Spec 2.0 requires
// operation ids to be unique, thus we have to include the model name.
var id = methodName;
if (!(id in operationIdRegistry)) {
// The id is already unique
return id;
}
var baseId = id;
id = createLongOperationId(baseId, verb, path);
if (id in operationIdRegistry) {
console.warn('Warning: detected multiple remote methods ' +
'at the same HTTP endpoint. ' +
'Swagger operation ids will be NOT unique.');
}
// Rename the first operation so that all operation ids of
// a multi-endpoint method are consistently using the long form
if (operationIdRegistry[baseId]) {
var oldEntry = operationIdRegistry[baseId];
var newId = createLongOperationId(baseId, oldEntry.method, oldEntry.path);
oldEntry.operation.operationId = newId;
operationIdRegistry[newId] = oldEntry;
operationIdRegistry[baseId] = null;
}
return id;
}
function createLongOperationId(baseId, verb, path) {
return baseId + '__' + verb + path.replace(/[\/:]+/g, '_');
}