burger-api 0.1.4 → 0.2.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 +17 -456
- package/dist/src/core/api-router.d.ts +37 -29
- package/dist/src/core/api-router.js +85 -65
- package/dist/src/core/openapi.d.ts +2 -9
- package/dist/src/core/openapi.js +4 -10
- package/dist/src/core/page-router.d.ts +1 -1
- package/dist/src/core/server.d.ts +2 -9
- package/dist/src/core/server.js +13 -18
- package/dist/src/index.d.ts +50 -5
- package/dist/src/index.js +239 -114
- package/dist/src/middleware/validator.d.ts +1 -10
- package/dist/src/middleware/validator.js +59 -42
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +1 -1
- package/dist/src/utils/response.d.ts +12 -0
- package/dist/src/utils/response.js +17 -0
- package/dist/src/utils/routing.d.ts +9 -1
- package/dist/src/utils/routing.js +26 -0
- package/package.json +82 -82
- package/dist/src/types/index.d.ts +0 -257
- package/dist/src/types/index.js +0 -1
package/dist/src/index.js
CHANGED
|
@@ -4,14 +4,49 @@ import { ApiRouter } from './core/api-router.js';
|
|
|
4
4
|
import { PageRouter } from './core/page-router.js';
|
|
5
5
|
import { generateOpenAPIDocument } from './core/openapi.js';
|
|
6
6
|
import { swaggerHtml } from './core/swagger-ui.js';
|
|
7
|
+
// Import utils
|
|
8
|
+
import { collectRoutes } from './utils/index.js';
|
|
9
|
+
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
|
|
7
10
|
// Import middleware
|
|
8
11
|
import { createValidationMiddleware } from './middleware/validator.js';
|
|
9
12
|
export class Burger {
|
|
10
13
|
options;
|
|
14
|
+
/**
|
|
15
|
+
* The server instance
|
|
16
|
+
*/
|
|
11
17
|
server;
|
|
18
|
+
/**
|
|
19
|
+
* The API router instance
|
|
20
|
+
*/
|
|
12
21
|
apiRouter;
|
|
22
|
+
/**
|
|
23
|
+
* The page router instance
|
|
24
|
+
*/
|
|
13
25
|
pageRouter;
|
|
26
|
+
/**
|
|
27
|
+
* The global middleware
|
|
28
|
+
*/
|
|
14
29
|
globalMiddleware = [];
|
|
30
|
+
/**
|
|
31
|
+
* The OpenAPI document
|
|
32
|
+
*/
|
|
33
|
+
openApiDoc = null;
|
|
34
|
+
/**
|
|
35
|
+
* The routes object
|
|
36
|
+
*/
|
|
37
|
+
routes = {};
|
|
38
|
+
/**
|
|
39
|
+
* Pre-computed responses for reuse
|
|
40
|
+
*/
|
|
41
|
+
METHOD_NOT_ALLOWED = METHOD_NOT_ALLOWED;
|
|
42
|
+
/**
|
|
43
|
+
* The not found response
|
|
44
|
+
*/
|
|
45
|
+
NOT_FOUND = NOT_FOUND;
|
|
46
|
+
/**
|
|
47
|
+
* The OpenAPI error response
|
|
48
|
+
*/
|
|
49
|
+
OPENAPI_ERROR = OPENAPI_ERROR;
|
|
15
50
|
/**
|
|
16
51
|
* Constructor for the Burger class.
|
|
17
52
|
* @param options - The options for the server and router.
|
|
@@ -23,26 +58,203 @@ export class Burger {
|
|
|
23
58
|
*/
|
|
24
59
|
constructor(options) {
|
|
25
60
|
this.options = options;
|
|
61
|
+
// Create server instance
|
|
26
62
|
this.server = new Server(options);
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
63
|
+
// Fast initialization for routers with nullish coalescing
|
|
64
|
+
const { apiDir, pageDir, apiPrefix, pagePrefix, globalMiddleware } = options;
|
|
65
|
+
// Initialize API router if apiDir is provided
|
|
66
|
+
this.apiRouter = apiDir
|
|
67
|
+
? new ApiRouter(apiDir, apiPrefix || 'api')
|
|
68
|
+
: undefined;
|
|
69
|
+
// Initialize page router if pageDir is provided
|
|
70
|
+
this.pageRouter = pageDir
|
|
71
|
+
? new PageRouter(pageDir, pagePrefix || '')
|
|
72
|
+
: undefined;
|
|
73
|
+
// Add global middleware if any
|
|
74
|
+
this.globalMiddleware = globalMiddleware?.length
|
|
75
|
+
? globalMiddleware.slice()
|
|
76
|
+
: [];
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Process the page routes and add them to the routes object
|
|
80
|
+
* @returns A promise that resolves to a boolean
|
|
81
|
+
*/
|
|
82
|
+
async processPageRoutes() {
|
|
83
|
+
// If no page router, return false
|
|
84
|
+
if (!this.pageRouter)
|
|
85
|
+
return false;
|
|
86
|
+
// Load pages routes
|
|
87
|
+
await this.pageRouter.loadPages();
|
|
88
|
+
// If there are any page routes, add them to the routes object
|
|
89
|
+
const pages = this.pageRouter.pages;
|
|
90
|
+
// Get the length of the pages routes
|
|
91
|
+
const pageCount = pages.length;
|
|
92
|
+
// If no pages, return false
|
|
93
|
+
if (pageCount === 0)
|
|
94
|
+
return false;
|
|
95
|
+
// Loop through the pages
|
|
96
|
+
for (let i = 0; i < pageCount; i++) {
|
|
97
|
+
// Get the current page
|
|
98
|
+
const page = pages[i];
|
|
99
|
+
// Add the page to the routes
|
|
100
|
+
this.routes[page.path] = page.handler;
|
|
34
101
|
}
|
|
35
|
-
//
|
|
36
|
-
|
|
37
|
-
|
|
102
|
+
// Return true if there are any pages
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Process the API routes and add them to the routes object
|
|
107
|
+
* @returns A promise that resolves to a boolean
|
|
108
|
+
*/
|
|
109
|
+
async processApiRoutes() {
|
|
110
|
+
// If no api router, return false
|
|
111
|
+
if (!this.apiRouter)
|
|
112
|
+
return false;
|
|
113
|
+
// Load API routes
|
|
114
|
+
await this.apiRouter.loadRoutes();
|
|
115
|
+
// Collect API routes
|
|
116
|
+
const apiRoutes = collectRoutes(this.apiRouter.routes);
|
|
117
|
+
// Get the length of the API routes
|
|
118
|
+
const routeCount = apiRoutes.length;
|
|
119
|
+
// If there are no API routes, return false
|
|
120
|
+
if (routeCount === 0)
|
|
121
|
+
return false;
|
|
122
|
+
// Generate OpenAPI document and cache it
|
|
123
|
+
this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options);
|
|
124
|
+
// Cache frequently accessed properties
|
|
125
|
+
const routes = this.routes;
|
|
126
|
+
// Get the global middleware
|
|
127
|
+
const globalMiddleware = this.globalMiddleware;
|
|
128
|
+
// Get the length of the global middleware
|
|
129
|
+
const globalMiddlewareLen = globalMiddleware.length;
|
|
130
|
+
// Process each route with optimized handler creation
|
|
131
|
+
for (let i = 0; i < routeCount; i++) {
|
|
132
|
+
/**
|
|
133
|
+
* ================================================
|
|
134
|
+
* Pre-compute the required functionality start
|
|
135
|
+
* ================================================
|
|
136
|
+
*/
|
|
137
|
+
// Get the current route object
|
|
138
|
+
const route = apiRoutes[i];
|
|
139
|
+
// Destructure the route object
|
|
140
|
+
const { path, schema, middleware: routeMiddleware, handlers, } = route;
|
|
141
|
+
// Get length of route specific middleware
|
|
142
|
+
const routeMiddlewareLen = routeMiddleware?.length || 0;
|
|
143
|
+
// Check if schema exists
|
|
144
|
+
const hasSchema = !!schema;
|
|
145
|
+
// Optimize middleware array initialization by pre-allocating size
|
|
146
|
+
const totalMiddlewareCount = globalMiddlewareLen + (hasSchema ? 1 : 0) + routeMiddlewareLen;
|
|
147
|
+
// Create optimized route handler
|
|
148
|
+
if (totalMiddlewareCount === 0) {
|
|
149
|
+
// Ultra-fast path: no middleware
|
|
150
|
+
routes[path] = (request) => {
|
|
151
|
+
const handler = handlers[request.method];
|
|
152
|
+
return handler ? handler(request) : this.METHOD_NOT_ALLOWED;
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
// Pre-compute middleware array with known size
|
|
157
|
+
const middlewares = new Array(totalMiddlewareCount);
|
|
158
|
+
// Initialize index to track the current middleware
|
|
159
|
+
let index = 0;
|
|
160
|
+
// Copy global middleware (most common case)
|
|
161
|
+
for (let j = 0; j < globalMiddlewareLen; j++) {
|
|
162
|
+
middlewares[index++] = globalMiddleware[j];
|
|
163
|
+
}
|
|
164
|
+
// Add validation middleware if needed
|
|
165
|
+
if (hasSchema) {
|
|
166
|
+
middlewares[index++] = createValidationMiddleware(schema);
|
|
167
|
+
}
|
|
168
|
+
// Add route-specific middlewares
|
|
169
|
+
if (routeMiddleware) {
|
|
170
|
+
for (let j = 0; j < routeMiddlewareLen; j++) {
|
|
171
|
+
middlewares[index++] = routeMiddleware[j];
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* ================================================
|
|
176
|
+
* Pre-compute the required functionality end
|
|
177
|
+
* ================================================
|
|
178
|
+
*/
|
|
179
|
+
// Create handler with middleware
|
|
180
|
+
routes[path] = (request) => {
|
|
181
|
+
const handler = handlers[request.method];
|
|
182
|
+
if (!handler)
|
|
183
|
+
return this.METHOD_NOT_ALLOWED;
|
|
184
|
+
return this.processMiddleware(request, middlewares, handler);
|
|
185
|
+
};
|
|
186
|
+
}
|
|
38
187
|
}
|
|
188
|
+
// Add special routes for OpenAPI
|
|
189
|
+
routes['/openapi.json'] = () => this.openApiDoc
|
|
190
|
+
? Response.json(this.openApiDoc)
|
|
191
|
+
: this.OPENAPI_ERROR;
|
|
192
|
+
// Add special route for Swagger UI
|
|
193
|
+
routes['/docs'] = () => new Response(swaggerHtml, {
|
|
194
|
+
headers: { 'Content-Type': 'text/html' },
|
|
195
|
+
});
|
|
196
|
+
return true;
|
|
39
197
|
}
|
|
40
198
|
/**
|
|
41
|
-
*
|
|
42
|
-
* @param
|
|
199
|
+
* Process the middleware and handler
|
|
200
|
+
* @param request - The request object
|
|
201
|
+
* @param middlewares - The middleware array
|
|
202
|
+
* @param handler - The handler function
|
|
203
|
+
* @returns A promise that resolves to a response
|
|
43
204
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
205
|
+
async processMiddleware(request, middlewares, handler) {
|
|
206
|
+
// Get the length of the middleware array
|
|
207
|
+
const middlewareLen = middlewares.length;
|
|
208
|
+
// Fast path: single middleware with no after functions
|
|
209
|
+
if (middlewareLen === 1) {
|
|
210
|
+
// Get the first middleware
|
|
211
|
+
const result = await middlewares[0](request);
|
|
212
|
+
// If the result is a response, return it
|
|
213
|
+
if (result instanceof Response) {
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
// If the result is not a function, return the handler
|
|
217
|
+
if (typeof result !== 'function') {
|
|
218
|
+
return handler(request);
|
|
219
|
+
}
|
|
220
|
+
// If the result is a function, return the result of the handler
|
|
221
|
+
return result(await handler(request));
|
|
222
|
+
}
|
|
223
|
+
// Stack to store "after" functions
|
|
224
|
+
// Regular path with pre-allocated afterStack
|
|
225
|
+
const afterStack = new Array(middlewareLen);
|
|
226
|
+
// Initialize the after middleware counter
|
|
227
|
+
let afterCount = 0;
|
|
228
|
+
// Process "before" logic
|
|
229
|
+
for (let i = 0; i < middlewareLen; i++) {
|
|
230
|
+
// Get the current middleware
|
|
231
|
+
const result = await middlewares[i](request);
|
|
232
|
+
// If the result is a response, return it
|
|
233
|
+
if (result instanceof Response) {
|
|
234
|
+
return result; // Short-circuit with a response
|
|
235
|
+
}
|
|
236
|
+
// If the result is a function, save it to the afterStack
|
|
237
|
+
else if (typeof result === 'function') {
|
|
238
|
+
afterStack[afterCount++] = result;
|
|
239
|
+
}
|
|
240
|
+
// If undefined, proceed to next middleware
|
|
241
|
+
}
|
|
242
|
+
// Get response from handler
|
|
243
|
+
let response = await handler(request);
|
|
244
|
+
// Fast path: no after functions
|
|
245
|
+
if (afterCount === 0) {
|
|
246
|
+
return response;
|
|
247
|
+
}
|
|
248
|
+
// Fast path: single after function
|
|
249
|
+
if (afterCount === 1) {
|
|
250
|
+
return afterStack[0](response);
|
|
251
|
+
}
|
|
252
|
+
// Process "after" logic in reverse order
|
|
253
|
+
for (let i = afterCount - 1; i >= 0; i--) {
|
|
254
|
+
response = await afterStack[i](response);
|
|
255
|
+
}
|
|
256
|
+
// Return the responseF
|
|
257
|
+
return response;
|
|
46
258
|
}
|
|
47
259
|
/**
|
|
48
260
|
* Starts the server and begins listening for incoming requests.
|
|
@@ -51,110 +263,23 @@ export class Burger {
|
|
|
51
263
|
* @returns A Promise that resolves when the server has started listening.
|
|
52
264
|
*/
|
|
53
265
|
async serve(port = 4000, cb) {
|
|
54
|
-
//
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
routes[page.path] = page.handler;
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
if (this.apiRouter) {
|
|
68
|
-
// Load API routes
|
|
69
|
-
await this.apiRouter.loadRoutes();
|
|
266
|
+
// Process routes in parallel if possible
|
|
267
|
+
const [pagesConfigured, apiConfigured] = await Promise.all([
|
|
268
|
+
this.processPageRoutes(),
|
|
269
|
+
this.processApiRoutes(),
|
|
270
|
+
]);
|
|
271
|
+
// Flag to track if any routes were loaded
|
|
272
|
+
const routesConfigured = pagesConfigured || apiConfigured;
|
|
273
|
+
// If routes were configured, start the server
|
|
274
|
+
if (routesConfigured) {
|
|
70
275
|
// Start the server
|
|
71
|
-
this.server.start(routes, async (
|
|
72
|
-
|
|
73
|
-
const url = new URL(req.url);
|
|
74
|
-
// Check if the request is for /openapi.json
|
|
75
|
-
if (url.pathname === '/openapi.json') {
|
|
76
|
-
if (this.apiRouter) {
|
|
77
|
-
// Generate OpenAPI document
|
|
78
|
-
const doc = generateOpenAPIDocument(this.apiRouter, this.options);
|
|
79
|
-
// Return it as JSON
|
|
80
|
-
return res.json(doc);
|
|
81
|
-
}
|
|
82
|
-
else {
|
|
83
|
-
// Return a descriptive error if router is not available
|
|
84
|
-
return res
|
|
85
|
-
.status(500)
|
|
86
|
-
.json({
|
|
87
|
-
error: 'API Router not configured',
|
|
88
|
-
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.'
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
// Serve the Swagger UI at /docs
|
|
93
|
-
if (url.pathname === '/docs') {
|
|
94
|
-
return res.html(swaggerHtml);
|
|
95
|
-
}
|
|
96
|
-
// Get the route and params for the current request
|
|
97
|
-
const { route, params } = this.apiRouter.resolve(req);
|
|
98
|
-
if (!route) {
|
|
99
|
-
// Return a 404 if no route is found
|
|
100
|
-
return res
|
|
101
|
-
.status(404)
|
|
102
|
-
.json({ error: 'Route not found' });
|
|
103
|
-
}
|
|
104
|
-
// Add params to the request
|
|
105
|
-
req.params = params;
|
|
106
|
-
// Get the handler for the current HTTP method
|
|
107
|
-
const method = req.method.toUpperCase();
|
|
108
|
-
const handler = route.handlers[method];
|
|
109
|
-
if (!handler) {
|
|
110
|
-
// Return a 405 if no handler is found
|
|
111
|
-
return res
|
|
112
|
-
.status(405)
|
|
113
|
-
.json({ error: 'Method Not Allowed' });
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Build the middleware composition chain.
|
|
117
|
-
* 1. Compose the Route-Specific Chain
|
|
118
|
-
* 2. Insert Validation Middleware (if a schema exists)
|
|
119
|
-
* 3. Insert Global Middleware
|
|
120
|
-
* 4. Execute the handler
|
|
121
|
-
*/
|
|
122
|
-
// 1. Compose the Route-Specific Chain
|
|
123
|
-
let routeChain = async () => handler(req, res);
|
|
124
|
-
if (route.middleware && route.middleware.length > 0) {
|
|
125
|
-
// Wrap route-specific middleware (in reverse order to preserve order of execution)
|
|
126
|
-
for (const mw of route.middleware.slice().reverse()) {
|
|
127
|
-
const next = routeChain;
|
|
128
|
-
routeChain = async () => mw(req, res, next);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
// 2. Insert Validation Middleware (if a schema exists)
|
|
132
|
-
let composedChain = routeChain;
|
|
133
|
-
if (route.schema) {
|
|
134
|
-
const validationMw = createValidationMiddleware(route.schema);
|
|
135
|
-
composedChain = async () => validationMw(req, res, routeChain);
|
|
136
|
-
}
|
|
137
|
-
// 3. Wrap Global Middleware (in reverse order so that the first-added runs first)
|
|
138
|
-
let finalHandler = composedChain;
|
|
139
|
-
if (this.globalMiddleware.length > 0) {
|
|
140
|
-
for (const mw of this.globalMiddleware
|
|
141
|
-
.slice()
|
|
142
|
-
.reverse()) {
|
|
143
|
-
const next = finalHandler;
|
|
144
|
-
finalHandler = async () => mw(req, res, next);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
// Execute the full chain
|
|
148
|
-
return await finalHandler();
|
|
276
|
+
this.server.start(this.routes, async () => {
|
|
277
|
+
return this.NOT_FOUND;
|
|
149
278
|
}, port, cb);
|
|
150
279
|
}
|
|
151
280
|
else {
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
return res
|
|
155
|
-
.status(200)
|
|
156
|
-
.json({ message: 'Hello from burger-api!' });
|
|
157
|
-
}, port, cb);
|
|
281
|
+
// If no routes were configured, log an error
|
|
282
|
+
console.error('Error: No routes configured! Please provide either apiDir with route.ts files or pageDir with html files when initializing the Burger Class.');
|
|
158
283
|
}
|
|
159
284
|
}
|
|
160
285
|
}
|
|
@@ -1,11 +1,2 @@
|
|
|
1
|
-
import type { RouteSchema, Middleware } from '
|
|
2
|
-
/**
|
|
3
|
-
* Creates a middleware function that validates request data according to the
|
|
4
|
-
* given schema for the current HTTP method.
|
|
5
|
-
*
|
|
6
|
-
* @param schema - The route schema to validate against.
|
|
7
|
-
* @returns A middleware function that validates request data and attaches the
|
|
8
|
-
* validated data to the request if successful, or returns a 400 response with
|
|
9
|
-
* error details if validation fails.
|
|
10
|
-
*/
|
|
1
|
+
import type { RouteSchema, Middleware } from '@burgerTypes';
|
|
11
2
|
export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
|
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Creates a middleware function that validates request data according to the
|
|
3
|
-
* given schema for the current HTTP method.
|
|
4
|
-
*
|
|
5
|
-
* @param schema - The route schema to validate against.
|
|
6
|
-
* @returns A middleware function that validates request data and attaches the
|
|
7
|
-
* validated data to the request if successful, or returns a 400 response with
|
|
8
|
-
* error details if validation fails.
|
|
9
|
-
*/
|
|
10
1
|
export function createValidationMiddleware(schema) {
|
|
11
|
-
return async (req
|
|
2
|
+
return async (req) => {
|
|
12
3
|
// If the request has been validated, continue.
|
|
13
4
|
if (req.validated) {
|
|
14
|
-
return
|
|
5
|
+
return undefined; // Proceed to the next middleware or handler
|
|
15
6
|
}
|
|
16
7
|
// Determine the HTTP method (in lowercase) to match the schema.
|
|
17
8
|
const method = req.method.toLowerCase();
|
|
@@ -19,14 +10,19 @@ export function createValidationMiddleware(schema) {
|
|
|
19
10
|
const methodSchema = schema[method];
|
|
20
11
|
// If there's no schema for this method, continue.
|
|
21
12
|
if (!methodSchema) {
|
|
22
|
-
return
|
|
13
|
+
return undefined; // Proceed to the next middleware or handler
|
|
23
14
|
}
|
|
15
|
+
// Get the schemas for the current method.
|
|
16
|
+
const paramsSchema = methodSchema.params;
|
|
17
|
+
const querySchema = methodSchema.query;
|
|
18
|
+
const bodySchema = methodSchema.body;
|
|
24
19
|
/**
|
|
25
20
|
* Array to collect validation errors.
|
|
26
21
|
* Each error contains a `field` indicating the part of the request that failed validation,
|
|
27
22
|
* and an `error` providing details about the validation failure.
|
|
28
23
|
*/
|
|
29
|
-
const errors =
|
|
24
|
+
const errors = new Array(3); // Pre-allocate for params, query, body
|
|
25
|
+
let errorCount = 0;
|
|
30
26
|
/**
|
|
31
27
|
* Object to store validated request data. This will be attached to the
|
|
32
28
|
* request object if validation is successful. The object will contain
|
|
@@ -38,56 +34,77 @@ export function createValidationMiddleware(schema) {
|
|
|
38
34
|
*/
|
|
39
35
|
const validated = {};
|
|
40
36
|
// Validate URL parameters (if available and schema provided).
|
|
41
|
-
|
|
42
|
-
if (methodSchema.params && req.params) {
|
|
37
|
+
if (paramsSchema && req.params) {
|
|
43
38
|
try {
|
|
44
|
-
|
|
39
|
+
const result = paramsSchema.safeParse(req.params);
|
|
40
|
+
if (result.success) {
|
|
41
|
+
validated.params = result.data;
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
errors[errorCount++] = {
|
|
45
|
+
field: 'params',
|
|
46
|
+
error: result.error,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
45
49
|
}
|
|
46
50
|
catch (e) {
|
|
47
|
-
errors
|
|
51
|
+
errors[errorCount++] = { field: 'params', error: e.errors };
|
|
48
52
|
}
|
|
49
53
|
}
|
|
50
54
|
// Validate query parameters.
|
|
51
|
-
|
|
55
|
+
const url = new URL(req.url);
|
|
56
|
+
const queryParams = Object.fromEntries(url.searchParams.entries());
|
|
57
|
+
if (querySchema) {
|
|
52
58
|
try {
|
|
53
|
-
|
|
59
|
+
const result = querySchema.safeParse(queryParams);
|
|
60
|
+
if (result.success) {
|
|
61
|
+
validated.query = result.data;
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
errors[errorCount++] = {
|
|
65
|
+
field: 'query',
|
|
66
|
+
error: result.error,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
54
69
|
}
|
|
55
70
|
catch (e) {
|
|
56
|
-
errors
|
|
71
|
+
errors[errorCount++] = { field: 'query', error: e.errors };
|
|
57
72
|
}
|
|
58
73
|
}
|
|
59
74
|
// Validate request body.
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
try {
|
|
72
|
-
// Attempt to parse the JSON body.
|
|
73
|
-
const bodyData = await req.json();
|
|
74
|
-
validated.body = methodSchema.body.parse(bodyData);
|
|
75
|
+
if (bodySchema &&
|
|
76
|
+
req.headers.get('Content-Type')?.includes('application/json')) {
|
|
77
|
+
try {
|
|
78
|
+
// Attempt to parse the JSON body.
|
|
79
|
+
const bodyData = await req.json();
|
|
80
|
+
const result = bodySchema.safeParse(bodyData);
|
|
81
|
+
if (result.success) {
|
|
82
|
+
// Set the validated body.
|
|
83
|
+
validated.body = result.data;
|
|
84
|
+
// Set the json method to return the validated body.
|
|
85
|
+
req.json = () => result.data;
|
|
75
86
|
}
|
|
76
|
-
|
|
77
|
-
errors
|
|
87
|
+
else {
|
|
88
|
+
errors[errorCount++] = {
|
|
78
89
|
field: 'body',
|
|
79
|
-
error:
|
|
80
|
-
}
|
|
90
|
+
error: result.error,
|
|
91
|
+
};
|
|
81
92
|
}
|
|
82
93
|
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
errors[errorCount++] = {
|
|
96
|
+
field: 'body',
|
|
97
|
+
error: e.errors || e.message,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
83
100
|
}
|
|
84
|
-
if (
|
|
101
|
+
if (errorCount > 0) {
|
|
85
102
|
// If validation fails, return a 400 response with error details.
|
|
86
|
-
return
|
|
103
|
+
return Response.json({ errors }, { status: 400 });
|
|
87
104
|
}
|
|
88
105
|
// Attach validated data to the request.
|
|
89
106
|
req.validated = validated;
|
|
90
107
|
// Continue to the next middleware or handler.
|
|
91
|
-
return
|
|
108
|
+
return undefined; // Proceed
|
|
92
109
|
};
|
|
93
110
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, } from './routing.js';
|
|
1
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
2
2
|
/**
|
|
3
3
|
* Resolves the given path to the specified directory.
|
|
4
4
|
* @param directory the directory to resolve to
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolve } from 'path';
|
|
2
2
|
// Export constants
|
|
3
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, } from './routing.js';
|
|
3
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
4
4
|
/**
|
|
5
5
|
* Resolves the given path to the specified directory.
|
|
6
6
|
* @param directory the directory to resolve to
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The method not allowed response
|
|
3
|
+
*/
|
|
4
|
+
export declare const METHOD_NOT_ALLOWED: Response;
|
|
5
|
+
/**
|
|
6
|
+
* The not found response
|
|
7
|
+
*/
|
|
8
|
+
export declare const NOT_FOUND: Response;
|
|
9
|
+
/**
|
|
10
|
+
* The OpenAPI error response
|
|
11
|
+
*/
|
|
12
|
+
export declare const OPENAPI_ERROR: Response;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The method not allowed response
|
|
3
|
+
*/
|
|
4
|
+
export const METHOD_NOT_ALLOWED = new Response('Method Not Allowed', {
|
|
5
|
+
status: 405,
|
|
6
|
+
});
|
|
7
|
+
/**
|
|
8
|
+
* The not found response
|
|
9
|
+
*/
|
|
10
|
+
export const NOT_FOUND = new Response('Not Found', { status: 404 });
|
|
11
|
+
/**
|
|
12
|
+
* The OpenAPI error response
|
|
13
|
+
*/
|
|
14
|
+
export const OPENAPI_ERROR = Response.json({
|
|
15
|
+
error: 'API Router not configured',
|
|
16
|
+
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.',
|
|
17
|
+
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PageDefinition, RouteDefinition } from '
|
|
1
|
+
import type { PageDefinition, RouteDefinition, TrieNode } from '@burgerTypes';
|
|
2
2
|
/**
|
|
3
3
|
* Constants for route handling.
|
|
4
4
|
*/
|
|
@@ -30,3 +30,11 @@ export declare const getRouteSpecificity: (path: string) => number;
|
|
|
30
30
|
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
31
31
|
*/
|
|
32
32
|
export declare const compareRoutes: (a: PageDefinition | RouteDefinition, b: PageDefinition | RouteDefinition) => number;
|
|
33
|
+
/**
|
|
34
|
+
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
35
|
+
* @param node The current node in the trie.
|
|
36
|
+
* @param currentPath The current path being traversed.
|
|
37
|
+
* @param routes The array of collected routes.
|
|
38
|
+
* @returns An array of RouteDefinition objects.
|
|
39
|
+
*/
|
|
40
|
+
export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
|
|
@@ -52,3 +52,29 @@ export const compareRoutes = (a, b) => {
|
|
|
52
52
|
return 1;
|
|
53
53
|
return a.path.localeCompare(b.path);
|
|
54
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
57
|
+
* @param node The current node in the trie.
|
|
58
|
+
* @param currentPath The current path being traversed.
|
|
59
|
+
* @param routes The array of collected routes.
|
|
60
|
+
* @returns An array of RouteDefinition objects.
|
|
61
|
+
*/
|
|
62
|
+
export function collectRoutes(node, currentPath = '', routes = []) {
|
|
63
|
+
// If this node has a route definition, add it
|
|
64
|
+
if (node.route) {
|
|
65
|
+
routes.push({
|
|
66
|
+
...node.route,
|
|
67
|
+
path: currentPath,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
// Traverse static children
|
|
71
|
+
node.children.forEach((child, segment) => {
|
|
72
|
+
collectRoutes(child, `${currentPath}/${segment}`, routes);
|
|
73
|
+
});
|
|
74
|
+
// Traverse dynamic child if exists
|
|
75
|
+
if (node.paramChild) {
|
|
76
|
+
const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
|
|
77
|
+
collectRoutes(node.paramChild, paramPath, routes);
|
|
78
|
+
}
|
|
79
|
+
return routes;
|
|
80
|
+
}
|