-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathcreateRouter.ts
More file actions
316 lines (304 loc) · 10.4 KB
/
Copy pathcreateRouter.ts
File metadata and controls
316 lines (304 loc) · 10.4 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
import * as DefaultFetchAPI from '@whatwg-node/fetch';
import { createServerAdapter } from '@whatwg-node/server';
import { useOpenAPI } from './plugins/openapi.js';
import { isLazySerializedResponse } from './Response.js';
import { HTTPMethod, TypedRequest, TypedResponse } from './typed-fetch.js';
import type {
AddRouteWithSchemasOpts,
OnRouteHook,
OnRouterInitHook,
OnSerializeResponseHook,
OpenAPIDocument,
OpenAPIInfo,
RouteHandler,
Router,
RouterBaseObject,
RouterComponentsBase,
RouterOptions,
RouterPlugin,
RouterSDK,
RouteSchemas,
} from './types.js';
import { addHandlersToMethod, PatternHandlersObj } from './utils.js';
import { useZod } from './zod/zod.js';
const HTTP_METHODS: HTTPMethod[] = [
'GET',
'HEAD',
'POST',
'PUT',
'DELETE',
'CONNECT',
'OPTIONS',
'TRACE',
'PATCH',
];
const EMPTY_OBJECT = {};
const EMPTY_MATCH = { pathname: { groups: {} } } as URLPatternResult;
export function createRouterBase<TServerContext>(
{
fetchAPI: givenFetchAPI,
base: basePath = '/',
plugins = [],
swaggerUI,
}: RouterOptions<TServerContext, any>,
openAPIDocument: OpenAPIDocument,
): RouterBaseObject<any, any, any> {
const fetchAPI = {
...DefaultFetchAPI,
...givenFetchAPI,
};
const __onRouterInitHooks: OnRouterInitHook<any>[] = [];
const onRouteHooks: OnRouteHook<any>[] = [];
const onSerializeResponseHooks: OnSerializeResponseHook<any>[] = [];
for (const plugin of plugins) {
if (plugin.onRouterInit) {
__onRouterInitHooks.push(plugin.onRouterInit);
}
if (plugin.onRoute) {
onRouteHooks.push(plugin.onRoute);
}
if (plugin.onSerializeResponse) {
onSerializeResponseHooks.push(plugin.onSerializeResponse);
}
}
const handlersByPatternByMethod = new Map<
HTTPMethod,
Map<URLPattern, RouteHandler<any, TypedRequest, TypedResponse>[]>
>();
const internalPatternsByMethod = new Map<HTTPMethod, Set<URLPattern>>();
// Use this in `handle` for iteration to get better performance
const patternHandlerObjByMethod = new Map<HTTPMethod, PatternHandlersObj<any>[]>();
return {
openAPIDocument,
async handle(request: Request, context: any) {
let url = new Proxy(EMPTY_OBJECT as URL, {
get(_target, prop, _receiver) {
url = new fetchAPI.URL(request.url, 'http://localhost');
return Reflect.get(url, prop, url);
},
}) as URL;
const methodPatternMaps = patternHandlerObjByMethod.get(request.method as HTTPMethod);
if (methodPatternMaps) {
const queryProxy = new Proxy(
{},
{
get(_, prop) {
if (prop !== 'then' && !url.searchParams.has(prop as string)) {
return undefined;
}
const allQueries = url.searchParams.getAll(prop.toString());
if (allQueries.length === 0) {
return '';
}
return allQueries.length === 1 ? allQueries[0] : allQueries;
},
has(_, prop) {
return url.searchParams.has(prop.toString());
},
},
);
for (const { pattern, handlers } of methodPatternMaps) {
// Do not parse URL if not needed
let match: URLPatternResult | null = null;
if (pattern.isPattern) {
match = pattern.exec(url);
} else if (request.url.endsWith(pattern.pathname) || url.pathname === pattern.pathname) {
match = EMPTY_MATCH;
}
if (match != null) {
const routerRequest = new Proxy(request as any, {
get(target, prop: keyof TypedRequest) {
if (prop === 'parsedUrl') {
return url;
}
if (prop === 'params') {
return new Proxy(match!.pathname.groups, {
get(_, prop) {
const value = (match!.pathname.groups as Record<string, string>)[
prop.toString()
];
if (value != null) {
return decodeURIComponent(value);
}
return value;
},
});
}
if (prop === 'query') {
return queryProxy;
}
const targetProp = target[prop];
if (typeof targetProp === 'function') {
return targetProp.bind(target);
}
return targetProp;
},
has(target, prop) {
return (
prop in target || prop === 'parsedUrl' || prop === 'params' || prop === 'query'
);
},
});
for (const handler of handlers) {
const handlerResult = await handler(routerRequest, context);
if (handlerResult) {
if (isLazySerializedResponse(handlerResult)) {
for (const onSerializeResponseHook of onSerializeResponseHooks) {
onSerializeResponseHook({
request: routerRequest,
path: pattern.pathname,
lazyResponse: handlerResult,
serverContext: context,
});
}
return (
handlerResult.actualResponse ||
fetchAPI.Response.json(handlerResult.jsonObj, handlerResult.init)
);
}
return handlerResult;
}
}
}
}
}
if (swaggerUI?.endpoint) {
return new fetchAPI.Response(null, {
status: 302,
headers: {
location: swaggerUI.endpoint,
},
});
}
return new fetchAPI.Response(null, { status: 404 });
},
route(
opts: AddRouteWithSchemasOpts<
any,
any,
RouteSchemas,
HTTPMethod,
string,
TypedRequest,
TypedResponse
>,
) {
const { operationId, description, method, path, schemas, tags, internal, handler } = opts;
const handlers = Array.isArray(handler) ? handler : [handler];
if (!method) {
for (const method of HTTP_METHODS) {
addHandlersToMethod({
operationId,
description,
method,
path,
schemas,
handlers,
tags,
internal,
// Router specific
onRouteHooks,
openAPIDocument,
basePath,
fetchAPI,
handlersByPatternByMethod,
internalPatternsByMethod,
patternHandlerObjByMethod,
});
}
} else {
addHandlersToMethod({
operationId,
description,
method,
path,
schemas,
handlers,
tags,
internal,
// Router specific
onRouteHooks,
openAPIDocument,
basePath,
fetchAPI,
handlersByPatternByMethod,
internalPatternsByMethod,
patternHandlerObjByMethod,
});
}
return this as any;
},
__client: {},
__onRouterInitHooks,
};
}
export function createRouter<
TServerContext,
TComponents extends RouterComponentsBase,
TRouterSDK extends RouterSDK<string, TypedRequest, TypedResponse> = {
[TKey: string]: never;
},
>(
options?: RouterOptions<TServerContext, TComponents> | undefined,
): Router<TServerContext, TComponents, TRouterSDK> {
const {
openAPI: { endpoint: oasEndpoint = '/openapi.json', ...openAPIDocument } = {},
swaggerUI: { endpoint: swaggerUIEndpoint = '/docs', ...swaggerUIOpts } = {},
plugins: userPlugins = [],
base = '/',
} = options || {};
openAPIDocument.openapi = openAPIDocument.openapi || '3.0.1';
const oasInfo = (openAPIDocument.info ||= {} as OpenAPIInfo);
oasInfo.title ||= 'feTS API';
oasInfo.description ||= 'An API written with feTS';
oasInfo.version ||= '1.0.0';
if (base !== '/') {
openAPIDocument.servers = openAPIDocument.servers || [
{
url: base,
},
];
}
const plugins: RouterPlugin<TServerContext>[] = [
...(oasEndpoint || swaggerUIEndpoint
? [
useOpenAPI({
oasEndpoint,
swaggerUIEndpoint,
swaggerUIOpts,
}),
]
: []),
useZod(),
...userPlugins,
];
const finalOpts: RouterOptions<TServerContext, TComponents> = {
...options,
swaggerUI: {
endpoint: swaggerUIEndpoint,
...swaggerUIOpts,
},
base,
plugins,
};
const routerBaseObject = createRouterBase(finalOpts, openAPIDocument as OpenAPIDocument);
// Argument of type 'RouterOptions<TServerContext, TComponents>' is not assignable to parameter of type 'ServerAdapterOptions<TServerContext>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
// Types of property 'plugins' are incompatible.
// Type 'RouterPlugin<TServerContext>[] | undefined' is not assignable to type 'ServerAdapterPlugin<TServerContext>[]'.
// Type 'undefined' is not assignable to type 'ServerAdapterPlugin<TServerContext>[]'.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const router = createServerAdapter(routerBaseObject, finalOpts);
for (const onRouterInitHook of routerBaseObject.__onRouterInitHooks) {
// Argument of type 'ServerAdapter<TServerContext, ServerAdapterBaseObject<TServerContext, ServerAdapterRequestHandler<TServerContext>>>' is not assignable to parameter of type 'Router<any, any, any>'.
// Type 'ServerAdapter<TServerContext, ServerAdapterBaseObject<TServerContext, ServerAdapterRequestHandler<TServerContext>>>' is not assignable to type 'RouterBaseObject<any, any, any>'.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
onRouterInitHook(router);
}
// Type 'ServerAdapter<TServerContext, ServerAdapterBaseObject<TServerContext, ServerAdapterRequestHandler<TServerContext>>>' is not assignable to type 'Router<TServerContext, TComponents, TRouterSDK>'.
// Type 'ServerAdapter<TServerContext, ServerAdapterBaseObject<TServerContext, ServerAdapterRequestHandler<TServerContext>>>' is not assignable to type 'RouterBaseObject<TServerContext, TComponents, TRouterSDK>'.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return router;
}