-
Notifications
You must be signed in to change notification settings - Fork 2
/
typed-router.ts
186 lines (165 loc) · 6.01 KB
/
typed-router.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
/** Type-safe wrapper around Express router for REST APIs */
import Ajv from 'ajv';
import express from 'express';
import {Endpoint} from './api-spec';
import { ExtractRouteParams, HTTPVerb, SafeKey } from './utils';
/** Throw this in a handler to produce an HTTP error response */
export class HTTPError extends Error {
code: number;
message: string;
constructor(code: number, message = '') {
super(`${code} ${message}`);
this.code = code;
this.message = message;
}
}
type RequestParams = Parameters<express.RequestHandler>;
type AnyEndpoint = Endpoint<any, any>;
export class TypedRouter<API> {
router: express.Router;
apiSchema?: any;
ajv?: Ajv.Ajv;
registrations: {path: string, method: HTTPVerb}[];
constructor(router: express.Router, apiSchema?: any) {
this.router = router;
if (apiSchema) {
this.apiSchema = apiSchema;
this.ajv = new Ajv({allErrors: true});
this.ajv.addSchema(apiSchema);
}
this.registrations = [];
}
get<
Path extends keyof API & string,
Spec extends SafeKey<API[Path], 'get'> = SafeKey<API[Path], 'get'>,
>(
route: Path,
handler: (
params: ExtractRouteParams<Path>,
request: express.Request<ExtractRouteParams<Path>, SafeKey<Spec, 'response'>>,
response: express.Response<SafeKey<Spec, 'response'>>,
) => Promise<Spec extends AnyEndpoint ? Spec['response'] : never>
) {
// TODO: fill in with a more streamlined implementation?
this.registerEndpoint(
'get' as any, route,
(params, _, request, response) => handler(params, request as any, response as any)
);
}
/** Register a handler on the router for the given path and verb */
registerEndpoint<
Path extends keyof API & string,
Method extends keyof API[Path] & HTTPVerb,
Spec extends API[Path][Method] = API[Path][Method]
>(
method: Method,
route: Path,
handler: (
params: ExtractRouteParams<Path>,
body: SafeKey<Spec, 'request'>,
request: express.Request<ExtractRouteParams<Path>, SafeKey<Spec, 'response'>, SafeKey<Spec, 'request'>>,
response: express.Response<SafeKey<Spec, 'response'>>,
) => Promise<Spec extends AnyEndpoint ? Spec['response'] : never>,
) {
const validate = this.getValidator(route, method);
this.registrations.push({path: route as string, method});
this.router[method](route as any, (...[req, response, next]: RequestParams) => {
const {body} = req;
if (validate && !validate(body)) {
return response.status(400).json({
error: this.ajv!.errorsText(validate.errors),
errors: validate.errors,
invalidRequest: body,
});
}
if (req.app.get('env') === 'test') {
// eslint-disable-next-line no-console
console.debug(method, route, 'params=', req.params, 'body=', body);
}
handler(req.params as any, body, req as any, response)
.then(responseObject => {
if (responseObject === null) {
// nothing to do. This can happen if the response redirected, say.
} else if (typeof responseObject === 'string') {
response.status(200).send(responseObject);
} else {
response.json(responseObject);
}
})
.catch((error: any) => {
// With target below ES2015, instanceof doesn't work here.
if (error instanceof HTTPError || (error.code)) {
response.status(error.code).json({error: error.message});
} else {
next(error);
}
});
});
}
/** Get a validation function for request bodies for the endpoint, or null if not applicable. */
getValidator(route: string, method: HTTPVerb): Ajv.ValidateFunction | null {
const {apiSchema} = this;
if (!apiSchema) {
return null;
}
const apiDef = apiSchema.properties as any;
if (!apiDef[route]) {
throw new Error(`API JSONSchema is missing entry for ${route}`);
}
const refSchema: string = apiDef[route].properties[method].$ref;
const endpoint = refSchema.slice('#/definitions/'.length);
const endpointTypes = (apiSchema.definitions as any)[endpoint].properties;
let requestType = endpointTypes.request;
if (requestType.$ref) {
requestType = requestType.$ref; // allow either references or inline types
} else if (requestType.type && requestType.type === 'null') {
requestType = null; // no request body, no validation
} else if (requestType.allOf) {
// TODO(danvk): figure out how to make ajv understand these.
throw new Error('Intersection types in APIs are not supported yet.');
}
if (requestType && this.ajv) {
let validate;
if (typeof requestType === 'string') {
validate = this.ajv.getSchema(requestType) ?? null;
} else {
// Create a new AJV validate for inline object types.
// This assumes these will never reference other type definitions.
const requestAjv = new Ajv();
validate = requestAjv.compile(requestType);
}
if (!validate) {
throw new Error(`Unable to get schema for '${requestType}'`);
}
return validate;
}
return null;
}
/** Throw if any routes declared in the API spec have not been implemented. */
assertAllRoutesRegistered() {
if (!this.apiSchema) {
throw new Error('TypedRouter.checkComplete requires JSON Schema');
}
const expected = new Set<string>();
const {
required: endpoints,
properties: endpointSpecs,
} = this.apiSchema;
for (const path of endpoints) {
const methods = endpointSpecs[path].required;
for (const method of methods) {
expected.add(`${method} ${path}`);
}
}
for (const {method, path} of this.registrations) {
const key = `${method} ${path}`;
expected.delete(key);
}
if (expected.size > 0) {
const missing = Array.from(expected.values()).join('\n');
throw new Error(
`Failed to register these endpoints, which were specified in API JSON Schema:\n${missing}`
);
}
}
}