/
application.ts
495 lines (438 loc) · 13.8 KB
/
application.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// Copyright IBM Corp. 2017. All Rights Reserved.
// Node module: @loopback/core
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {AssertionError} from 'assert';
import * as SwaggerParser from 'swagger-parser';
import {
Binding,
Context,
Constructor,
Provider,
inject,
} from '@loopback/context';
import {
OpenApiSpec,
Route,
ParsedRequest,
OperationObject,
ControllerRoute,
RouteEntry,
createEmptyApiSpec,
} from '.';
import {ServerRequest, ServerResponse, createServer} from 'http';
import {Component, mountComponent} from './component';
import {getControllerSpec} from './router/metadata';
import {HttpHandler} from './http-handler';
import {writeResultToResponse} from './writer';
import {DefaultSequence, SequenceHandler, SequenceFunction} from './sequence';
import {RejectProvider} from './router/reject';
import {FindRoute, InvokeMethod, Send, Reject} from './internal-types';
import {ControllerClass} from './router/routing-table';
// NOTE(bajtos) we cannot use `import * as cloneDeep from 'lodash/cloneDeep'
// because it produces the following TypeScript error:
// Module '"(...)/node_modules/@types/lodash/cloneDeep/index"' resolves to
// a non-module entity and cannot be imported using this construct.
const cloneDeep: <T>(value: T) => T = require('lodash/cloneDeep');
const debug = require('debug')('loopback:core:application');
export class Application extends Context {
/**
* Handle incoming HTTP(S) request by invoking the corresponding
* Controller method via the configured Sequence.
*
* @example
*
* ```ts
* const app = new Application();
* // setup controllers, etc.
*
* const server = http.createServer(app.handleHttp);
* server.listen(3000);
* ```
*
* @param req The request.
* @param res The response.
*/
public handleHttp: (req: ServerRequest, res: ServerResponse) => void;
protected _httpHandler: HttpHandler;
constructor(public options?: ApplicationOptions) {
super();
if (!options) options = {};
this.bind('http.port').to(options.http ? options.http.port : 3000);
this.api(createEmptyApiSpec());
if (options.components) {
for (const component of options.components) {
this.component(component);
}
}
this.sequence(options.sequence ? options.sequence : DefaultSequence);
this.handleHttp = (req: ServerRequest, res: ServerResponse) => {
try {
this._handleHttpRequest(req, res)
.catch(err => this._onUnhandledError(req, res, err));
} catch (err) {
this._onUnhandledError(req, res, err);
}
};
this.bind('sequence.actions.logError').to(this._logError.bind(this));
this.bind('sequence.actions.send').to(writeResultToResponse);
this.bind('sequence.actions.reject').toProvider(RejectProvider);
}
protected _handleHttpRequest(
request: ServerRequest,
response: ServerResponse,
) {
this._setupHandlerIfNeeded();
if (request.method === 'GET' && request.url === '/openapi.json') {
return this._serveOpenApiSpec(request, response);
}
return this._httpHandler.handleRequest(request, response);
}
protected _setupHandlerIfNeeded() {
// TODO(bajtos) support hot-reloading of controllers
// after the app started. The idea is to rebuild the HttpHandler
// instance whenever a controller was added/deleted.
// See https://github.com/strongloop/loopback-next/issues/433
if (this._httpHandler) return;
this._httpHandler = new HttpHandler(this);
for (const b of this.find('controllers.*')) {
const controllerName = b.key.replace(/^controllers\./, '');
const ctor = b.valueConstructor;
if (!ctor) {
throw new Error(
`The controller ${controllerName} was not bound via .toClass()`);
}
const apiSpec = getControllerSpec(ctor);
if (!apiSpec) {
// controller methods are specified through app.api() spec
continue;
}
this._httpHandler.registerController(ctor, apiSpec);
}
for (const b of this.find('routes.*')) {
// TODO(bajtos) should we support routes defined asynchronously?
const route = this.getSync(b.key);
this._httpHandler.registerRoute(route);
}
// TODO(bajtos) should we support API spec defined asynchronously?
const spec: OpenApiSpec = this.getSync('api-spec');
for (const path in spec.paths) {
for (const verb in spec.paths[path]) {
const routeSpec: OperationObject = spec.paths[path][verb];
this._setupOperation(verb, path, routeSpec);
}
}
}
private _setupOperation(verb: string, path: string, spec: OperationObject) {
const handler = spec['x-operation'];
if (typeof handler === 'function') {
// Remove a field value that cannot be represented in JSON.
// Start by creating a shallow-copy of the spec, so that we don't
// modify the original spec object provided by user.
spec = Object.assign({}, spec);
delete spec['x-operation'];
const route = new Route(verb, path, spec, handler);
this._httpHandler.registerRoute(route);
return;
}
const controllerName = spec['x-controller'];
if (typeof controllerName === 'string') {
const b = this.find(`controllers.${controllerName}`)[0];
if (!b) {
throw new Error(
`Unknown controller ${controllerName} used by "${verb} ${path}"`);
}
const ctor = b.valueConstructor;
if (!ctor) {
throw new Error(
`The controller ${controllerName} was not bound via .toClass()`,
);
}
const route = new ControllerRoute(verb, path, spec, ctor);
this._httpHandler.registerRoute(route);
return;
}
throw new Error(
`There is no handler configured for operation "${verb} ${path}`);
}
private async _serveOpenApiSpec(
request: ServerRequest,
response: ServerResponse,
) {
const spec = JSON.stringify(this.getApiSpec(), null, 2);
response.setHeader('content-type', 'application/json; charset=utf-8');
response.end(spec, 'utf-8');
}
/**
* Register a controller class with this application.
*
* @param controllerCtor {Function} The controller class
* (constructor function).
* @return {Binding} The newly created binding, you can use the reference to
* further modify the binding, e.g. lock the value to prevent further
* modifications.
*
* ```ts
* @spec(apiSpec)
* class MyController {
* }
* app.controller(MyController).lock();
* ```
*/
controller(controllerCtor: ControllerClass): Binding {
return this.bind('controllers.' + controllerCtor.name).toClass(
controllerCtor,
);
}
/**
* Register a new Controller-based route.
*
* ```ts
* class MyController {
* greet(name: string) {
* return `hello ${name}`;
* }
* }
* app.route('get', '/greet', operationSpec, MyController, 'greet');
* ```
*
* @param verb HTTP verb of the endpoint
* @param path URL path of the endpoint
* @param spec The OpenAPI spec describing the endpoint (operation)
* @param controller Controller constructor
* @param methodName The name of the controller method
*/
route(
verb: string,
path: string,
spec: OperationObject,
controller: ControllerClass,
methodName: string): Binding;
/**
* Register a new route.
*
* ```ts
* function greet(name: string) {
* return `hello ${name}`;
* }
* const route = new Route('get', '/', operationSpec, greet);
* app.route(route);
* ```
*
* @param route The route to add.
*/
route(route: RouteEntry): Binding;
route(
routeOrVerb: RouteEntry | string,
path?: string,
spec?: OperationObject,
controller?: ControllerClass,
methodName?: string,
): Binding {
if (typeof routeOrVerb === 'object') {
const r = routeOrVerb;
return this.bind(`routes.${r.verb} ${r.path}`).to(r);
}
if (!path) {
throw new AssertionError({
message: 'path is required for a controller-based route',
});
}
if (!spec) {
throw new AssertionError({
message: 'spec is required for a controller-based route',
});
}
if (!controller) {
throw new AssertionError({
message: 'controller is required for a controller-based route',
});
}
if (!methodName) {
throw new AssertionError({
message: 'methodName is required for a controller-based route',
});
}
return this.route(new ControllerRoute(
routeOrVerb,
path,
spec,
controller,
methodName));
}
api(spec: OpenApiSpec): Binding {
return this.bind('api-spec').to(spec);
}
/**
* Get the OpenAPI specification describing the REST API provided by
* this application.
*
* This method merges operations (HTTP endpoints) from the following sources:
* - `app.api(spec)`
* - `app.controller(MyController)`
* - `app.route(route)`
* - `app.route('get', '/greet', operationSpec, MyController, 'greet')`
*/
getApiSpec(): OpenApiSpec {
const spec = this.getSync('api-spec');
this._setupHandlerIfNeeded();
// Apply deep clone to prevent getApiSpec() callers from
// accidentally modifying our internal routing data
spec.paths = cloneDeep(this._httpHandler.describeApiPaths());
return spec;
}
async validateApiSpec(): Promise<void> {
const spec = this.getApiSpec();
const opts: SwaggerParser.Options = {
$refs: {
internal: false,
external: false,
},
} as SwaggerParser.Options;
// workaround for unhelpful message returned by SwaggerParser
if (!spec.swagger) {
throw new Error('Missing required property: swagger at #/');
}
if (!spec.info) {
throw new Error('Missing required property: info at #/');
}
if (!spec.paths) {
throw new Error('Missing required property: paths at #/');
}
await SwaggerParser.validate(spec, opts);
}
protected _logError(
err: Error,
statusCode: number,
req: ServerRequest,
): void {
console.error(
'Unhandled error in %s %s: %s %s',
req.method,
req.url,
statusCode,
err.stack || err,
);
}
/**
* Add a component to this application.
*
* @param component The component to add.
*
* ```ts
*
* export class ProductComponent {
* controllers = [ProductController];
* repositories = [ProductRepo, UserRepo];
* providers = {
* [AUTHENTICATION_STRATEGY]: AuthStrategy,
* [AUTHORIZATION_ROLE]: Role,
* };
* };
*
* app.component(ProductComponent);
* ```
*/
public component(component: Constructor<Component>) {
const componentKey = `components.${component.name}`;
this.bind(componentKey).toClass(component);
const instance = this.getSync(componentKey);
mountComponent(this, instance);
}
/**
* Configure a custom sequence class for handling incoming requests.
*
* ```ts
* class MySequence implements SequenceHandler {
* constructor(
* @inject('send) public send: Send)) {
* }
*
* public async handle(request: ParsedRequest, response: ServerResponse) {
* send(response, 'hello world');
* }
* }
* ```
*
* @param value The sequence to invoke for each incoming request.
*/
public sequence(value: Constructor<SequenceHandler>) {
this.bind('sequence').toClass(value);
}
/**
* Configure a custom sequence function for handling incoming requests.
*
* ```ts
* app.handler((sequence, request, response) => {
* sequence.send(response, 'hello world'));
* });
* ```
*
* @param handlerFn The handler to invoke for each incoming request.
*/
public handler(handlerFn: SequenceFunction) {
class SequenceFromFunction extends DefaultSequence {
// NOTE(bajtos) Unfortunately, we have to duplicate the constructor
// in order for our DI/IoC framework to inject constructor arguments
constructor(
@inject('sequence.actions.findRoute') protected findRoute: FindRoute,
@inject('sequence.actions.invokeMethod') protected invoke: InvokeMethod,
@inject('sequence.actions.send') public send: Send,
@inject('sequence.actions.reject') public reject: Reject,
) {
super(findRoute, invoke, send, reject);
}
async handle(
request: ParsedRequest,
response: ServerResponse,
): Promise<void> {
await Promise.resolve(handlerFn(this, request, response));
}
}
this.sequence(SequenceFromFunction);
}
/**
* Start the application (e.g. HTTP/HTTPS servers).
*/
async start(): Promise<void> {
// Setup the HTTP handler so that we can verify the configuration
// of API spec, controllers and routes at startup time.
this._setupHandlerIfNeeded();
const httpPort = await this.get('http.port');
const server = createServer(this.handleHttp);
// TODO(bajtos) support httpHostname too
// See https://github.com/strongloop/loopback-next/issues/434
server.listen(httpPort);
return new Promise<void>((resolve, reject) => {
server.once('listening', () => {
this.bind('http.port').to(server.address().port);
resolve();
});
server.once('error', reject);
});
}
protected _onUnhandledError(
req: ServerRequest,
res: ServerResponse,
err: Error,
) {
if (!res.headersSent) {
res.statusCode = 500;
res.end();
}
// It's the responsibility of the Sequence to handle any errors.
// If an unhandled error escaped, then something very wrong happened
// and it's best to crash the process immediately.
process.nextTick(() => {
throw err;
});
}
}
export interface ApplicationOptions {
http?: HttpConfig;
components?: Array<Constructor<Component>>;
sequence?: Constructor<SequenceHandler>;
}
export interface HttpConfig {
port: number;
}