-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
external-express-routes.ts
176 lines (156 loc) · 4.72 KB
/
external-express-routes.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
// Copyright IBM Corp. 2017, 2018. 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 {Context} from '@loopback/context';
import {
OpenApiSpec,
OperationObject,
SchemasObject,
} from '@loopback/openapi-v3-types';
import * as express from 'express';
import {PathParams} from 'express-serve-static-core';
import * as HttpErrors from 'http-errors';
import {ServeStaticOptions} from 'serve-static';
import {ResolvedRoute, RouteEntry} from '.';
import {RequestContext} from '../request-context';
import {
OperationArgs,
OperationRetval,
PathParameterValues,
Request,
Response,
} from '../types';
import {assignRouterSpec, RouterSpec} from './router-spec';
export type ExpressRequestHandler = express.RequestHandler;
/**
* A registry of external, Express-style routes. These routes are invoked
* _after_ no LB4 route (controller or handler based) matched the incoming
* request.
*/
export class ExternalExpressRoutes {
protected _externalRoutes: express.Router = express.Router();
protected _specForExternalRoutes: RouterSpec = {paths: {}};
protected _staticRoutes: express.Router = express.Router();
get routerSpec(): RouterSpec {
return this._specForExternalRoutes;
}
public registerAssets(
path: PathParams,
rootDir: string,
options?: ServeStaticOptions,
) {
this._staticRoutes.use(path, express.static(rootDir, options));
}
public mountRouter(
basePath: string,
router: ExpressRequestHandler,
spec: RouterSpec = {paths: {}},
) {
this._externalRoutes.use(basePath, router);
spec = rebaseOpenApiSpec(spec, basePath);
assignRouterSpec(this._specForExternalRoutes, spec);
}
find(request: Request): ResolvedRoute {
// TODO(bajtos) look up OpenAPI spec for matching LB3 route?
return new ExternalRoute(
this._externalRoutes,
this._staticRoutes,
request.method,
request.url,
// TODO(bajtos) look-up the spec from `this.specForExternalRoutes`
{
description: 'LoopBack static assets route',
'x-visibility': 'undocumented',
responses: {},
},
);
}
}
class ExternalRoute implements RouteEntry, ResolvedRoute {
// ResolvedRoute API
readonly pathParams: PathParameterValues = [];
readonly schemas: SchemasObject = {};
constructor(
private readonly _externalRouter: express.Router,
private readonly _staticAssets: express.Router,
public readonly verb: string,
public readonly path: string,
public readonly spec: OperationObject,
) {}
updateBindings(requestContext: Context): void {
// no-op
}
async invokeHandler(
context: RequestContext,
args: OperationArgs,
): Promise<OperationRetval> {
const {request, response} = context;
let handled = await executeRequestHandler(
this._externalRouter,
request,
response,
);
if (handled) return;
handled = await executeRequestHandler(
this._staticAssets,
request,
response,
);
if (handled) return;
// Express router called next, which means no route was matched
throw new HttpErrors.NotFound(
`Endpoint "${request.method} ${request.path}" not found.`,
);
}
describe(): string {
// TODO(bajtos) provide better description for Express routes with spec
return `external Express route "${this.verb} ${this.path}"`;
}
}
export function rebaseOpenApiSpec<T extends Partial<OpenApiSpec>>(
spec: T,
basePath: string,
): T {
if (!spec.paths) return spec;
if (!basePath || basePath === '/') return spec;
const localPaths = spec.paths;
// Don't modify the spec object provided to us.
spec = Object.assign({}, spec);
spec.paths = {};
for (const url in localPaths) {
spec.paths[`${basePath}${url}`] = localPaths[url];
}
return spec;
}
/**
* Execute an Express-style callback-based request handler.
*
* @param handler
* @param request
* @param response
* @returns A promise resolved to:
* - `true` when the request was handled
* - `false` when the handler called `next()` to proceed to the next
* handler (middleware) in the chain.
*/
export function executeRequestHandler(
handler: express.RequestHandler,
request: Request,
response: Response,
): Promise<boolean> {
return new Promise((resolve, reject) => {
const onceFinished = () => resolve(true);
// FIXME(bajtos) use on-finished module instead
response.once('finish', onceFinished);
handler(request, response, (err: Error) => {
response.removeListener('finish', onceFinished);
if (err) {
reject(err);
} else {
// Express router called next, which means no route was matched
resolve(false);
}
});
});
}