-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathRouter.ts
More file actions
462 lines (417 loc) · 13 KB
/
Router.ts
File metadata and controls
462 lines (417 loc) · 13 KB
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
import { Logger } from '@rocket.chat/logger';
import type { Method } from '@rocket.chat/rest-typings';
import type { AnySchema } from 'ajv';
import express from 'express';
import type { Context, HonoRequest, MiddlewareHandler } from 'hono';
import { Hono } from 'hono';
import type { StatusCode } from 'hono/utils/http-status';
import qs from 'qs'; // Using qs specifically to keep express compatibility
import type { ResponseSchema, TypedOptions } from './definition';
import { honoAdapterForExpress } from './middlewares/honoAdapterForExpress';
const logger = new Logger('HttpRouter');
type MiddlewareHandlerListAndActionHandler<TOptions extends TypedOptions, TContext = (c: Context) => Promise<ResponseSchema<TOptions>>> = [
...MiddlewareHandler[],
TContext,
];
function splitArray<T, U>(arr: [...T[], U]): [T[], U] {
const last = arr[arr.length - 1];
const rest = arr.slice(0, -1) as T[];
return [rest, last as U];
}
function coerceDatesToStrings(obj: unknown): unknown {
if (Array.isArray(obj)) {
return obj.map(coerceDatesToStrings);
}
if (obj && typeof obj === 'object') {
const newObj: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
if (value instanceof Date) {
newObj[key] = value.toISOString();
} else {
newObj[key] = coerceDatesToStrings(value);
}
}
return newObj;
}
return obj;
}
export type Route = {
responses: Record<
number,
{
description: string;
content: {
'application/json': {
schema: AnySchema;
};
};
}
>;
parameters?: {
schema: AnySchema;
in: 'query';
name: 'query';
required: true;
}[];
requestBody?: {
required: true;
content: {
'application/json': {
schema: AnySchema;
};
};
};
security?: {
userId: [];
authToken: [];
}[];
tags?: string[];
};
export abstract class AbstractRouter<TActionCallback = (c: Context) => Promise<ResponseSchema<TypedOptions>>> {
protected abstract convertActionToHandler(action: TActionCallback): (c: Context) => Promise<ResponseSchema<TypedOptions>>;
}
export class Router<
TBasePath extends string,
TOperations extends {
[x: string]: unknown;
} = NonNullable<unknown>,
TActionCallback = (c: Context) => Promise<ResponseSchema<TypedOptions>>,
> extends AbstractRouter<TActionCallback> {
protected innerRouter: Hono<{
Variables: {
remoteAddress: string;
};
}>;
constructor(readonly base: TBasePath) {
super();
this.innerRouter = new Hono();
}
public typedRoutes: Record<string, Record<string, Route>> = {};
protected registerTypedRoutes<
TSubPathPattern extends string,
TOptions extends TypedOptions,
TPathPattern extends `${TBasePath}/${TSubPathPattern}`,
>(method: Method, subpath: TSubPathPattern, options: TOptions): void {
const path = `/${this.base}/${subpath}`.replaceAll('//', '/') as TPathPattern;
this.typedRoutes = this.typedRoutes || {};
this.typedRoutes[path] = this.typedRoutes[subpath] || {};
const { query, response = {}, authRequired, body, tags, ...rest } = options;
this.typedRoutes[path][method.toLowerCase()] = {
responses: Object.fromEntries(
Object.entries(response).map(([status, schema]) => [
parseInt(status, 10),
{
description: '',
content: {
'application/json': { schema: ('schema' in schema ? schema.schema : schema) as AnySchema },
},
},
]),
),
...(query && {
parameters: [
{
schema: query.schema,
in: 'query',
name: 'query',
required: true,
},
],
}),
...(body && {
requestBody: {
required: true,
content: {
'application/json': { schema: body.schema },
},
},
}),
...(authRequired && {
...rest,
security: [
{
userId: [],
authToken: [],
},
],
}),
tags,
};
}
protected async parseBodyParams<T extends Record<string, any>>({ request }: { request: HonoRequest; extra?: T }) {
try {
let parsedBody = {};
const contentType = request.header('content-type');
if (contentType?.includes('application/json')) {
parsedBody = await request.raw.clone().json();
} else if (contentType?.includes('multipart/form-data')) {
parsedBody = await request.raw.clone().formData();
} else if (contentType?.includes('application/x-www-form-urlencoded')) {
const req = await request.raw.clone().formData();
parsedBody = Object.fromEntries(req.entries());
} else {
parsedBody = await request.raw.clone().text();
}
// This is necessary to keep the compatibility with the previous version, otherwise the bodyParams will be an empty string when no content-type is sent
if (parsedBody === '') {
return {};
}
if (Array.isArray(parsedBody)) {
return parsedBody;
}
return { ...parsedBody };
// eslint-disable-next-line no-empty
} catch {}
return {};
}
protected parseQueryParams(request: HonoRequest) {
return qs.parse(request.raw.url.split('?')?.[1] || '');
}
protected method<TSubPathPattern extends string, TOptions extends TypedOptions>(
method: Method,
subpath: TSubPathPattern,
options: TOptions,
...actions: MiddlewareHandlerListAndActionHandler<TOptions, TActionCallback>
): Router<TBasePath, TOperations, TActionCallback> {
const [middlewares, action] = splitArray<MiddlewareHandler, TActionCallback>(actions);
const convertedAction = this.convertActionToHandler(action);
this.innerRouter[method.toLowerCase() as Lowercase<Method>](`/${subpath}`.replace('//', '/'), ...middlewares, async (c) => {
const { req, res } = c;
const queryParams = this.parseQueryParams(req);
if (options.query) {
const validatorFn = options.query;
if (typeof options.query === 'function' && !validatorFn(queryParams)) {
logger.warn({
msg: 'Query parameters validation failed - route spec does not match request payload',
method: req.method,
path: req.url,
error: validatorFn.errors?.map((error: any) => error.message).join('\n '),
});
return c.json(
{
success: false,
errorType: 'error-invalid-params',
error: validatorFn.errors?.map((error: any) => error.message).join('\n '),
},
400,
);
}
}
const bodyParams = await this.parseBodyParams({ request: req });
if (options.body) {
const validatorFn = options.body;
if (typeof options.body === 'function' && !validatorFn((req as any).bodyParams || bodyParams)) {
logger.warn({
msg: 'Request body validation failed - route spec does not match request payload',
method: req.method,
path: req.url,
error: validatorFn.errors?.map((error: any) => error.message).join('\n '),
});
return c.json(
{
success: false,
errorType: 'invalid-params',
error: validatorFn.errors?.map((error: any) => error.message).join('\n '),
},
400,
);
}
}
const response = await convertedAction(c);
const { body, statusCode, headers } = response as {
body: any;
statusCode: number;
headers?: Record<string, string>;
};
if (process.env.NODE_ENV === 'test' || process.env.TEST_MODE) {
const responseValidatorFn = options?.response?.[statusCode as keyof typeof options.response];
/* c8 ignore next 3 */
if (!responseValidatorFn && options.typed) {
throw new Error(`Missing response validator for endpoint ${req.method} - ${req.url} with status code ${statusCode}`);
}
if (responseValidatorFn && !responseValidatorFn(coerceDatesToStrings(body))) {
logger.warn({
msg: 'Response validation failed - response does not match route spec',
method: req.method,
path: req.url,
error: responseValidatorFn.errors?.map((error: any) => error.message).join('\n '),
});
return c.json(
{
success: false,
errorType: 'error-invalid-body',
error: `Invalid response for endpoint ${req.method} - ${req.url}. Error: ${responseValidatorFn.errors
?.map(
(error: any) =>
`${error.message} (${[
error.instancePath,
Object.entries(error.params)
.map(([key, value]) => `${key}: ${value}`)
.join(', '),
]
.filter(Boolean)
.join(' - ')})`,
)
.join('\n')}`,
},
400,
);
}
}
const responseHeaders = Object.fromEntries(
Object.entries({
...res.headers,
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
...headers,
}).map(([key, value]) => [key.toLowerCase(), value]),
);
const contentType = (responseHeaders['content-type'] || 'application/json') as string;
const isContentLess = (statusCode: number): statusCode is 101 | 204 | 205 | 304 => {
return [101, 204, 205, 304].includes(statusCode);
};
if (isContentLess(statusCode)) {
return c.status(statusCode as 101 | 204 | 205 | 304);
}
Object.entries(responseHeaders).forEach(([key, value]) => {
if (value) {
c.header(key, String(value));
}
});
return c.body((contentType?.match(/json|javascript/) ? JSON.stringify(body) : body) as any, statusCode as StatusCode);
});
this.registerTypedRoutes(method, subpath, options);
return this;
}
protected convertActionToHandler(action: TActionCallback): (c: Context) => Promise<ResponseSchema<TypedOptions>> {
// Default implementation simply passes through the action
// Subclasses can override this to provide custom handling
return action as (c: Context) => Promise<ResponseSchema<TypedOptions>>;
}
get<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TActionCallback>
): Router<
TBasePath,
| TOperations
| ({
method: 'GET';
path: TPathPattern;
} & Omit<TOptions, 'response'>),
TActionCallback
> {
return this.method('GET', subpath, options, ...action);
}
post<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TActionCallback>
): Router<
TBasePath,
| TOperations
| ({
method: 'POST';
path: TPathPattern;
} & Omit<TOptions, 'response'>),
TActionCallback
> {
return this.method('POST', subpath, options, ...action);
}
put<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TActionCallback>
): Router<
TBasePath,
| TOperations
| ({
method: 'PUT';
path: TPathPattern;
} & Omit<TOptions, 'response'>),
TActionCallback
> {
return this.method('PUT', subpath, options, ...action);
}
delete<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TActionCallback>
): Router<
TBasePath,
| TOperations
| ({
method: 'DELETE';
path: TPathPattern;
} & Omit<TOptions, 'response'>),
TActionCallback
> {
return this.method('DELETE', subpath, options, ...action);
}
use<FN extends MiddlewareHandler>(fn: FN): Router<TBasePath, TOperations, TActionCallback>;
use<IRouter extends Router<any, any, any>>(
innerRouter: IRouter,
): IRouter extends Router<any, infer IOperations, any>
? Router<TBasePath, ConcatPathOptions<TBasePath, IOperations, TOperations>, TActionCallback>
: never;
use(innerRouter: unknown): any {
if (innerRouter instanceof Router) {
this.typedRoutes = {
...this.typedRoutes,
...Object.fromEntries(Object.entries(innerRouter.typedRoutes).map(([path, routes]) => [`${this.base}${path}`, routes])),
};
this.innerRouter.route(innerRouter.base, innerRouter.innerRouter);
}
if (typeof innerRouter === 'function') {
this.innerRouter.use(innerRouter as any);
}
return this as any;
}
get router(): express.Router {
// eslint-disable-next-line new-cap
const router = express.Router();
const hono = new Hono();
router.use(
this.base,
honoAdapterForExpress(
hono.route(this.base, this.innerRouter).options('*', (c) => {
return c.body('OK');
}),
),
);
return router;
}
getHonoRouter(): Hono<{
Variables: {
remoteAddress: string;
};
}> {
return this.innerRouter;
}
}
type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
type ConcatPathOptions<
TPath extends string,
TOptions extends {
[x: string]: unknown;
},
TOther extends {
[x: string]: unknown;
},
> = Prettify<
Filter<
{
[x in keyof TOptions]: x extends 'path' ? (TOptions[x] extends string ? `${TPath}${TOptions[x]}` : never) : TOptions[x];
} & TOther
>
>;
type Filter<
TOther extends {
[x: string]: unknown;
},
> = TOther extends { method: Method; path: string } ? TOther : never;
export type ExtractRouterEndpoints<TRoute extends Router<any, any, any>> =
TRoute extends Router<any, infer TOperations, any> ? TOperations : never;