burger-api 0.1.0 → 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,116 +1,129 @@
1
-
2
1
  <p align="center">
3
2
  <img src="https://github.com/user-attachments/assets/0d9b376e-1d89-479a-aa7f-e7ee3c6b2342" alt="BurgerAPI logo"/>
4
3
  </p>
5
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)
6
8
 
7
- [![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)
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.
8
15
 
9
- **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.
10
-
11
- **This project is under active development and should not be used in production yet.**
16
+ **This project is under active development and should not be used in production
17
+ yet.**
12
18
 
13
19
  ## 📚 Table of Contents
14
20
 
15
- - [Overview](#-overview)
16
- - [Features](#-features)
17
- - [Core Features](#core-features)
18
- - [Release Notes](#-release-notes)
19
- - [Version 0.1.0](#version-010)
20
- - [Version 0.0.39](#version-0039)
21
- - [What's Coming Next](#-whats-coming-next)
22
- - [Installation](#-installation)
23
- - [How to Use burger-api](#-how-to-use-burger-api)
24
- - [Basic Usage Example](#basic-usage-example)
25
- - [Project Structure](#recommended-project-structure)
26
- - [Implementation Examples](#example-implementation)
27
- - [File-Based Routing](#file-based-routing-examples)
28
- - [Page Directory Usage](#page-directory-structure)
29
- - [Route Examples](#route-file-example)
30
- - [API Documentation](#api-documentation-endpoints)
31
- - [Contributing](#-contributing)
32
- - [License](#-license)
33
- - [FAQs & Resources](#-faqs--additional-resources)
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)
34
38
 
35
39
  ## 🚀 Overview
36
40
 
37
41
  burger-api is built to offer a robust developer experience through:
38
42
 
39
- - ⚡ **Bun-Native Performance:**
40
- Leverages Bun's high-performance HTTP server.
43
+ - ⚡ **Bun-Native Performance:**
44
+ Leverages Bun's high-performance HTTP server.
41
45
 
42
- - 📁 **File-Based Routing:**
43
- 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.
44
49
 
45
- - 🔄 **Middleware Architecture:**
46
- 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.
47
53
 
48
- - ✅ **Type-Safe Validation:**
49
- 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.
50
57
 
51
- - 📚 **Automatic OpenAPI Generation:**
52
- 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.
53
62
 
54
- - 🔍 **Swagger UI Integration:**
55
- 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.
56
66
 
57
67
  ## ✨ Features
58
68
 
59
69
  ### Core Features
60
70
 
61
- - ⚡ **Bun-Native HTTP Server:**
62
- Built on Bun's native APIs for exceptional performance.
63
-
64
- - 📁 **File-Based Routing Engine:**
65
- Automatically scans directories to register routes.
71
+ - ⚡ **Bun-Native HTTP Server:**
72
+ Built on Bun's native APIs for exceptional performance.
66
73
 
67
- - Supports dynamic routes via folder names like `[id]` for `/api/product/:id`.
74
+ - 📁 **File-Based Routing Engine:**
75
+ Automatically scans directories to register routes.
68
76
 
69
- - 🛠️ **Request & Response Enhancements:**
77
+ - Supports dynamic routes via folder names like `[id]` for
78
+ `/api/product/:id`.
70
79
 
71
- - `BurgerRequest` extends the native Request to include query, params, and validated data.
72
- - `BurgerResponse` provides methods to set headers, status, and build responses (JSON, text, HTML, redirects, files).
80
+ - 🛠️ **Request & Response Enhancements:**
73
81
 
74
- - 🔄 **Middleware System:**
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).
75
86
 
76
- - **Global Middleware:** Runs on every request.
77
- - **Route-Specific Middleware:** Defined in individual route files.
78
- - **Validation Middleware:** Automatically validates request data using Zod schemas exported from routes.
87
+ - 🔄 **Middleware System:**
79
88
 
80
- - ✅ **Zod-Based Schema Validation:**
81
- Automatically validates request params, query, and body using Zod.
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.
82
93
 
83
- - Supports preprocessing (e.g., converting URL parameters from string to number).
94
+ - ✅ **Zod-Based Schema Validation:**
95
+ Automatically validates request params, query, and body using Zod.
84
96
 
85
- - 📚 **Automatic OpenAPI Specification Generation:**
86
- Generates an OpenAPI 3.0 document using route metadata and Zod schemas.
97
+ - Supports preprocessing (e.g., converting URL parameters from string to
98
+ number).
87
99
 
88
- - **OpenAPI Options:**
89
- - Global metadata (title, description, version)
90
- - Per-route metadata (summary, description, tags, operationId, deprecated, externalDocs)
91
- - Auto-generated parameters and requestBody schemas (using `zod-to-json-schema` for detailed inline JSON schema definitions)
100
+ - 📚 **Automatic OpenAPI Specification Generation:**
101
+ Generates an OpenAPI 3.0 document using route metadata and Zod schemas.
92
102
 
93
- - 🔍 **Swagger UI Integration:**
94
- Provides a `/docs` endpoint serving an interactive Swagger UI that reads from `/openapi.json`.
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)
95
109
 
96
- ## 📣 Release Notes
110
+ - 🔍 **Swagger UI Integration:**
111
+ Provides a `/docs` endpoint serving an interactive Swagger UI that reads
112
+ from `/openapi.json`.
97
113
 
98
- ### Version 0.1.0
114
+ ## 📣 Changelog
99
115
 
100
- - 🎨 **Static Page Serving:**
101
- - Basic support for serving static `.html` files
102
- - File-based routing for pages
103
- - Support for route grouping with `(group)` syntax
104
- - Support for dynamic route with `[slug]` syntax
116
+ For detailed release notes, please refer to the [Changelog](CHANGELOG.md) file.
105
117
 
106
- ### Version 0.0.39
118
+ ### Version 0.1.3 (March 15, 2024)
107
119
 
108
- - 🚀 Initial release with core API features
109
- - ⚡ Bun-native HTTP server implementation
110
- - 📁 File-based API routing
111
- - ✅ Zod schema validation
112
- - 📚 OpenAPI/Swagger integration
113
- - 🔄 Middleware system
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
114
127
 
115
128
  ## 🎯 What's Coming Next?
116
129
 
@@ -118,17 +131,21 @@ We're actively enhancing burger-api with powerful new features:
118
131
 
119
132
  ### 🎨 Page Serving Enhancements (In Development)
120
133
 
121
- - 🔥 **TSX Support:** Adding React/TSX rendering capabilities
122
- - 🔐 **Global Middleware:** Applies to all routes for tasks like logging and authentication.
123
- - 🔐 **Page-Specific Middleware:** Defined in individual route files for tailored processing.
124
- - 🛠️ **Advanced Middleware:** More built-in middleware for common use cases:
125
- - CORS handling
126
- - Rate limiting
127
- - Request logging
128
- - Security headers
129
- - 🎯 **Performance Optimizations:** Further leveraging Bun's capabilities for faster page serving
130
-
131
- 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.
132
149
 
133
150
  ## 📦 Installation
134
151
 
@@ -143,42 +160,44 @@ bun add burger-api
143
160
  ### **Basic Usage Example**
144
161
 
145
162
  ```ts
146
- import { Burger } from "burger-api";
163
+ import { Burger } from 'burger-api';
147
164
 
148
165
  // Global middleware example: a simple logger.
149
166
  const globalLogger = async (req, res, next) => {
150
- console.log(`[Global Logger] ${req.method} ${req.url}`);
151
- return next();
167
+ console.log(`[Global Logger] ${req.method} ${req.url}`);
168
+ return next();
152
169
  };
153
170
 
154
171
  const burger = new Burger({
155
- title: "My Custom API",
156
- description: "Custom API with auto-generated docs and validation",
157
- apiDir: "api",
158
- globalMiddleware: [globalLogger],
159
- version: "1.0.0",
160
- 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
161
178
  });
162
179
 
163
180
  // Start the server on port 4000 with a callback
164
181
  burger.serve(4000, (port) => {
165
- console.log(`Server is running on port ${port}`);
182
+ console.log(`Server is running on port ${port}`);
166
183
  });
167
184
  ```
168
185
 
169
186
  The `debug` option enables:
170
187
 
171
- - 🔍 Interactive stack trace page at when errors occur
172
- - Shows detailed error information
173
- - Displays the full stack trace
174
- - Highlights the exact line where the error occurred
175
- - Provides request context and environment details
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
176
193
 
177
- This is particularly useful during development to understand how your API is working and troubleshoot issues.
194
+ This is particularly useful during development to understand how your API is
195
+ working and troubleshoot issues.
178
196
 
179
197
  ### **Recommended Project Structure**
180
198
 
181
- 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:
182
201
 
183
202
  ```
184
203
  my-api/
@@ -215,132 +234,135 @@ Here's how to implement this structure:
215
234
  1. **Global Middleware** (`src/middleware/global/logger.ts`):
216
235
 
217
236
  ```ts
218
- import type { BurgerRequest, BurgerResponse } from "burger-api";
237
+ import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
219
238
 
220
239
  export const logger = async (
221
- req: BurgerRequest,
222
- res: BurgerResponse,
223
- next: () => Promise<Response>
240
+ req: BurgerRequest,
241
+ res: BurgerResponse,
242
+ next: BurgerNext
224
243
  ) => {
225
- console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
226
- return next();
244
+ console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
245
+ return next();
227
246
  };
228
247
  ```
229
248
 
230
249
  2. **Route-Specific Middleware** (`src/middleware/routes/products.ts`):
231
250
 
232
251
  ```ts
233
- import type { BurgerRequest, BurgerResponse } from "burger-api";
252
+ import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
234
253
 
235
254
  export const validateProductAccess = async (
236
- req: BurgerRequest,
237
- res: BurgerResponse,
238
- next: () => Promise<Response>
255
+ req: BurgerRequest,
256
+ res: BurgerResponse,
257
+ next: BurgerNext
239
258
  ) => {
240
- // Your middleware logic here
241
- return next();
259
+ // Your middleware logic here
260
+ return next();
242
261
  };
243
262
  ```
244
263
 
245
264
  3. **Schemas** (`src/schemas/product.ts`):
246
265
 
247
266
  ```ts
248
- import { z } from "zod";
267
+ import { z } from 'zod';
249
268
 
250
269
  export const productSchema = {
251
- create: z.object({
252
- name: z.string().min(1),
253
- price: z.number().positive(),
254
- description: z.string().optional(),
255
- }),
256
- update: z.object({
257
- name: z.string().min(1).optional(),
258
- price: z.number().positive().optional(),
259
- description: z.string().optional(),
260
- }),
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
+ }),
261
280
  };
262
281
  ```
263
282
 
264
283
  4. **Route File** (`src/api/products/route.ts`):
265
284
 
266
285
  ```ts
267
- import type { BurgerRequest, BurgerResponse } from "burger-api";
268
- import { validateProductAccess } from "../../middleware/routes/products";
269
- 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';
270
289
 
271
290
  export const middleware = [validateProductAccess];
272
291
  export const schema = {
273
- post: {
274
- body: productSchema.create,
275
- },
276
- put: {
277
- body: productSchema.update,
278
- },
292
+ post: {
293
+ body: productSchema.create,
294
+ },
295
+ put: {
296
+ body: productSchema.update,
297
+ },
279
298
  };
280
299
 
281
300
  export async function GET(req: BurgerRequest, res: BurgerResponse) {
282
- return res.json({ message: "List of products" });
301
+ return res.json({ message: 'List of products' });
283
302
  }
284
303
 
285
304
  export async function POST(req: BurgerRequest, res: BurgerResponse) {
286
- const body = req.validated?.body;
287
- return res.json({ message: "Product created", data: body });
305
+ const body = req.validated?.body;
306
+ return res.json({ message: 'Product created', data: body });
288
307
  }
289
308
  ```
290
309
 
291
310
  5. **Main Application** (`src/index.ts`):
292
311
 
293
312
  ```ts
294
- import { Burger } from "burger-api";
295
- import { logger } from "./middleware/global/logger";
313
+ import { Burger } from 'burger-api';
314
+ import { logger } from './middleware/global/logger';
296
315
 
297
316
  const burger = new Burger({
298
- title: "Product API",
299
- description: "API for managing products",
300
- apiDir: "api",
301
- globalMiddleware: [logger],
302
- 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',
303
322
  });
304
323
 
305
324
  burger.serve(4000, (port) => {
306
- console.log(`Server is running on port ${port}`);
325
+ console.log(`Server is running on port ${port}`);
307
326
  });
308
327
  ```
309
328
 
310
329
  This structure provides several benefits:
311
330
 
312
- - 🎯 Clear separation of concerns
313
- - 📁 Easy to find and maintain code
314
- - 🔄 Reusable components
315
- - 🧹 Clean and organized codebase
316
- - 📚 Better scalability
331
+ - 🎯 Clear separation of concerns
332
+ - 📁 Easy to find and maintain code
333
+ - 🔄 Reusable components
334
+ - 🧹 Clean and organized codebase
335
+ - 📚 Better scalability
317
336
 
318
337
  ### **File-Based Routing Examples**
319
338
 
320
- - 📄 **Static API Route:**
321
- 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`).
322
342
 
323
- - 🔄 **Dynamic API Route:**
324
- For routes with dynamic segments, create folders with square brackets. For example:
325
- ```
326
- src/api/product/
327
- ├── route.ts // Handles /api/product
328
- └── [id]/
329
- └── route.ts // Handles /api/product/:id
330
- ```
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
+ ```
331
352
 
332
353
  ### **Page Directory Structure**
333
354
 
334
- burger-api supports serving static pages alongside your API routes. Here's how to use the `pageDir` feature:
355
+ burger-api supports serving static pages alongside your API routes. Here's how
356
+ to use the `pageDir` feature:
335
357
 
336
358
  ```ts
337
359
  const burger = new Burger({
338
- title: "My Custom API",
339
- description: "Custom API with auto-generated docs and validation",
340
- apiDir: "api",
341
- pageDir: "pages", // Enable page serving from the pages directory
342
- globalMiddleware: [globalLogger],
343
- version: "1.0.0",
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',
344
366
  });
345
367
  ```
346
368
 
@@ -361,14 +383,14 @@ my-api/
361
383
 
362
384
  #### **Page Routing Features:**
363
385
 
364
- - 📄 **Index Pages:** Files named `index.html` serve as directory index pages
365
- - 🔄 **Clean URLs:**
366
- - `/pages/about.html` → `/about`
367
- - 📁 **Dynamic Routes:** Use `[param]` syntax in folder names
368
- - `/pages/products/[id]/index.html` → `/products/:id`
369
- - 🎯 **Route Grouping:** Use `(group)` syntax for logical grouping
370
- - `/pages/(auth)/login.html` → `/login`
371
- - `/pages/(auth)/register.html` → `/register`
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`
372
394
 
373
395
  #### **Example Page Structure:**
374
396
 
@@ -376,123 +398,133 @@ my-api/
376
398
  <!-- pages/products/[id]/index.html -->
377
399
  <!DOCTYPE html>
378
400
  <html>
379
- <head>
380
- <title>Product Details</title>
381
- </head>
382
- <body>
383
- <h1>Product Details</h1>
384
- <!-- Content here -->
385
- </body>
401
+ <head>
402
+ <title>Product Details</title>
403
+ </head>
404
+ <body>
405
+ <h1>Product Details</h1>
406
+ <!-- Content here -->
407
+ </body>
386
408
  </html>
387
409
  ```
388
410
 
389
411
  ### **Route File Example**
390
412
 
391
- 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.
392
415
 
393
416
  ```ts
394
417
  // examples/demo/api/product/[id]/route.ts
395
418
 
396
- import { z } from "zod";
397
- import type { BurgerRequest, BurgerResponse } from "burger-api";
419
+ import { z } from 'zod';
420
+ import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
398
421
 
399
422
  // OpenAPI metadata for this route
400
423
  export const openapi = {
401
- get: {
402
- summary: "Get Product Details",
403
- description: "Retrieves product details by product ID.",
404
- tags: ["Product"],
405
- operationId: "getProductDetails",
406
- },
424
+ get: {
425
+ summary: 'Get Product Details',
426
+ description: 'Retrieves product details by product ID.',
427
+ tags: ['Product'],
428
+ operationId: 'getProductDetails',
429
+ },
407
430
  };
408
431
 
409
432
  // Validation Schemas for GET and POST requests
410
433
  export const schema = {
411
- get: {
412
- params: z.object({
413
- id: z.preprocess(
414
- (val) => (typeof val === "string" ? parseInt(val, 10) : val),
415
- z.number().min(1, "ID is required")
416
- ),
417
- }),
418
- query: z.object({
419
- search: z.string().optional(),
420
- }),
421
- },
422
- post: {
423
- body: z.object({
424
- name: z.string().min(1, "Name is required"),
425
- price: z.number().positive("Price must be positive"),
426
- }),
427
- },
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
+ },
428
451
  };
429
452
 
430
453
  // Route-specific middleware
431
454
  export const middleware = [
432
- async (
433
- req: BurgerRequest,
434
- res: BurgerResponse,
435
- next: () => Promise<Response>
436
- ) => {
437
- console.log("[Product Middleware] Executing product route middleware");
438
- return next();
439
- },
455
+ async (req: BurgerRequest, res: BurgerResponse, next: BurgerNext) => {
456
+ console.log('[Product Middleware] Executing product route middleware');
457
+ return next();
458
+ },
440
459
  ];
441
460
 
442
461
  // GET handler: returns product details
443
462
  export async function GET(
444
- req: BurgerRequest,
445
- res: BurgerResponse,
446
- params: { id: number }
463
+ req: BurgerRequest,
464
+ res: BurgerResponse,
465
+ params: { id: number }
447
466
  ) {
448
- console.log("[GET] Product route invoked");
449
- const validatedParams = (req.validated?.params as { id: number }) || params;
450
- const query = req.validated?.query || Object.fromEntries(req.query.entries());
451
- return res.json({
452
- id: validatedParams.id,
453
- query,
454
- name: "Sample Product",
455
- });
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
+ });
456
476
  }
457
477
 
458
478
  // POST handler: creates a new product
459
479
  export async function POST(req: BurgerRequest, res: BurgerResponse) {
460
- console.log("[POST] Product route invoked");
461
- const body = req.validated?.body || (await req.json());
462
- 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);
463
483
  }
464
484
  ```
465
485
 
466
486
  ### **API Documentation Endpoints**
467
487
 
468
- - 📚 **OpenAPI JSON:**
469
- 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.
470
491
 
471
- - 🔍 **Swagger UI:**
472
- 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.
473
495
 
474
496
  ## 🤝 Contributing
475
497
 
476
- 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.
477
501
 
478
502
  ## 📄 License
479
503
 
480
- 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.
481
506
 
482
- 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.
483
510
 
484
511
  ## ❓ FAQs & Additional Resources
485
512
 
486
- - 🔄 **How do I add custom middleware?**
487
- 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.
488
516
 
489
- - 📁 **How does file-based routing work?**
490
- 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).
491
520
 
492
- - ✅ **How is validation handled?**
493
- 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.
494
524
 
495
- - 📚 **How can I customize the OpenAPI documentation?**
496
- 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.
497
528
 
498
- _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! 🚀