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 +337 -184
- package/dist/src/core/{router.d.ts → api-router.d.ts} +12 -19
- package/dist/src/core/api-router.js +209 -0
- package/dist/src/core/openapi.d.ts +3 -3
- package/dist/src/core/openapi.js +17 -17
- package/dist/src/core/page-router.d.ts +59 -0
- package/dist/src/core/page-router.js +232 -0
- package/dist/src/core/response.js +6 -6
- package/dist/src/core/server.d.ts +8 -5
- package/dist/src/core/server.js +15 -10
- package/dist/src/index.d.ts +5 -4
- package/dist/src/index.js +65 -40
- package/dist/src/middleware/validator.d.ts +1 -1
- package/dist/src/middleware/validator.js +9 -6
- package/dist/src/types/index.d.ts +13 -7
- package/dist/src/types/index.js +1 -1
- package/dist/src/utils/error.js +10 -163
- package/dist/src/utils/index.d.ts +1 -0
- package/dist/src/utils/index.js +7 -5
- package/dist/src/utils/routing.d.ts +32 -0
- package/dist/src/utils/routing.js +54 -0
- package/package.json +83 -82
- package/dist/src/core/router.js +0 -197
package/README.md
CHANGED
|
@@ -1,81 +1,151 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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
|
+
[](https://github.com/isfhan/burger-api)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](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
|
-
-
|
|
12
|
-
|
|
43
|
+
- ⚡ **Bun-Native Performance:**
|
|
44
|
+
Leverages Bun's high-performance HTTP server.
|
|
13
45
|
|
|
14
|
-
-
|
|
15
|
-
|
|
46
|
+
- 📁 **File-Based Routing:**
|
|
47
|
+
Automatically registers API routes from your file structure using a clear
|
|
48
|
+
naming convention.
|
|
16
49
|
|
|
17
|
-
-
|
|
18
|
-
|
|
50
|
+
- 🔄 **Middleware Architecture:**
|
|
51
|
+
Supports both global and route-specific middleware with a familiar
|
|
52
|
+
`req, res, next` pattern.
|
|
19
53
|
|
|
20
|
-
-
|
|
21
|
-
|
|
54
|
+
- ✅ **Type-Safe Validation:**
|
|
55
|
+
Utilizes Zod for request validation, ensuring full type safety and automatic
|
|
56
|
+
error reporting.
|
|
22
57
|
|
|
23
|
-
-
|
|
24
|
-
|
|
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
|
-
-
|
|
27
|
-
|
|
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
|
-
-
|
|
34
|
-
|
|
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
|
-
-
|
|
37
|
-
Automatically scans directories to register routes.
|
|
87
|
+
- 🔄 **Middleware System:**
|
|
38
88
|
|
|
39
|
-
|
|
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
|
-
-
|
|
94
|
+
- ✅ **Zod-Based Schema Validation:**
|
|
95
|
+
Automatically validates request params, query, and body using Zod.
|
|
42
96
|
|
|
43
|
-
|
|
44
|
-
|
|
97
|
+
- Supports preprocessing (e.g., converting URL parameters from string to
|
|
98
|
+
number).
|
|
45
99
|
|
|
46
|
-
-
|
|
100
|
+
- 📚 **Automatic OpenAPI Specification Generation:**
|
|
101
|
+
Generates an OpenAPI 3.0 document using route metadata and Zod schemas.
|
|
47
102
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
-
|
|
53
|
-
|
|
110
|
+
- 🔍 **Swagger UI Integration:**
|
|
111
|
+
Provides a `/docs` endpoint serving an interactive Swagger UI that reads
|
|
112
|
+
from `/openapi.json`.
|
|
54
113
|
|
|
55
|
-
|
|
114
|
+
## 📣 Changelog
|
|
56
115
|
|
|
57
|
-
|
|
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
|
-
|
|
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
|
-
-
|
|
66
|
-
|
|
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
|
|
130
|
+
We're actively enhancing burger-api with powerful new features:
|
|
71
131
|
|
|
72
|
-
### 🎨
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
98
|
-
|
|
167
|
+
console.log(`[Global Logger] ${req.method} ${req.url}`);
|
|
168
|
+
return next();
|
|
99
169
|
};
|
|
100
170
|
|
|
101
171
|
const burger = new Burger({
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
237
|
+
import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
|
|
164
238
|
|
|
165
|
-
export const logger = async (
|
|
166
|
-
|
|
167
|
-
|
|
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
|
|
252
|
+
import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
|
|
174
253
|
|
|
175
254
|
export const validateProductAccess = async (
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
255
|
+
req: BurgerRequest,
|
|
256
|
+
res: BurgerResponse,
|
|
257
|
+
next: BurgerNext
|
|
179
258
|
) => {
|
|
180
|
-
|
|
181
|
-
|
|
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
|
|
267
|
+
import { z } from 'zod';
|
|
188
268
|
|
|
189
269
|
export const productSchema = {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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
|
|
206
|
-
import { validateProductAccess } from
|
|
207
|
-
import { productSchema } from
|
|
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
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
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
|
-
|
|
301
|
+
return res.json({ message: 'List of products' });
|
|
221
302
|
}
|
|
222
303
|
|
|
223
304
|
export async function POST(req: BurgerRequest, res: BurgerResponse) {
|
|
224
|
-
|
|
225
|
-
|
|
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
|
|
232
|
-
import { logger } from
|
|
313
|
+
import { Burger } from 'burger-api';
|
|
314
|
+
import { logger } from './middleware/global/logger';
|
|
233
315
|
|
|
234
316
|
const burger = new Burger({
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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
|
-
|
|
325
|
+
console.log(`Server is running on port ${port}`);
|
|
244
326
|
});
|
|
245
327
|
```
|
|
246
328
|
|
|
247
329
|
This structure provides several benefits:
|
|
248
|
-
|
|
249
|
-
-
|
|
250
|
-
-
|
|
251
|
-
-
|
|
252
|
-
-
|
|
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
|
-
-
|
|
257
|
-
|
|
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
|
-
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
|
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
|
|
276
|
-
import type { BurgerRequest, BurgerResponse } from
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
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
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
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
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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
|
-
|
|
324
|
-
|
|
325
|
-
|
|
463
|
+
req: BurgerRequest,
|
|
464
|
+
res: BurgerResponse,
|
|
465
|
+
params: { id: number }
|
|
326
466
|
) {
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
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
|
-
|
|
340
|
-
|
|
341
|
-
|
|
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
|
-
-
|
|
348
|
-
|
|
488
|
+
- 📚 **OpenAPI JSON:**
|
|
489
|
+
Access `http://localhost:4000/openapi.json` to view the auto-generated
|
|
490
|
+
OpenAPI specification.
|
|
349
491
|
|
|
350
|
-
-
|
|
351
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
-
|
|
366
|
-
|
|
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
|
-
-
|
|
369
|
-
|
|
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
|
-
-
|
|
372
|
-
|
|
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
|
-
-
|
|
375
|
-
|
|
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
|
|
529
|
+
_burger-api_ aims to revolutionize your API development experience with
|
|
530
|
+
simplicity, speed, and cutting-edge features. Happy coding! 🚀
|