-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rest.server.ts
1027 lines (918 loc) · 29.5 KB
/
rest.server.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright IBM Corp. 2018,2019. All Rights Reserved.
// Node module: @loopback/rest
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {
Binding,
BindingAddress,
BindingScope,
Constructor,
Context,
inject,
} from '@loopback/context';
import {Application, CoreBindings, Server} from '@loopback/core';
import {HttpServer, HttpServerOptions} from '@loopback/http-server';
import {
getControllerSpec,
OpenApiSpec,
OperationObject,
ServerObject,
} from '@loopback/openapi-v3';
import {AssertionError} from 'assert';
import * as cors from 'cors';
import * as debugFactory from 'debug';
import * as express from 'express';
import {PathParams} from 'express-serve-static-core';
import {IncomingMessage, ServerResponse} from 'http';
import {ServerOptions} from 'https';
import {safeDump} from 'js-yaml';
import {ServeStaticOptions} from 'serve-static';
import {BodyParser, REQUEST_BODY_PARSER_TAG} from './body-parsers';
import {HttpHandler} from './http-handler';
import {RestBindings} from './keys';
import {RequestContext} from './request-context';
import {
ControllerClass,
ControllerFactory,
ControllerInstance,
ControllerRoute,
createControllerFactoryForBinding,
ExpressRequestHandler,
ExternalExpressRoutes,
RedirectRoute,
RestRouterOptions,
Route,
RouteEntry,
RouterSpec,
RoutingTable,
} from './router';
import {assignRouterSpec} from './router/router-spec';
import {DefaultSequence, SequenceFunction, SequenceHandler} from './sequence';
import {
FindRoute,
InvokeMethod,
ParseParams,
Reject,
Request,
RequestBodyParserOptions,
Response,
Send,
} from './types';
const debug = debugFactory('loopback:rest:server');
export type HttpRequestListener = (
req: IncomingMessage,
res: ServerResponse,
) => void;
export interface HttpServerLike {
requestHandler: HttpRequestListener;
}
const SequenceActions = RestBindings.SequenceActions;
// 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');
/**
* A REST API server for use with Loopback.
* Add this server to your application by importing the RestComponent.
*
* @example
* ```ts
* const app = new MyApplication();
* app.component(RestComponent);
* ```
*
* To add additional instances of RestServer to your application, use the
* `.server` function:
* ```ts
* app.server(RestServer, 'nameOfYourServer');
* ```
*
* By default, one instance of RestServer will be created when the RestComponent
* is bootstrapped. This instance can be retrieved with
* `app.getServer(RestServer)`, or by calling `app.get('servers.RestServer')`
* Note that retrieving other instances of RestServer must be done using the
* server's name:
* ```ts
* const server = await app.getServer('foo')
* // OR
* const server = await app.get('servers.foo');
* ```
*/
export class RestServer extends Context implements Server, HttpServerLike {
/**
* Handle incoming HTTP(S) request by invoking the corresponding
* Controller method via the configured Sequence.
*
* @example
*
* ```ts
* const app = new Application();
* app.component(RestComponent);
* // setup controllers, etc.
*
* const restServer = await app.getServer(RestServer);
* const httpServer = http.createServer(restServer.requestHandler);
* httpServer.listen(3000);
* ```
*
* @param req - The request.
* @param res - The response.
*/
protected _requestHandler: HttpRequestListener;
public get requestHandler(): HttpRequestListener {
if (this._requestHandler == null) {
this._setupRequestHandlerIfNeeded();
}
return this._requestHandler;
}
public readonly config: RestServerResolvedConfig;
private _basePath: string;
protected _httpHandler: HttpHandler;
protected get httpHandler(): HttpHandler {
this._setupHandlerIfNeeded();
return this._httpHandler;
}
protected _httpServer: HttpServer | undefined;
protected _expressApp: express.Application;
get listening(): boolean {
return this._httpServer ? this._httpServer.listening : false;
}
/**
* The base url for the server, including the basePath if set. For example,
* the value will be 'http://localhost:3000/api' if `basePath` is set to
* '/api'.
*/
get url(): string | undefined {
let serverUrl = this.rootUrl;
if (!serverUrl) return serverUrl;
serverUrl = serverUrl + (this._basePath || '');
return serverUrl;
}
/**
* The root url for the server without the basePath. For example, the value
* will be 'http://localhost:3000' regardless of the `basePath`.
*/
get rootUrl(): string | undefined {
return this._httpServer && this._httpServer.url;
}
/**
*
* Creates an instance of RestServer.
*
* @param app - The application instance (injected via
* CoreBindings.APPLICATION_INSTANCE).
* @param config - The configuration options (injected via
* RestBindings.CONFIG).
*
*/
constructor(
@inject(CoreBindings.APPLICATION_INSTANCE) app: Application,
@inject(RestBindings.CONFIG, {optional: true})
config: RestServerConfig = {},
) {
super(app);
this.config = resolveRestServerConfig(config);
this.bind(RestBindings.PORT).to(this.config.port);
this.bind(RestBindings.HOST).to(config.host);
this.bind(RestBindings.PROTOCOL).to(config.protocol || 'http');
this.bind(RestBindings.HTTPS_OPTIONS).to(config as ServerOptions);
if (config.requestBodyParser) {
this.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS).to(
config.requestBodyParser,
);
}
if (config.sequence) {
this.sequence(config.sequence);
}
if (config.router) {
this.bind(RestBindings.ROUTER_OPTIONS).to(config.router);
}
this.basePath(config.basePath);
this.bind(RestBindings.BASE_PATH).toDynamicValue(() => this._basePath);
this.bind(RestBindings.HANDLER).toDynamicValue(() => this.httpHandler);
}
protected _setupRequestHandlerIfNeeded() {
if (this._expressApp) return;
this._expressApp = express();
this._applyExpressSettings();
this._requestHandler = this._expressApp;
// Allow CORS support for all endpoints so that users
// can test with online SwaggerUI instance
this._expressApp.use(cors(this.config.cors));
// Set up endpoints for OpenAPI spec/ui
this._setupOpenApiSpecEndpoints();
// Mount our router & request handler
this._expressApp.use(this._basePath, (req, res, next) => {
this._handleHttpRequest(req, res).catch(next);
});
// Mount our error handler
this._expressApp.use(
(err: Error, req: Request, res: Response, next: Function) => {
this._onUnhandledError(req, res, err);
},
);
}
/**
* Apply express settings.
*/
protected _applyExpressSettings() {
const settings = this.config.expressSettings;
for (const key in settings) {
this._expressApp.set(key, settings[key]);
}
if (this.config.router && typeof this.config.router.strict === 'boolean') {
this._expressApp.set('strict routing', this.config.router.strict);
}
}
/**
* Mount /openapi.json, /openapi.yaml for specs and /swagger-ui, /explorer
* to redirect to externally hosted API explorer
*/
protected _setupOpenApiSpecEndpoints() {
if (this.config.openApiSpec.disabled) return;
// NOTE(bajtos) Regular routes are handled through Sequence.
// IMO, this built-in endpoint should not run through a Sequence,
// because it's not part of the application API itself.
// E.g. if the app implements access/audit logs, I don't want
// this endpoint to trigger a log entry. If the server implements
// content-negotiation to support XML clients, I don't want the OpenAPI
// spec to be converted into an XML response.
const mapping = this.config.openApiSpec.endpointMapping!;
// Serving OpenAPI spec
for (const p in mapping) {
this._expressApp.get(p, (req, res) =>
this._serveOpenApiSpec(req, res, mapping[p]),
);
}
const explorerPaths = ['/swagger-ui', '/explorer'];
this._expressApp.get(explorerPaths, (req, res, next) =>
this._redirectToSwaggerUI(req, res, next),
);
}
protected _handleHttpRequest(request: Request, response: 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;
/**
* Check if there is custom router in the context
*/
const router = this.getSync(RestBindings.ROUTER, {optional: true});
const routingTable = new RoutingTable(router, this._externalRoutes);
this._httpHandler = new HttpHandler(this, this.config, routingTable);
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
debug('Skipping controller %s - no API spec provided', controllerName);
continue;
}
debug('Registering controller %s', controllerName);
if (apiSpec.components && apiSpec.components.schemas) {
this._httpHandler.registerApiDefinitions(apiSpec.components.schemas);
}
const controllerFactory = createControllerFactoryForBinding(b.key);
this._httpHandler.registerController(apiSpec, ctor, controllerFactory);
}
for (const b of this.find('routes.*')) {
// TODO(bajtos) should we support routes defined asynchronously?
const route = this.getSync<RouteEntry>(b.key);
this._httpHandler.registerRoute(route);
}
// TODO(bajtos) should we support API spec defined asynchronously?
const spec: OpenApiSpec = this.getSync(RestBindings.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-name'];
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 controllerFactory = createControllerFactoryForBinding(b.key);
const route = new ControllerRoute(
verb,
path,
spec,
ctor,
controllerFactory,
);
this._httpHandler.registerRoute(route);
return;
}
throw new Error(
`There is no handler configured for operation "${verb} ${path}`,
);
}
private async _serveOpenApiSpec(
request: Request,
response: Response,
specForm?: OpenApiSpecForm,
) {
const requestContext = new RequestContext(
request,
response,
this,
this.config,
);
specForm = specForm || {version: '3.0.0', format: 'json'};
let specObj = this.getApiSpec();
if (this.config.openApiSpec.setServersFromRequest) {
specObj = Object.assign({}, specObj);
specObj.servers = [{url: requestContext.requestedBaseUrl}];
}
const basePath = requestContext.basePath;
if (specObj.servers && basePath) {
for (const s of specObj.servers) {
// Update the default server url to honor `basePath`
if (s.url === '/') {
s.url = basePath;
}
}
}
if (specForm.format === 'json') {
const spec = JSON.stringify(specObj, null, 2);
response.setHeader('content-type', 'application/json; charset=utf-8');
response.end(spec, 'utf-8');
} else {
const yaml = safeDump(specObj, {});
response.setHeader('content-type', 'text/yaml; charset=utf-8');
response.end(yaml, 'utf-8');
}
}
private async _redirectToSwaggerUI(
request: Request,
response: Response,
next: express.NextFunction,
) {
const config = this.config.apiExplorer;
if (config.disabled) {
debug('Redirect to swagger-ui was disabled by configuration.');
next();
return;
}
debug('Redirecting to swagger-ui from %j.', request.originalUrl);
const requestContext = new RequestContext(
request,
response,
this,
this.config,
);
const protocol = requestContext.requestedProtocol;
const baseUrl = protocol === 'http' ? config.httpUrl : config.url;
const openApiUrl = `${requestContext.requestedBaseUrl}/openapi.json`;
const fullUrl = `${baseUrl}?url=${openApiUrl}`;
response.redirect(302, fullUrl);
}
/**
* Register a controller class with this server.
*
* @param controllerCtor - The controller class
* (constructor function).
* @returns The newly created binding, you can use the reference to
* further modify the binding, e.g. lock the value to prevent further
* modifications.
*
* @example
* ```ts
* class MyController {
* }
* app.controller(MyController).lock();
* ```
*
*/
controller(controllerCtor: ControllerClass<ControllerInstance>): Binding {
return this.bind('controllers.' + controllerCtor.name).toClass(
controllerCtor,
);
}
/**
* Register a new Controller-based route.
*
* @example
* ```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 controllerCtor - Controller constructor
* @param controllerFactory - A factory function to create controller instance
* @param methodName - The name of the controller method
*/
route<I>(
verb: string,
path: string,
spec: OperationObject,
controllerCtor: ControllerClass<I>,
controllerFactory: ControllerFactory<I>,
methodName: string,
): Binding;
/**
* Register a new route invoking a handler function.
*
* @example
* ```ts
* function greet(name: string) {
* return `hello ${name}`;
* }
* app.route('get', '/', operationSpec, 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 handler - The function to invoke with the request parameters
* described in the spec.
*/
route(
verb: string,
path: string,
spec: OperationObject,
handler: Function,
): Binding;
/**
* Register a new generic route.
*
* @example
* ```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<T>(
routeOrVerb: RouteEntry | string,
path?: string,
spec?: OperationObject,
controllerCtorOrHandler?: ControllerClass<T> | Function,
controllerFactory?: ControllerFactory<T>,
methodName?: string,
): Binding {
if (typeof routeOrVerb === 'object') {
const r = routeOrVerb;
// Encode the path to escape special chars
const encodedPath = encodeURIComponent(r.path).replace(/\./g, '%2E');
return this.bind(`routes.${r.verb} ${encodedPath}`)
.to(r)
.tag('route');
}
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 (arguments.length === 4) {
if (!controllerCtorOrHandler) {
throw new AssertionError({
message: 'handler function is required for a handler-based route',
});
}
return this.route(
new Route(routeOrVerb, path, spec, controllerCtorOrHandler as Function),
);
}
if (!controllerCtorOrHandler) {
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,
controllerCtorOrHandler as ControllerClass<T>,
controllerFactory,
methodName,
),
);
}
/**
* Register a route redirecting callers to a different URL.
*
* @example
* ```ts
* server.redirect('/explorer', '/explorer/');
* ```
*
* @param fromPath - URL path of the redirect endpoint
* @param toPathOrUrl - Location (URL path or full URL) where to redirect to.
* If your server is configured with a custom `basePath`, then the base path
* is prepended to the target location.
* @param statusCode - HTTP status code to respond with,
* defaults to 303 (See Other).
*/
redirect(
fromPath: string,
toPathOrUrl: string,
statusCode?: number,
): Binding {
return this.route(
new RedirectRoute(fromPath, this._basePath + toPathOrUrl, statusCode),
);
}
/*
* Registry of external routes & static assets
*/
private _externalRoutes = new ExternalExpressRoutes();
/**
* Mount static assets to the REST server.
* See https://expressjs.com/en/4x/api.html#express.static
* @param path - The path(s) to serve the asset.
* See examples at https://expressjs.com/en/4x/api.html#path-examples
* @param rootDir - The root directory from which to serve static assets
* @param options - Options for serve-static
*/
static(path: PathParams, rootDir: string, options?: ServeStaticOptions) {
this._externalRoutes.registerAssets(path, rootDir, options);
}
/**
* Set the OpenAPI specification that defines the REST API schema for this
* server. All routes, parameter definitions and return types will be defined
* in this way.
*
* Note that this will override any routes defined via decorators at the
* controller level (this function takes precedent).
*
* @param spec - The OpenAPI specification, as an object.
* @returns Binding for the spec
*
*/
api(spec: OpenApiSpec): Binding {
return this.bind(RestBindings.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<OpenApiSpec>(RestBindings.API_SPEC);
const defs = this.httpHandler.getApiDefinitions();
// Apply deep clone to prevent getApiSpec() callers from
// accidentally modifying our internal routing data
spec.paths = cloneDeep(this.httpHandler.describeApiPaths());
if (defs) {
spec.components = spec.components || {};
spec.components.schemas = cloneDeep(defs);
}
assignRouterSpec(spec, this._externalRoutes.routerSpec);
return spec;
}
/**
* Configure a custom sequence class for handling incoming requests.
*
* @example
* ```ts
* class MySequence implements SequenceHandler {
* constructor(
* @inject('send) public send: Send)) {
* }
*
* public async handle({response}: RequestContext) {
* send(response, 'hello world');
* }
* }
* ```
*
* @param value - The sequence to invoke for each incoming request.
*/
public sequence(value: Constructor<SequenceHandler>) {
this.bind(RestBindings.SEQUENCE).toClass(value);
}
/**
* Configure a custom sequence function for handling incoming requests.
*
* @example
* ```ts
* app.handler(({request, response}, sequence) => {
* 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(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
@inject(SequenceActions.PARSE_PARAMS)
protected parseParams: ParseParams,
@inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
@inject(SequenceActions.SEND) public send: Send,
@inject(SequenceActions.REJECT) public reject: Reject,
) {
super(findRoute, parseParams, invoke, send, reject);
}
async handle(context: RequestContext): Promise<void> {
await Promise.resolve(handlerFn(context, this));
}
}
this.sequence(SequenceFromFunction);
}
/**
* Bind a body parser to the server context
* @param parserClass - Body parser class
* @param address - Optional binding address
*/
bodyParser(
bodyParserClass: Constructor<BodyParser>,
address?: BindingAddress<BodyParser>,
): Binding<BodyParser> {
const binding = createBodyParserBinding(bodyParserClass, address);
this.add(binding);
return binding;
}
/**
* Configure the `basePath` for the rest server
* @param path - Base path
*/
basePath(path: string = '') {
if (this._requestHandler) {
throw new Error(
'Base path cannot be set as the request handler has been created',
);
}
// Trim leading and trailing `/`
path = path.replace(/(^\/)|(\/$)/, '');
if (path) path = '/' + path;
this._basePath = path;
}
/**
* Start this REST API's HTTP/HTTPS server.
*/
async start(): Promise<void> {
// Set up the Express app if not done yet
this._setupRequestHandlerIfNeeded();
// Setup the HTTP handler so that we can verify the configuration
// of API spec, controllers and routes at startup time.
this._setupHandlerIfNeeded();
const port = await this.get(RestBindings.PORT);
const host = await this.get(RestBindings.HOST);
const protocol = await this.get(RestBindings.PROTOCOL);
const httpsOptions = await this.get(RestBindings.HTTPS_OPTIONS);
const serverOptions = {};
if (protocol === 'https') Object.assign(serverOptions, httpsOptions);
Object.assign(serverOptions, {port, host, protocol});
this._httpServer = new HttpServer(this.requestHandler, serverOptions);
await this._httpServer.start();
this.bind(RestBindings.PORT).to(this._httpServer.port);
this.bind(RestBindings.HOST).to(this._httpServer.host);
this.bind(RestBindings.URL).to(this._httpServer.url);
debug('RestServer listening at %s', this._httpServer.url);
}
/**
* Stop this REST API's HTTP/HTTPS server.
*/
async stop() {
// Kill the server instance.
if (!this._httpServer) return;
await this._httpServer.stop();
this._httpServer = undefined;
}
protected _onUnhandledError(req: Request, res: Response, 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;
});
}
/**
* Mount an Express router to expose additional REST endpoints handled
* via legacy Express-based stack.
*
* @param basePath - Path where to mount the router at, e.g. `/` or `/api`.
* @param router - The Express router to handle the requests.
* @param spec - A partial OpenAPI spec describing endpoints provided by the
* router. LoopBack will prepend `basePath` to all endpoints automatically.
* This argument is optional. You can leave it out if you don't want to
* document the routes.
*/
mountExpressRouter(
basePath: string,
router: ExpressRequestHandler,
spec?: RouterSpec,
): void {
this._externalRoutes.mountRouter(basePath, router, spec);
}
}
/**
* Create a binding for the given body parser class
* @param parserClass - Body parser class
* @param key - Optional binding address
*/
export function createBodyParserBinding(
parserClass: Constructor<BodyParser>,
key?: BindingAddress<BodyParser>,
): Binding<BodyParser> {
const address =
key || `${RestBindings.REQUEST_BODY_PARSER}.${parserClass.name}`;
return Binding.bind<BodyParser>(address)
.toClass(parserClass)
.inScope(BindingScope.TRANSIENT)
.tag(REQUEST_BODY_PARSER_TAG);
}
/**
* The form of OpenAPI specs to be served
*/
export interface OpenApiSpecForm {
version?: string;
format?: string;
}
const OPENAPI_SPEC_MAPPING: {[key: string]: OpenApiSpecForm} = {
'/openapi.json': {version: '3.0.0', format: 'json'},
'/openapi.yaml': {version: '3.0.0', format: 'yaml'},
};
/**
* Options to customize how OpenAPI specs are served
*/
export interface OpenApiSpecOptions {
/**
* Mapping of urls to spec forms, by default:
* ```
* {
* '/openapi.json': {version: '3.0.0', format: 'json'},
* '/openapi.yaml': {version: '3.0.0', format: 'yaml'},
* }
* ```
*/
endpointMapping?: {[key: string]: OpenApiSpecForm};
/**
* A flag to force `servers` to be set from the http request for the OpenAPI
* spec
*/
setServersFromRequest?: boolean;
/**
* Configure servers for OpenAPI spec
*/
servers?: ServerObject[];
/**
* Set this flag to disable the endpoint for OpenAPI spec
*/
disabled?: true;
}
export interface ApiExplorerOptions {
/**
* URL for the hosted API explorer UI
* default to https://loopback.io/api-explorer
*/
url?: string;
/**
* URL for the API explorer served over `http` protocol to deal with mixed
* content security imposed by browsers as the spec is exposed over `http` by
* default.
* See https://github.com/strongloop/loopback-next/issues/1603
*/
httpUrl?: string;
/**
* Set this flag to disable the built-in redirect to externally
* hosted API Explorer UI.
*/
disabled?: true;
}
/**
* RestServer options
*/
export type RestServerOptions = Partial<RestServerResolvedOptions>;
export interface RestServerResolvedOptions {
port: number;
/**
* Base path for API/static routes
*/
basePath?: string;
cors: cors.CorsOptions;
openApiSpec: OpenApiSpecOptions;
apiExplorer: ApiExplorerOptions;
requestBodyParser?: RequestBodyParserOptions;
sequence?: Constructor<SequenceHandler>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expressSettings: {[name: string]: any};
router: RestRouterOptions;
}
/**
* Valid configuration for the RestServer constructor.
*/
export type RestServerConfig = RestServerOptions & HttpServerOptions;
export type RestServerResolvedConfig = RestServerResolvedOptions &
HttpServerOptions;
const DEFAULT_CONFIG: RestServerResolvedConfig = {
port: 3000,
openApiSpec: {},
apiExplorer: {},
cors: {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
maxAge: 86400,
credentials: true,
},
expressSettings: {},
router: {},
};
function resolveRestServerConfig(
config: RestServerConfig,
): RestServerResolvedConfig {
const result: RestServerResolvedConfig = Object.assign(
{},
DEFAULT_CONFIG,
config,
);
// Can't check falsiness, 0 is a valid port.
if (result.port == null) {
result.port = 3000;
}
if (result.host == null) {
// Set it to '' so that the http server will listen on all interfaces
result.host = undefined;
}