burger-api 0.0.39 → 0.1.4

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 CHANGED
@@ -1,81 +1,151 @@
1
- # 🍔 burger-api [![Under Development](https://img.shields.io/badge/under%20development-red.svg)](https://github.com/isfhan/burger-api) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Bun](https://img.shields.io/badge/Bun-1.2.4-black?logo=bun)](https://bun.sh)
2
-
3
- **burger-api** is a modern, open source API framework built on [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with powerful features like built-in middleware, Zod-based schema validation, and automatic OpenAPI generation. Designed for high performance and ease-of-use, burger-api leverages Bun's native modules to deliver blazing-fast API responses while keeping your codebase clean and maintainable.
4
-
5
- **This project is under active development and should not be used in production yet.**
1
+ <p align="center">
2
+ <img src="https://github.com/user-attachments/assets/0d9b376e-1d89-479a-aa7f-e7ee3c6b2342" alt="BurgerAPI logo"/>
3
+ </p>
4
+
5
+ [![Under Development](https://img.shields.io/badge/under%20development-red.svg)](https://github.com/isfhan/burger-api)
6
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+ [![Bun](https://img.shields.io/badge/Bun-1.2.4-black?logo=bun)](https://bun.sh)
8
+
9
+ **burger-api** is a modern, open source API framework built on
10
+ [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
11
+ powerful features like built-in middleware, Zod-based schema validation, and
12
+ automatic OpenAPI generation. Designed for high performance and ease-of-use,
13
+ burger-api leverages Bun's native modules to deliver blazing-fast API responses
14
+ while keeping your codebase clean and maintainable.
15
+
16
+ **This project is under active development and should not be used in production
17
+ yet.**
18
+
19
+ ## 📚 Table of Contents
20
+
21
+ - [Overview](#-overview)
22
+ - [Features](#-features)
23
+ - [Core Features](#core-features)
24
+ - [Changelog](#-changelog)
25
+ - [What's Coming Next](#-whats-coming-next)
26
+ - [Installation](#-installation)
27
+ - [How to Use burger-api](#-how-to-use-burger-api)
28
+ - [Basic Usage Example](#basic-usage-example)
29
+ - [Project Structure](#recommended-project-structure)
30
+ - [Implementation Examples](#example-implementation)
31
+ - [File-Based Routing](#file-based-routing-examples)
32
+ - [Page Directory Usage](#page-directory-structure)
33
+ - [Route Examples](#route-file-example)
34
+ - [API Documentation](#api-documentation-endpoints)
35
+ - [Contributing](#-contributing)
36
+ - [License](#-license)
37
+ - [FAQs & Resources](#-faqs--additional-resources)
6
38
 
7
39
  ## 🚀 Overview
8
40
 
9
41
  burger-api is built to offer a robust developer experience through:
10
42
 
11
- - ⚡ **Bun-Native Performance:**
12
- Leverages Bun's high-performance HTTP server.
43
+ - ⚡ **Bun-Native Performance:**
44
+ Leverages Bun's high-performance HTTP server.
13
45
 
14
- - 📁 **File-Based Routing:**
15
- Automatically registers API routes from your file structure using a clear naming convention.
46
+ - 📁 **File-Based Routing:**
47
+ Automatically registers API routes from your file structure using a clear
48
+ naming convention.
16
49
 
17
- - 🔄 **Middleware Architecture:**
18
- Supports both global and route-specific middleware with a familiar `req, res, next` pattern.
50
+ - 🔄 **Middleware Architecture:**
51
+ Supports both global and route-specific middleware with a familiar
52
+ `req, res, next` pattern.
19
53
 
20
- - ✅ **Type-Safe Validation:**
21
- Utilizes Zod for request validation, ensuring full type safety and automatic error reporting.
54
+ - ✅ **Type-Safe Validation:**
55
+ Utilizes Zod for request validation, ensuring full type safety and automatic
56
+ error reporting.
22
57
 
23
- - 📚 **Automatic OpenAPI Generation:**
24
- Generates a complete OpenAPI 3.0 specification (with support for tags, summaries, descriptions, operationId, deprecated status, externalDocs, and more) directly from your routes and Zod schemas.
58
+ - 📚 **Automatic OpenAPI Generation:**
59
+ Generates a complete OpenAPI 3.0 specification (with support for tags,
60
+ summaries, descriptions, operationId, deprecated status, externalDocs, and
61
+ more) directly from your routes and Zod schemas.
25
62
 
26
- - 🔍 **Swagger UI Integration:**
27
- Provides an out-of-the-box Swagger UI endpoint for interactive API documentation.
63
+ - 🔍 **Swagger UI Integration:**
64
+ Provides an out-of-the-box Swagger UI endpoint for interactive API
65
+ documentation.
28
66
 
29
67
  ## ✨ Features
30
68
 
31
69
  ### Core Features
32
70
 
33
- - ⚡ **Bun-Native HTTP Server:**
34
- Built on Bun's native APIs for exceptional performance.
71
+ - ⚡ **Bun-Native HTTP Server:**
72
+ Built on Bun's native APIs for exceptional performance.
73
+
74
+ - 📁 **File-Based Routing Engine:**
75
+ Automatically scans directories to register routes.
76
+
77
+ - Supports dynamic routes via folder names like `[id]` for
78
+ `/api/product/:id`.
79
+
80
+ - 🛠️ **Request & Response Enhancements:**
81
+
82
+ - `BurgerRequest` extends the native Request to include query, params, and
83
+ validated data.
84
+ - `BurgerResponse` provides methods to set headers, status, and build
85
+ responses (JSON, text, HTML, redirects, files).
35
86
 
36
- - 📁 **File-Based Routing Engine:**
37
- Automatically scans directories to register routes.
87
+ - 🔄 **Middleware System:**
38
88
 
39
- - Supports dynamic routes via folder names like `[id]` for `/api/product/:id`.
89
+ - **Global Middleware:** Runs on every request.
90
+ - **Route-Specific Middleware:** Defined in individual route files.
91
+ - **Validation Middleware:** Automatically validates request data using
92
+ Zod schemas exported from routes.
40
93
 
41
- - 🛠️ **Request & Response Enhancements:**
94
+ - ✅ **Zod-Based Schema Validation:**
95
+ Automatically validates request params, query, and body using Zod.
42
96
 
43
- - `BurgerRequest` extends the native Request to include query, params, and validated data.
44
- - `BurgerResponse` provides methods to set headers, status, and build responses (JSON, text, HTML, redirects, files).
97
+ - Supports preprocessing (e.g., converting URL parameters from string to
98
+ number).
45
99
 
46
- - 🔄 **Middleware System:**
100
+ - 📚 **Automatic OpenAPI Specification Generation:**
101
+ Generates an OpenAPI 3.0 document using route metadata and Zod schemas.
47
102
 
48
- - **Global Middleware:** Runs on every request.
49
- - **Route-Specific Middleware:** Defined in individual route files.
50
- - **Validation Middleware:** Automatically validates request data using Zod schemas exported from routes.
103
+ - **OpenAPI Options:**
104
+ - Global metadata (title, description, version)
105
+ - Per-route metadata (summary, description, tags, operationId,
106
+ deprecated, externalDocs)
107
+ - Auto-generated parameters and requestBody schemas (using
108
+ `zod-to-json-schema` for detailed inline JSON schema definitions)
51
109
 
52
- - ✅ **Zod-Based Schema Validation:**
53
- Automatically validates request params, query, and body using Zod.
110
+ - 🔍 **Swagger UI Integration:**
111
+ Provides a `/docs` endpoint serving an interactive Swagger UI that reads
112
+ from `/openapi.json`.
54
113
 
55
- - Supports preprocessing (e.g., converting URL parameters from string to number).
114
+ ## 📣 Changelog
56
115
 
57
- - 📚 **Automatic OpenAPI Specification Generation:**
58
- Generates an OpenAPI 3.0 document using route metadata and Zod schemas.
116
+ For detailed release notes, please refer to the [Changelog](CHANGELOG.md) file.
59
117
 
60
- - **OpenAPI Options:**
61
- - Global metadata (title, description, version)
62
- - Per-route metadata (summary, description, tags, operationId, deprecated, externalDocs)
63
- - Auto-generated parameters and requestBody schemas (using `zod-to-json-schema` for detailed inline JSON schema definitions)
118
+ ### Version 0.1.3 (March 15, 2024)
64
119
 
65
- - 🔍 **Swagger UI Integration:**
66
- Provides a `/docs` endpoint serving an interactive Swagger UI that reads from `/openapi.json`.
120
+ - 🔄 **Bug Fixes and Improvements:**
121
+ - Enhanced page routing and server response handling
122
+ - Improved import paths configuration in tsconfig.json
123
+ - Updated request/response handling
124
+ - Enhanced server initialization process
125
+ - Improved native types handling
126
+ - Updated server response functionality
67
127
 
68
128
  ## 🎯 What's Coming Next?
69
129
 
70
- We're enhancing burger-api to make it even more powerful! While our core focus remains on building fast, type-safe APIs, we're adding the ability to serve simple pages when needed:
130
+ We're actively enhancing burger-api with powerful new features:
71
131
 
72
- ### 🎨 Simple Page Serving (Coming Soon!)
73
- - Optional page serving capability for simple views
74
- - Perfect for API documentation, admin panels, or simple dashboards
75
- - Not meant to replace full-stack frameworks like Next.js
76
- - For complex frontend applications, we recommend using dedicated frontend frameworks
132
+ ### 🎨 Page Serving Enhancements (In Development)
77
133
 
78
- Stay tuned for updates as we continue to build and improve burger-api! We're committed to making it the best API framework for Bun.js.
134
+ - 🔥 **TSX Support:** Adding React/TSX rendering capabilities
135
+ - 🔐 **Global Middleware:** Applies to all routes for tasks like logging and
136
+ authentication.
137
+ - 🔐 **Page-Specific Middleware:** Defined in individual route files for
138
+ tailored processing.
139
+ - 🛠️ **Advanced Middleware:** More built-in middleware for common use cases:
140
+ - CORS handling
141
+ - Rate limiting
142
+ - Request logging
143
+ - Security headers
144
+ - 🎯 **Performance Optimizations:** Further leveraging Bun's capabilities for
145
+ faster page serving
146
+
147
+ Stay tuned for updates as we continue to build and improve burger-api! We're
148
+ committed to making it the best API framework for Bun.js.
79
149
 
80
150
  ## 📦 Installation
81
151
 
@@ -90,41 +160,44 @@ bun add burger-api
90
160
  ### **Basic Usage Example**
91
161
 
92
162
  ```ts
93
- import { Burger } from "burger-api";
163
+ import { Burger } from 'burger-api';
94
164
 
95
165
  // Global middleware example: a simple logger.
96
166
  const globalLogger = async (req, res, next) => {
97
- console.log(`[Global Logger] ${req.method} ${req.url}`);
98
- return next();
167
+ console.log(`[Global Logger] ${req.method} ${req.url}`);
168
+ return next();
99
169
  };
100
170
 
101
171
  const burger = new Burger({
102
- title: "My Custom API",
103
- description: "Custom API with auto-generated docs and validation",
104
- apiDir: "api",
105
- globalMiddleware: [globalLogger],
106
- version: "1.0.0",
107
- debug: true, // Enable debug mode for detailed logging and stack trace page
172
+ title: 'My Custom API',
173
+ description: 'Custom API with auto-generated docs and validation',
174
+ apiDir: 'api',
175
+ globalMiddleware: [globalLogger],
176
+ version: '1.0.0',
177
+ debug: true, // Enable debug mode for detailed logging and stack trace page
108
178
  });
109
179
 
110
180
  // Start the server on port 4000 with a callback
111
181
  burger.serve(4000, (port) => {
112
- console.log(`Server is running on port ${port}`);
182
+ console.log(`Server is running on port ${port}`);
113
183
  });
114
184
  ```
115
185
 
116
186
  The `debug` option enables:
117
- - 🔍 Interactive stack trace page at when errors occur
118
- - Shows detailed error information
119
- - Displays the full stack trace
120
- - Highlights the exact line where the error occurred
121
- - Provides request context and environment details
122
187
 
123
- This is particularly useful during development to understand how your API is working and troubleshoot issues.
188
+ - 🔍 Interactive stack trace page at when errors occur
189
+ - Shows detailed error information
190
+ - Displays the full stack trace
191
+ - Highlights the exact line where the error occurred
192
+ - Provides request context and environment details
193
+
194
+ This is particularly useful during development to understand how your API is
195
+ working and troubleshoot issues.
124
196
 
125
197
  ### **Recommended Project Structure**
126
198
 
127
- Here's a recommended project structure that helps keep your code organized and maintainable:
199
+ Here's a recommended project structure that helps keep your code organized and
200
+ maintainable:
128
201
 
129
202
  ```
130
203
  my-api/
@@ -159,219 +232,299 @@ my-api/
159
232
  Here's how to implement this structure:
160
233
 
161
234
  1. **Global Middleware** (`src/middleware/global/logger.ts`):
235
+
162
236
  ```ts
163
- import type { BurgerRequest, BurgerResponse } from "burger-api";
237
+ import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
164
238
 
165
- export const logger = async (req: BurgerRequest, res: BurgerResponse, next: () => Promise<Response>) => {
166
- console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
167
- return next();
239
+ export const logger = async (
240
+ req: BurgerRequest,
241
+ res: BurgerResponse,
242
+ next: BurgerNext
243
+ ) => {
244
+ console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
245
+ return next();
168
246
  };
169
247
  ```
170
248
 
171
249
  2. **Route-Specific Middleware** (`src/middleware/routes/products.ts`):
250
+
172
251
  ```ts
173
- import type { BurgerRequest, BurgerResponse } from "burger-api";
252
+ import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
174
253
 
175
254
  export const validateProductAccess = async (
176
- req: BurgerRequest,
177
- res: BurgerResponse,
178
- next: () => Promise<Response>
255
+ req: BurgerRequest,
256
+ res: BurgerResponse,
257
+ next: BurgerNext
179
258
  ) => {
180
- // Your middleware logic here
181
- return next();
259
+ // Your middleware logic here
260
+ return next();
182
261
  };
183
262
  ```
184
263
 
185
264
  3. **Schemas** (`src/schemas/product.ts`):
265
+
186
266
  ```ts
187
- import { z } from "zod";
267
+ import { z } from 'zod';
188
268
 
189
269
  export const productSchema = {
190
- create: z.object({
191
- name: z.string().min(1),
192
- price: z.number().positive(),
193
- description: z.string().optional(),
194
- }),
195
- update: z.object({
196
- name: z.string().min(1).optional(),
197
- price: z.number().positive().optional(),
198
- description: z.string().optional(),
199
- }),
270
+ create: z.object({
271
+ name: z.string().min(1),
272
+ price: z.number().positive(),
273
+ description: z.string().optional(),
274
+ }),
275
+ update: z.object({
276
+ name: z.string().min(1).optional(),
277
+ price: z.number().positive().optional(),
278
+ description: z.string().optional(),
279
+ }),
200
280
  };
201
281
  ```
202
282
 
203
283
  4. **Route File** (`src/api/products/route.ts`):
284
+
204
285
  ```ts
205
- import type { BurgerRequest, BurgerResponse } from "burger-api";
206
- import { validateProductAccess } from "../../middleware/routes/products";
207
- import { productSchema } from "../../schemas/product";
286
+ import type { BurgerRequest, BurgerResponse } from 'burger-api';
287
+ import { validateProductAccess } from '../../middleware/routes/products';
288
+ import { productSchema } from '../../schemas/product';
208
289
 
209
290
  export const middleware = [validateProductAccess];
210
291
  export const schema = {
211
- post: {
212
- body: productSchema.create,
213
- },
214
- put: {
215
- body: productSchema.update,
216
- },
292
+ post: {
293
+ body: productSchema.create,
294
+ },
295
+ put: {
296
+ body: productSchema.update,
297
+ },
217
298
  };
218
299
 
219
300
  export async function GET(req: BurgerRequest, res: BurgerResponse) {
220
- return res.json({ message: "List of products" });
301
+ return res.json({ message: 'List of products' });
221
302
  }
222
303
 
223
304
  export async function POST(req: BurgerRequest, res: BurgerResponse) {
224
- const body = req.validated?.body;
225
- return res.json({ message: "Product created", data: body });
305
+ const body = req.validated?.body;
306
+ return res.json({ message: 'Product created', data: body });
226
307
  }
227
308
  ```
228
309
 
229
310
  5. **Main Application** (`src/index.ts`):
311
+
230
312
  ```ts
231
- import { Burger } from "burger-api";
232
- import { logger } from "./middleware/global/logger";
313
+ import { Burger } from 'burger-api';
314
+ import { logger } from './middleware/global/logger';
233
315
 
234
316
  const burger = new Burger({
235
- title: "Product API",
236
- description: "API for managing products",
237
- apiDir: "api",
238
- globalMiddleware: [logger],
239
- version: "1.0.0",
317
+ title: 'Product API',
318
+ description: 'API for managing products',
319
+ apiDir: 'api',
320
+ globalMiddleware: [logger],
321
+ version: '1.0.0',
240
322
  });
241
323
 
242
324
  burger.serve(4000, (port) => {
243
- console.log(`Server is running on port ${port}`);
325
+ console.log(`Server is running on port ${port}`);
244
326
  });
245
327
  ```
246
328
 
247
329
  This structure provides several benefits:
248
- - 🎯 Clear separation of concerns
249
- - 📁 Easy to find and maintain code
250
- - 🔄 Reusable components
251
- - 🧹 Clean and organized codebase
252
- - 📚 Better scalability
330
+
331
+ - 🎯 Clear separation of concerns
332
+ - 📁 Easy to find and maintain code
333
+ - 🔄 Reusable components
334
+ - 🧹 Clean and organized codebase
335
+ - 📚 Better scalability
253
336
 
254
337
  ### **File-Based Routing Examples**
255
338
 
256
- - 📄 **Static API Route:**
257
- Place a file at `src/api/route.ts` to handle the root API endpoint (e.g., `/api`).
339
+ - 📄 **Static API Route:**
340
+ Place a file at `src/api/route.ts` to handle the root API endpoint (e.g.,
341
+ `/api`).
258
342
 
259
- - 🔄 **Dynamic API Route:**
260
- For routes with dynamic segments, create folders with square brackets. For example:
261
- ```
262
- src/api/product/
263
- ├── route.ts // Handles /api/product
264
- └── [id]/
265
- └── route.ts // Handles /api/product/:id
266
- ```
343
+ - 🔄 **Dynamic API Route:**
344
+ For routes with dynamic segments, create folders with square brackets. For
345
+ example:
346
+ ```
347
+ src/api/product/
348
+ ├── route.ts // Handles /api/product
349
+ └── [id]/
350
+ └── route.ts // Handles /api/product/:id
351
+ ```
352
+
353
+ ### **Page Directory Structure**
354
+
355
+ burger-api supports serving static pages alongside your API routes. Here's how
356
+ to use the `pageDir` feature:
357
+
358
+ ```ts
359
+ const burger = new Burger({
360
+ title: 'My Custom API',
361
+ description: 'Custom API with auto-generated docs and validation',
362
+ apiDir: 'api',
363
+ pageDir: 'pages', // Enable page serving from the pages directory
364
+ globalMiddleware: [globalLogger],
365
+ version: '1.0.0',
366
+ });
367
+ ```
368
+
369
+ #### **Page Directory Structure Example:**
370
+
371
+ ```
372
+ my-api/
373
+ ├── src/
374
+ │ ├── pages/ # Pages directory
375
+ │ │ ├── index.html # Home page (/)
376
+ │ │ ├── about.html # About page (/about)
377
+ │ │ └── products/
378
+ │ │ ├── index.html # Products list (/products)
379
+ │ │ └── [id]/ # Dynamic product pages
380
+ │ │ └── index.html # Single product (/products/123)
381
+ │ └── api/ # Your API routes
382
+ ```
383
+
384
+ #### **Page Routing Features:**
385
+
386
+ - 📄 **Index Pages:** Files named `index.html` serve as directory index pages
387
+ - 🔄 **Clean URLs:**
388
+ - `/pages/about.html` → `/about`
389
+ - 📁 **Dynamic Routes:** Use `[param]` syntax in folder names
390
+ - `/pages/products/[id]/index.html` → `/products/:id`
391
+ - 🎯 **Route Grouping:** Use `(group)` syntax for logical grouping
392
+ - `/pages/(auth)/login.html` → `/login`
393
+ - `/pages/(auth)/register.html` → `/register`
394
+
395
+ #### **Example Page Structure:**
396
+
397
+ ```html
398
+ <!-- pages/products/[id]/index.html -->
399
+ <!DOCTYPE html>
400
+ <html>
401
+ <head>
402
+ <title>Product Details</title>
403
+ </head>
404
+ <body>
405
+ <h1>Product Details</h1>
406
+ <!-- Content here -->
407
+ </body>
408
+ </html>
409
+ ```
267
410
 
268
411
  ### **Route File Example**
269
412
 
270
- Below is an example route file demonstrating schema validation, route-specific middleware, and OpenAPI metadata.
413
+ Below is an example route file demonstrating schema validation, route-specific
414
+ middleware, and OpenAPI metadata.
271
415
 
272
416
  ```ts
273
417
  // examples/demo/api/product/[id]/route.ts
274
418
 
275
- import { z } from "zod";
276
- import type { BurgerRequest, BurgerResponse } from "burger-api";
419
+ import { z } from 'zod';
420
+ import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
277
421
 
278
422
  // OpenAPI metadata for this route
279
423
  export const openapi = {
280
- get: {
281
- summary: "Get Product Details",
282
- description: "Retrieves product details by product ID.",
283
- tags: ["Product"],
284
- operationId: "getProductDetails",
285
- },
424
+ get: {
425
+ summary: 'Get Product Details',
426
+ description: 'Retrieves product details by product ID.',
427
+ tags: ['Product'],
428
+ operationId: 'getProductDetails',
429
+ },
286
430
  };
287
431
 
288
432
  // Validation Schemas for GET and POST requests
289
433
  export const schema = {
290
- get: {
291
- params: z.object({
292
- id: z.preprocess(
293
- (val) => (typeof val === "string" ? parseInt(val, 10) : val),
294
- z.number().min(1, "ID is required")
295
- ),
296
- }),
297
- query: z.object({
298
- search: z.string().optional(),
299
- }),
300
- },
301
- post: {
302
- body: z.object({
303
- name: z.string().min(1, "Name is required"),
304
- price: z.number().positive("Price must be positive"),
305
- }),
306
- },
434
+ get: {
435
+ params: z.object({
436
+ id: z.preprocess(
437
+ (val) => (typeof val === 'string' ? parseInt(val, 10) : val),
438
+ z.number().min(1, 'ID is required')
439
+ ),
440
+ }),
441
+ query: z.object({
442
+ search: z.string().optional(),
443
+ }),
444
+ },
445
+ post: {
446
+ body: z.object({
447
+ name: z.string().min(1, 'Name is required'),
448
+ price: z.number().positive('Price must be positive'),
449
+ }),
450
+ },
307
451
  };
308
452
 
309
453
  // Route-specific middleware
310
454
  export const middleware = [
311
- async (
312
- req: BurgerRequest,
313
- res: BurgerResponse,
314
- next: () => Promise<Response>
315
- ) => {
316
- console.log("[Product Middleware] Executing product route middleware");
317
- return next();
318
- },
455
+ async (req: BurgerRequest, res: BurgerResponse, next: BurgerNext) => {
456
+ console.log('[Product Middleware] Executing product route middleware');
457
+ return next();
458
+ },
319
459
  ];
320
460
 
321
461
  // GET handler: returns product details
322
462
  export async function GET(
323
- req: BurgerRequest,
324
- res: BurgerResponse,
325
- params: { id: number }
463
+ req: BurgerRequest,
464
+ res: BurgerResponse,
465
+ params: { id: number }
326
466
  ) {
327
- console.log("[GET] Product route invoked");
328
- const validatedParams = (req.validated?.params as { id: number }) || params;
329
- const query = req.validated?.query || Object.fromEntries(req.query.entries());
330
- return res.json({
331
- id: validatedParams.id,
332
- query,
333
- name: "Sample Product",
334
- });
467
+ console.log('[GET] Product route invoked');
468
+ const validatedParams = (req.validated?.params as { id: number }) || params;
469
+ const query =
470
+ req.validated?.query || Object.fromEntries(req.query.entries());
471
+ return res.json({
472
+ id: validatedParams.id,
473
+ query,
474
+ name: 'Sample Product',
475
+ });
335
476
  }
336
477
 
337
478
  // POST handler: creates a new product
338
479
  export async function POST(req: BurgerRequest, res: BurgerResponse) {
339
- console.log("[POST] Product route invoked");
340
- const body = req.validated?.body || (await req.json());
341
- return res.json(body);
480
+ console.log('[POST] Product route invoked');
481
+ const body = req.validated?.body || (await req.json());
482
+ return res.json(body);
342
483
  }
343
484
  ```
344
485
 
345
486
  ### **API Documentation Endpoints**
346
487
 
347
- - 📚 **OpenAPI JSON:**
348
- Access `http://localhost:4000/openapi.json` to view the auto-generated OpenAPI specification.
488
+ - 📚 **OpenAPI JSON:**
489
+ Access `http://localhost:4000/openapi.json` to view the auto-generated
490
+ OpenAPI specification.
349
491
 
350
- - 🔍 **Swagger UI:**
351
- Access `http://localhost:4000/docs` to view interactive API documentation via Swagger UI.
492
+ - 🔍 **Swagger UI:**
493
+ Access `http://localhost:4000/docs` to view interactive API documentation
494
+ via Swagger UI.
352
495
 
353
496
  ## 🤝 Contributing
354
497
 
355
- We welcome contributions from the community! If you have suggestions or improvements, please open an issue or submit a pull request. Let's build something amazing together.
498
+ We welcome contributions from the community! If you have suggestions or
499
+ improvements, please open an issue or submit a pull request. Let's build
500
+ something amazing together.
356
501
 
357
502
  ## 📄 License
358
503
 
359
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
504
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
505
+ for details.
360
506
 
361
- The MIT License is a permissive license that is short and to the point. It lets people do anything they want with your code as long as they provide attribution back to you and don't hold you liable.
507
+ The MIT License is a permissive license that is short and to the point. It lets
508
+ people do anything they want with your code as long as they provide attribution
509
+ back to you and don't hold you liable.
362
510
 
363
511
  ## ❓ FAQs & Additional Resources
364
512
 
365
- - 🔄 **How do I add custom middleware?**
366
- You can pass an array of global middleware in the Burger options or export route-specific middleware in your route files.
513
+ - 🔄 **How do I add custom middleware?**
514
+ You can pass an array of global middleware in the Burger options or export
515
+ route-specific middleware in your route files.
367
516
 
368
- - 📁 **How does file-based routing work?**
369
- Place your route files under `src/api/` or just `/api` using folder and file naming conventions (e.g., `[id]` for dynamic routes).
517
+ - 📁 **How does file-based routing work?**
518
+ Place your route files under `src/api/` or just `/api` using folder and file
519
+ naming conventions (e.g., `[id]` for dynamic routes).
370
520
 
371
- - ✅ **How is validation handled?**
372
- burger-api uses Zod for schema validation. Define your schemas in your route files and they are automatically used to validate incoming requests.
521
+ - ✅ **How is validation handled?**
522
+ burger-api uses Zod for schema validation. Define your schemas in your route
523
+ files and they are automatically used to validate incoming requests.
373
524
 
374
- - 📚 **How can I customize the OpenAPI documentation?**
375
- Override the default auto-generated summaries, descriptions, tags, and operationIds by exporting an `openapi` object in your route files.
525
+ - 📚 **How can I customize the OpenAPI documentation?**
526
+ Override the default auto-generated summaries, descriptions, tags, and
527
+ operationIds by exporting an `openapi` object in your route files.
376
528
 
377
- _burger-api_ aims to revolutionize your API development experience with simplicity, speed, and cutting-edge features. Happy coding! 🚀
529
+ _burger-api_ aims to revolutionize your API development experience with
530
+ simplicity, speed, and cutting-edge features. Happy coding! 🚀