burger-api 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -16
- package/dist/src/core/api-router.d.ts +53 -0
- package/dist/src/core/api-router.js +93 -3
- package/dist/src/core/openapi.js +58 -1
- package/dist/src/core/page-router.d.ts +43 -0
- package/dist/src/core/page-router.js +72 -1
- package/dist/src/core/server.d.ts +10 -0
- package/dist/src/core/server.js +16 -0
- package/dist/src/index.d.ts +75 -0
- package/dist/src/index.js +264 -47
- package/dist/src/middleware/validator.d.ts +12 -0
- package/dist/src/middleware/validator.js +59 -9
- package/dist/src/types/index.d.ts +143 -1
- package/dist/src/utils/error.d.ts +16 -0
- package/dist/src/utils/error.js +24 -0
- package/dist/src/utils/index.d.ts +17 -0
- package/dist/src/utils/index.js +22 -0
- package/dist/src/utils/response.d.ts +9 -0
- package/dist/src/utils/response.js +9 -0
- package/dist/src/utils/routing.d.ts +28 -0
- package/dist/src/utils/routing.js +41 -3
- package/dist/src/utils/wildcard.d.ts +11 -0
- package/dist/src/utils/wildcard.js +42 -6
- package/package.json +1 -1
package/dist/src/index.js
CHANGED
|
@@ -1,186 +1,403 @@
|
|
|
1
|
+
// Import stuff from core
|
|
1
2
|
import { Server } from './core/server';
|
|
2
3
|
import { ApiRouter } from './core/api-router';
|
|
3
4
|
import { PageRouter } from './core/page-router';
|
|
4
5
|
import { generateOpenAPIDocument } from './core/openapi';
|
|
5
6
|
import { swaggerHtml } from './core/swagger-ui';
|
|
7
|
+
// Import utils
|
|
6
8
|
import { collectRoutes } from './utils/index';
|
|
7
9
|
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
|
|
8
10
|
import { extractPathnameFromUrl, extractWildcardParams, } from './utils/wildcard';
|
|
11
|
+
// Import middleware
|
|
9
12
|
import { createValidationMiddleware } from './middleware/validator';
|
|
10
13
|
export class Burger {
|
|
11
14
|
options;
|
|
15
|
+
/**
|
|
16
|
+
* The server instance
|
|
17
|
+
*/
|
|
12
18
|
server;
|
|
19
|
+
/**
|
|
20
|
+
* The API router instance
|
|
21
|
+
*/
|
|
13
22
|
apiRouter;
|
|
23
|
+
/**
|
|
24
|
+
* The page router instance
|
|
25
|
+
*/
|
|
14
26
|
pageRouter;
|
|
27
|
+
/**
|
|
28
|
+
* The global middleware
|
|
29
|
+
*/
|
|
15
30
|
globalMiddleware = [];
|
|
31
|
+
/**
|
|
32
|
+
* The OpenAPI document
|
|
33
|
+
*/
|
|
16
34
|
openApiDoc = null;
|
|
35
|
+
/**
|
|
36
|
+
* The routes object
|
|
37
|
+
*/
|
|
17
38
|
routes = {};
|
|
39
|
+
/**
|
|
40
|
+
* Pre-computed responses for reuse
|
|
41
|
+
*/
|
|
18
42
|
METHOD_NOT_ALLOWED = METHOD_NOT_ALLOWED;
|
|
43
|
+
/**
|
|
44
|
+
* The not found response
|
|
45
|
+
*/
|
|
19
46
|
NOT_FOUND = NOT_FOUND;
|
|
47
|
+
/**
|
|
48
|
+
* The OpenAPI error response
|
|
49
|
+
*/
|
|
20
50
|
OPENAPI_ERROR = OPENAPI_ERROR;
|
|
51
|
+
/**
|
|
52
|
+
* Constructor for the Burger class.
|
|
53
|
+
* @param options - The options for the server and router.
|
|
54
|
+
* The options object should contain the following properties:
|
|
55
|
+
* - port: The port number to listen on.
|
|
56
|
+
* - apiDir: The directory path to load API routes from.
|
|
57
|
+
* - pageDir: The directory path to load page routes from.
|
|
58
|
+
* - middleware: An array of global middleware functions.
|
|
59
|
+
*/
|
|
21
60
|
constructor(options) {
|
|
22
61
|
this.options = options;
|
|
62
|
+
// Create server instance
|
|
23
63
|
this.server = new Server(options);
|
|
64
|
+
// Fast initialization for routers with nullish coalescing
|
|
24
65
|
const { apiDir, pageDir, apiPrefix, pagePrefix, globalMiddleware } = options;
|
|
66
|
+
// Initialize API router if apiDir is provided
|
|
25
67
|
this.apiRouter = apiDir
|
|
26
68
|
? new ApiRouter(apiDir, apiPrefix || 'api')
|
|
27
69
|
: undefined;
|
|
70
|
+
// Initialize page router if pageDir is provided
|
|
28
71
|
this.pageRouter = pageDir
|
|
29
72
|
? new PageRouter(pageDir, pagePrefix || '')
|
|
30
73
|
: undefined;
|
|
74
|
+
// Add global middleware if any
|
|
31
75
|
this.globalMiddleware = globalMiddleware?.length
|
|
32
76
|
? globalMiddleware.slice()
|
|
33
77
|
: [];
|
|
34
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* Process the page routes and add them to the routes object
|
|
81
|
+
* @returns A promise that resolves to a boolean
|
|
82
|
+
*/
|
|
35
83
|
async processPageRoutes() {
|
|
84
|
+
// If no page router, return false
|
|
36
85
|
if (!this.pageRouter)
|
|
37
86
|
return false;
|
|
87
|
+
// Load pages routes
|
|
38
88
|
await this.pageRouter.loadPages();
|
|
89
|
+
// If there are any page routes, add them to the routes object
|
|
39
90
|
const pages = this.pageRouter.pages;
|
|
91
|
+
// Get the length of the pages routes
|
|
40
92
|
const pageCount = pages.length;
|
|
93
|
+
// If no pages, return false
|
|
41
94
|
if (pageCount === 0)
|
|
42
95
|
return false;
|
|
96
|
+
// Loop through the pages
|
|
43
97
|
for (let i = 0; i < pageCount; i++) {
|
|
98
|
+
// Get the current page
|
|
44
99
|
const page = pages[i];
|
|
100
|
+
// Add the page to the routes
|
|
45
101
|
this.routes[page.path] = page.handler;
|
|
46
102
|
}
|
|
103
|
+
// Return true if there are any pages
|
|
47
104
|
return true;
|
|
48
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Process the API routes and add them to the routes object
|
|
108
|
+
* @returns A promise that resolves to a boolean
|
|
109
|
+
*/
|
|
49
110
|
async processApiRoutes() {
|
|
111
|
+
// If no api router, return false
|
|
50
112
|
if (!this.apiRouter)
|
|
51
113
|
return false;
|
|
114
|
+
// Load API routes
|
|
52
115
|
await this.apiRouter.loadRoutes();
|
|
116
|
+
// Collect API routes
|
|
53
117
|
const apiRoutes = collectRoutes(this.apiRouter.routes);
|
|
118
|
+
// Get the length of the API routes
|
|
54
119
|
const routeCount = apiRoutes.length;
|
|
120
|
+
// If there are no API routes, return false
|
|
55
121
|
if (routeCount === 0)
|
|
56
122
|
return false;
|
|
123
|
+
// Generate OpenAPI document and cache it
|
|
57
124
|
this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options);
|
|
125
|
+
// Cache frequently accessed properties
|
|
58
126
|
const routes = this.routes;
|
|
127
|
+
// Get the global middleware
|
|
59
128
|
const globalMiddleware = this.globalMiddleware;
|
|
129
|
+
// Get the length of the global middleware
|
|
60
130
|
const globalMiddlewareLen = globalMiddleware.length;
|
|
131
|
+
// Process each route with optimized handler creation
|
|
61
132
|
for (let i = 0; i < routeCount; i++) {
|
|
133
|
+
/**
|
|
134
|
+
* ================================================
|
|
135
|
+
* Pre-compute the required functionality start
|
|
136
|
+
* ================================================
|
|
137
|
+
*/
|
|
138
|
+
// Get the current route object
|
|
62
139
|
const route = apiRoutes[i];
|
|
140
|
+
// Destructure the route object
|
|
63
141
|
const { path, schema, middleware: routeMiddleware, handlers, } = route;
|
|
142
|
+
// Get length of route specific middleware
|
|
64
143
|
const routeMiddlewareLen = routeMiddleware?.length || 0;
|
|
144
|
+
// Check if schema exists
|
|
65
145
|
const hasSchema = !!schema;
|
|
146
|
+
// Optimize middleware array initialization by pre-allocating size
|
|
66
147
|
const totalMiddlewareCount = globalMiddlewareLen + (hasSchema ? 1 : 0) + routeMiddlewareLen;
|
|
148
|
+
// Pre-compute wildcard info once (used in all paths)
|
|
149
|
+
const isWildcard = route.isWildcard;
|
|
150
|
+
const baseSegmentCount = isWildcard
|
|
151
|
+
? path.split('/').filter(Boolean).length - 1
|
|
152
|
+
: 0;
|
|
153
|
+
// Create optimized route handler based on middleware count
|
|
67
154
|
if (totalMiddlewareCount === 0) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (isWildcard) {
|
|
155
|
+
// Ultra-fast path: no middleware at all
|
|
156
|
+
// Inline everything for maximum speed
|
|
157
|
+
if (isWildcard) {
|
|
158
|
+
// Wildcard route with no middleware
|
|
159
|
+
routes[path] = (request) => {
|
|
74
160
|
const pathname = extractPathnameFromUrl(request.url);
|
|
75
161
|
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
162
|
+
const handler = handlers[request.method];
|
|
163
|
+
return handler
|
|
164
|
+
? handler(request)
|
|
165
|
+
: this.METHOD_NOT_ALLOWED;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
// Regular route with no middleware (most common case)
|
|
170
|
+
routes[path] = (request) => {
|
|
171
|
+
const handler = handlers[request.method];
|
|
172
|
+
return handler
|
|
173
|
+
? handler(request)
|
|
174
|
+
: this.METHOD_NOT_ALLOWED;
|
|
175
|
+
};
|
|
176
|
+
}
|
|
80
177
|
}
|
|
81
178
|
else {
|
|
179
|
+
// Pre-compute middleware array with exact size (AOT optimization)
|
|
82
180
|
const middlewares = new Array(totalMiddlewareCount);
|
|
83
|
-
let
|
|
181
|
+
let idx = 0;
|
|
182
|
+
// Copy global middleware (manual loop is faster than spread/concat)
|
|
84
183
|
for (let j = 0; j < globalMiddlewareLen; j++) {
|
|
85
|
-
middlewares[
|
|
184
|
+
middlewares[idx++] = globalMiddleware[j];
|
|
86
185
|
}
|
|
186
|
+
// Add validation middleware if needed
|
|
87
187
|
if (hasSchema) {
|
|
88
|
-
middlewares[
|
|
188
|
+
middlewares[idx++] = createValidationMiddleware(schema);
|
|
89
189
|
}
|
|
190
|
+
// Add route-specific middlewares
|
|
90
191
|
if (routeMiddleware) {
|
|
91
192
|
for (let j = 0; j < routeMiddlewareLen; j++) {
|
|
92
|
-
middlewares[
|
|
193
|
+
middlewares[idx++] = routeMiddleware[j];
|
|
93
194
|
}
|
|
94
195
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
routes[path] = (request) => {
|
|
196
|
+
// Create specialized handler based on middleware count
|
|
197
|
+
if (totalMiddlewareCount === 1) {
|
|
198
|
+
// Single middleware fast path (common: just CORS or just auth)
|
|
199
|
+
const singleMiddleware = middlewares[0];
|
|
100
200
|
if (isWildcard) {
|
|
101
|
-
|
|
102
|
-
|
|
201
|
+
routes[path] = (request) => {
|
|
202
|
+
const pathname = extractPathnameFromUrl(request.url);
|
|
203
|
+
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
204
|
+
const handler = handlers[request.method];
|
|
205
|
+
if (!handler)
|
|
206
|
+
return this.METHOD_NOT_ALLOWED;
|
|
207
|
+
return this.processSingleMiddleware(request, singleMiddleware, handler);
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
routes[path] = (request) => {
|
|
212
|
+
const handler = handlers[request.method];
|
|
213
|
+
if (!handler)
|
|
214
|
+
return this.METHOD_NOT_ALLOWED;
|
|
215
|
+
return this.processSingleMiddleware(request, singleMiddleware, handler);
|
|
216
|
+
};
|
|
103
217
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
// Multiple middlewares (general case)
|
|
221
|
+
if (isWildcard) {
|
|
222
|
+
routes[path] = (request) => {
|
|
223
|
+
const pathname = extractPathnameFromUrl(request.url);
|
|
224
|
+
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
225
|
+
const handler = handlers[request.method];
|
|
226
|
+
if (!handler)
|
|
227
|
+
return this.METHOD_NOT_ALLOWED;
|
|
228
|
+
return this.processMiddleware(request, middlewares, handler);
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
routes[path] = (request) => {
|
|
233
|
+
const handler = handlers[request.method];
|
|
234
|
+
if (!handler)
|
|
235
|
+
return this.METHOD_NOT_ALLOWED;
|
|
236
|
+
return this.processMiddleware(request, middlewares, handler);
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
109
240
|
}
|
|
241
|
+
// For wildcard routes, also register the base path
|
|
242
|
+
// Bun's /* wildcard may not match the base path itself, so we register both
|
|
110
243
|
if (route.isWildcard && path.endsWith('/*')) {
|
|
111
|
-
const basePath = path.slice(0, -2);
|
|
244
|
+
const basePath = path.slice(0, -2); // Remove "/*" to get base path
|
|
245
|
+
// Only register base path if no static route exists (preserve priority)
|
|
246
|
+
// Static routes have highest priority: Static > Dynamic > Wildcard
|
|
112
247
|
if (!routes[basePath]) {
|
|
248
|
+
// No static route found, register wildcard for base path
|
|
113
249
|
routes[basePath] = routes[path];
|
|
114
250
|
}
|
|
251
|
+
// If static route exists, it takes priority (correct behavior)
|
|
115
252
|
}
|
|
116
253
|
}
|
|
254
|
+
// Add special routes for OpenAPI
|
|
117
255
|
routes['/openapi.json'] = () => this.openApiDoc
|
|
118
256
|
? Response.json(this.openApiDoc)
|
|
119
257
|
: this.OPENAPI_ERROR;
|
|
258
|
+
// Add special route for Swagger UI
|
|
120
259
|
routes['/docs'] = () => new Response(swaggerHtml, {
|
|
121
260
|
headers: { 'Content-Type': 'text/html' },
|
|
122
261
|
});
|
|
123
262
|
return true;
|
|
124
263
|
}
|
|
264
|
+
/**
|
|
265
|
+
* Process single middleware
|
|
266
|
+
* @param request - The request object
|
|
267
|
+
* @param middleware - The middleware function
|
|
268
|
+
* @param handler - The handler function
|
|
269
|
+
* @returns A promise that resolves to a response
|
|
270
|
+
*/
|
|
271
|
+
async processSingleMiddleware(request, middleware, handler) {
|
|
272
|
+
const result = await middleware(request);
|
|
273
|
+
// Short-circuit with Response
|
|
274
|
+
if (result instanceof Response) {
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
277
|
+
// Transform response after handler
|
|
278
|
+
if (typeof result === 'function') {
|
|
279
|
+
return result(await handler(request));
|
|
280
|
+
}
|
|
281
|
+
// Continue to handler
|
|
282
|
+
return handler(request);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Process middleware and handler
|
|
286
|
+
*
|
|
287
|
+
* How it works:
|
|
288
|
+
* 1. Run each middleware in order
|
|
289
|
+
* 2. If middleware returns Response → stop and send that response (but still apply "after" functions)
|
|
290
|
+
* 3. If middleware returns undefined → continue to next middleware
|
|
291
|
+
* 4. If middleware returns function → save it to transform the final response later
|
|
292
|
+
* 5. After all middlewares, run the handler
|
|
293
|
+
* 6. Apply all saved "after" functions to the response (in reverse order)
|
|
294
|
+
*
|
|
295
|
+
* Performance optimizations:
|
|
296
|
+
* - Pre-allocated array for "after" functions (avoids dynamic resizing)
|
|
297
|
+
* - Fast paths for 0, 1, and 2 middlewares (most common cases)
|
|
298
|
+
* - Manual loop unrolling for small counts
|
|
299
|
+
* - Minimal branching in hot path
|
|
300
|
+
*/
|
|
125
301
|
async processMiddleware(request, middlewares, handler) {
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
302
|
+
const len = middlewares.length;
|
|
303
|
+
// Fast path: two middlewares (common: CORS + logger, or auth + logger)
|
|
304
|
+
if (len === 2) {
|
|
305
|
+
// First middleware
|
|
306
|
+
const result1 = await middlewares[0](request);
|
|
307
|
+
if (result1 instanceof Response) {
|
|
308
|
+
return result1;
|
|
131
309
|
}
|
|
132
|
-
|
|
133
|
-
|
|
310
|
+
// Second middleware
|
|
311
|
+
const result2 = await middlewares[1](request);
|
|
312
|
+
if (result2 instanceof Response) {
|
|
313
|
+
// Apply first middleware's after function if exists
|
|
314
|
+
if (typeof result1 === 'function') {
|
|
315
|
+
return result1(result2);
|
|
316
|
+
}
|
|
317
|
+
return result2;
|
|
134
318
|
}
|
|
135
|
-
|
|
319
|
+
// Run handler
|
|
320
|
+
let response = await handler(request);
|
|
321
|
+
// Apply after functions in reverse order (manual unroll)
|
|
322
|
+
if (typeof result2 === 'function') {
|
|
323
|
+
response = await result2(response);
|
|
324
|
+
}
|
|
325
|
+
if (typeof result1 === 'function') {
|
|
326
|
+
response = await result1(response);
|
|
327
|
+
}
|
|
328
|
+
return response;
|
|
136
329
|
}
|
|
137
|
-
|
|
330
|
+
// General path: 3+ middlewares (less common)
|
|
331
|
+
// Pre-allocate array with exact size to avoid dynamic resizing
|
|
332
|
+
const afterStack = new Array(len);
|
|
138
333
|
let afterCount = 0;
|
|
139
|
-
|
|
334
|
+
// Run each middleware
|
|
335
|
+
for (let i = 0; i < len; i++) {
|
|
140
336
|
const result = await middlewares[i](request);
|
|
337
|
+
// Short-circuit with Response (check first - most common early exit)
|
|
141
338
|
if (result instanceof Response) {
|
|
339
|
+
// Apply collected "after" functions in reverse
|
|
340
|
+
if (afterCount === 0)
|
|
341
|
+
return result;
|
|
342
|
+
if (afterCount === 1)
|
|
343
|
+
return afterStack[0](result);
|
|
344
|
+
// Multiple after functions
|
|
142
345
|
let response = result;
|
|
143
|
-
if (afterCount === 0) {
|
|
144
|
-
return response;
|
|
145
|
-
}
|
|
146
|
-
if (afterCount === 1) {
|
|
147
|
-
return afterStack[0](response);
|
|
148
|
-
}
|
|
149
346
|
for (let j = afterCount - 1; j >= 0; j--) {
|
|
150
347
|
response = await afterStack[j](response);
|
|
151
348
|
}
|
|
152
349
|
return response;
|
|
153
350
|
}
|
|
154
|
-
|
|
351
|
+
// Save function for later (check once, no double typeof check)
|
|
352
|
+
if (typeof result === 'function') {
|
|
155
353
|
afterStack[afterCount++] = result;
|
|
156
354
|
}
|
|
355
|
+
// undefined - continue (implicit, no check needed)
|
|
157
356
|
}
|
|
357
|
+
// All middlewares passed - run handler
|
|
158
358
|
let response = await handler(request);
|
|
159
|
-
|
|
359
|
+
// Apply "after" functions in reverse order
|
|
360
|
+
// Fast paths for common cases
|
|
361
|
+
if (afterCount === 0)
|
|
160
362
|
return response;
|
|
161
|
-
|
|
162
|
-
|
|
363
|
+
if (afterCount === 1)
|
|
364
|
+
return afterStack[0](response);
|
|
365
|
+
if (afterCount === 2) {
|
|
366
|
+
response = await afterStack[1](response);
|
|
163
367
|
return afterStack[0](response);
|
|
164
368
|
}
|
|
369
|
+
// General case: 3+ after functions
|
|
165
370
|
for (let i = afterCount - 1; i >= 0; i--) {
|
|
166
371
|
response = await afterStack[i](response);
|
|
167
372
|
}
|
|
168
373
|
return response;
|
|
169
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* Starts the server and begins listening for incoming requests.
|
|
377
|
+
* @param port - The port number to listen on. Defaults to `4000`.
|
|
378
|
+
* @param cb - An optional cb function to be executed when the server is listening.
|
|
379
|
+
* @returns A Promise that resolves when the server has started listening.
|
|
380
|
+
*/
|
|
170
381
|
async serve(port = 4000, cb) {
|
|
382
|
+
// Process routes in parallel if possible
|
|
171
383
|
const [pagesConfigured, apiConfigured] = await Promise.all([
|
|
172
384
|
this.processPageRoutes(),
|
|
173
385
|
this.processApiRoutes(),
|
|
174
386
|
]);
|
|
387
|
+
// Flag to track if any routes were loaded
|
|
175
388
|
const routesConfigured = pagesConfigured || apiConfigured;
|
|
389
|
+
// If routes were configured, start the server
|
|
176
390
|
if (routesConfigured) {
|
|
391
|
+
// Start the server
|
|
177
392
|
this.server.start(this.routes, async () => {
|
|
178
393
|
return this.NOT_FOUND;
|
|
179
394
|
}, port, cb);
|
|
180
395
|
}
|
|
181
396
|
else {
|
|
397
|
+
// If no routes were configured, log an error
|
|
182
398
|
console.error('Error: No routes configured! Please provide either apiDir with route.ts files or pageDir with html files when initializing the Burger Class.');
|
|
183
399
|
}
|
|
184
400
|
}
|
|
185
401
|
}
|
|
402
|
+
// Export utils
|
|
186
403
|
export { setDir } from './utils/index';
|
|
@@ -1,2 +1,14 @@
|
|
|
1
1
|
import type { RouteSchema, Middleware } from '../types/index';
|
|
2
|
+
/**
|
|
3
|
+
* createValidationMiddleware:
|
|
4
|
+
* - Precompute a smaller runtime descriptor per method to avoid
|
|
5
|
+
* repeatedly touching the full schema object on every request.
|
|
6
|
+
* - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
|
|
7
|
+
* - Parses querystring manually (no URL constructor, no throw).
|
|
8
|
+
* - Lazily allocates the errors container only when needed.
|
|
9
|
+
* - Avoids unnecessary object allocations for successful paths.
|
|
10
|
+
*
|
|
11
|
+
* @param schema - The route schema to validate the request against.
|
|
12
|
+
* @returns The middleware function that validates the request.
|
|
13
|
+
*/
|
|
2
14
|
export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
|
|
@@ -1,29 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createValidationMiddleware:
|
|
3
|
+
* - Precompute a smaller runtime descriptor per method to avoid
|
|
4
|
+
* repeatedly touching the full schema object on every request.
|
|
5
|
+
* - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
|
|
6
|
+
* - Parses querystring manually (no URL constructor, no throw).
|
|
7
|
+
* - Lazily allocates the errors container only when needed.
|
|
8
|
+
* - Avoids unnecessary object allocations for successful paths.
|
|
9
|
+
*
|
|
10
|
+
* @param schema - The route schema to validate the request against.
|
|
11
|
+
* @returns The middleware function that validates the request.
|
|
12
|
+
*/
|
|
1
13
|
export function createValidationMiddleware(schema) {
|
|
14
|
+
// Precompute a minimal descriptor per HTTP method (lowercased)
|
|
15
|
+
// This work runs once at middleware creation time (fast startup cost, zero cost on each request for those computations).
|
|
2
16
|
const methodMap = {};
|
|
17
|
+
// Loop through the schema and create a method map
|
|
3
18
|
for (const rawMethod of Object.keys(schema)) {
|
|
19
|
+
// Convert the method to lowercase
|
|
4
20
|
const key = rawMethod.toLowerCase();
|
|
21
|
+
// Get the method schema
|
|
5
22
|
const m = schema[rawMethod] || {};
|
|
23
|
+
// Create a method map
|
|
6
24
|
methodMap[key] = {
|
|
7
|
-
paramsSchema: m.params,
|
|
8
|
-
querySchema: m.query,
|
|
9
|
-
bodySchema: m.body,
|
|
10
|
-
hasParams: !!m.params,
|
|
11
|
-
hasQuery: !!m.query,
|
|
12
|
-
hasBody: !!m.body,
|
|
25
|
+
paramsSchema: m.params, // URL parameters schema
|
|
26
|
+
querySchema: m.query, // Query parameters schema
|
|
27
|
+
bodySchema: m.body, // Request body schema
|
|
28
|
+
hasParams: !!m.params, // Whether the method has URL parameters
|
|
29
|
+
hasQuery: !!m.query, // Whether the method has query parameters
|
|
30
|
+
hasBody: !!m.body, // Whether the method has a request body
|
|
13
31
|
};
|
|
14
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* The middleware function that validates the request.
|
|
35
|
+
*
|
|
36
|
+
* @param req - The request object.
|
|
37
|
+
* @returns The next middleware or handler.
|
|
38
|
+
*/
|
|
15
39
|
return async (req) => {
|
|
40
|
+
// If the request has been validated, continue.
|
|
16
41
|
if (req.validated) {
|
|
17
|
-
return undefined;
|
|
42
|
+
return undefined; // Proceed to the next middleware or handler
|
|
18
43
|
}
|
|
44
|
+
// Determine the HTTP method (in lowercase) to match the schema.
|
|
19
45
|
const method = (req.method || 'get').toLowerCase();
|
|
46
|
+
// Get the schema for the current method.
|
|
20
47
|
const methodSchema = methodMap[method];
|
|
48
|
+
// If there's no schema for this method, continue.
|
|
21
49
|
if (!methodSchema) {
|
|
22
|
-
return undefined;
|
|
50
|
+
return undefined; // Proceed to the next middleware or handler
|
|
23
51
|
}
|
|
52
|
+
// Get the schemas for the current method.
|
|
24
53
|
const { paramsSchema, querySchema, bodySchema, hasParams, hasQuery, hasBody, } = methodSchema;
|
|
54
|
+
/**
|
|
55
|
+
* Object to store validated request data. This will be attached to the
|
|
56
|
+
* request object if validation is successful. The object will contain
|
|
57
|
+
* validated data for the following fields:
|
|
58
|
+
*
|
|
59
|
+
* - `params`: Validated URL parameters (if available and schema provided).
|
|
60
|
+
* - `query`: Validated query parameters (if available and schema provided).
|
|
61
|
+
* - `body`: Validated request body (if JSON and schema provided).
|
|
62
|
+
*/
|
|
25
63
|
const validated = {};
|
|
64
|
+
// Lazy errors — create only if/when an error occurs
|
|
26
65
|
let errors = null;
|
|
66
|
+
// Validate URL parameters (if available and schema provided).
|
|
27
67
|
if (hasParams && req.params) {
|
|
28
68
|
const result = paramsSchema.safeParse(req.params);
|
|
29
69
|
if (result.success) {
|
|
@@ -35,6 +75,7 @@ export function createValidationMiddleware(schema) {
|
|
|
35
75
|
errors.params = result.error.issues;
|
|
36
76
|
}
|
|
37
77
|
}
|
|
78
|
+
// Validate query parameters if available and schema provided.
|
|
38
79
|
if (hasQuery) {
|
|
39
80
|
const url = new URL(req.url);
|
|
40
81
|
const queryParams = Object.fromEntries(url.searchParams.entries());
|
|
@@ -48,15 +89,20 @@ export function createValidationMiddleware(schema) {
|
|
|
48
89
|
errors.query = result.error.issues;
|
|
49
90
|
}
|
|
50
91
|
}
|
|
92
|
+
// Get the content type header
|
|
51
93
|
const contentType = req.headers.get('content-type') ??
|
|
52
94
|
req.headers.get('Content-Type') ??
|
|
53
95
|
'';
|
|
96
|
+
// Validate request body if it's JSON
|
|
54
97
|
if (hasBody && contentType?.includes('application/json')) {
|
|
55
98
|
try {
|
|
99
|
+
// Attempt to parse the JSON body.
|
|
56
100
|
const bodyData = await req.json();
|
|
57
101
|
const result = bodySchema.safeParse(bodyData);
|
|
58
102
|
if (result.success) {
|
|
103
|
+
// Set the validated body.
|
|
59
104
|
validated.body = result.data;
|
|
105
|
+
// Set the json method to return the validated body.
|
|
60
106
|
req.json = async () => result.data;
|
|
61
107
|
}
|
|
62
108
|
else {
|
|
@@ -66,6 +112,7 @@ export function createValidationMiddleware(schema) {
|
|
|
66
112
|
}
|
|
67
113
|
}
|
|
68
114
|
catch (error) {
|
|
115
|
+
// Create a message from the error.
|
|
69
116
|
const msg = error && typeof error.message === 'string'
|
|
70
117
|
? error.message
|
|
71
118
|
: String(error);
|
|
@@ -75,9 +122,12 @@ export function createValidationMiddleware(schema) {
|
|
|
75
122
|
}
|
|
76
123
|
}
|
|
77
124
|
if (errors) {
|
|
125
|
+
// If validation fails, return a 400 response with error details.
|
|
78
126
|
return Response.json({ errors }, { status: 400 });
|
|
79
127
|
}
|
|
128
|
+
// Attach validated data to the request.
|
|
80
129
|
req.validated = validated;
|
|
81
|
-
|
|
130
|
+
// Continue to the next middleware or handler.
|
|
131
|
+
return undefined; // Proceed
|
|
82
132
|
};
|
|
83
133
|
}
|