burger-api 0.1.0 → 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 +58 -465
- package/dist/src/core/api-router.d.ts +37 -29
- package/dist/src/core/api-router.js +96 -76
- package/dist/src/core/openapi.d.ts +2 -9
- package/dist/src/core/openapi.js +21 -27
- package/dist/src/core/page-router.d.ts +1 -1
- package/dist/src/core/page-router.js +20 -19
- package/dist/src/core/response.js +6 -6
- package/dist/src/core/server.d.ts +4 -9
- package/dist/src/core/server.js +18 -20
- package/dist/src/index.d.ts +51 -6
- package/dist/src/index.js +246 -112
- package/dist/src/middleware/validator.d.ts +1 -10
- package/dist/src/middleware/validator.js +60 -40
- package/dist/src/utils/error.js +9 -9
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +6 -6
- 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 +41 -15
- package/package.json +7 -6
- package/dist/src/types/index.d.ts +0 -251
- package/dist/src/types/index.js +0 -1
package/README.md
CHANGED
|
@@ -1,498 +1,91 @@
|
|
|
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
|
+
[](https://github.com/isfhan/burger-api)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](https://bun.sh)
|
|
8
|
+
[](https://github.com/isfhan/burger-api/releases)
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
**burger-api** is a modern, open source API framework built on
|
|
11
|
+
[Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
|
|
12
|
+
powerful features like built-in middleware, Zod-based schema validation, and
|
|
13
|
+
automatic OpenAPI generation. Designed for high performance and ease-of-use,
|
|
14
|
+
burger-api leverages Bun's native modules to deliver blazing-fast API responses
|
|
15
|
+
while keeping your codebase clean and maintainable.
|
|
8
16
|
|
|
9
|
-
**
|
|
10
|
-
|
|
11
|
-
**This project is under active development and should not be used in production yet.**
|
|
17
|
+
**This project is under active development and should not be used in production
|
|
18
|
+
yet.**
|
|
12
19
|
|
|
13
20
|
## 📚 Table of Contents
|
|
14
21
|
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
|
|
18
|
-
-
|
|
19
|
-
|
|
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)
|
|
34
|
-
|
|
35
|
-
## 🚀 Overview
|
|
36
|
-
|
|
37
|
-
burger-api is built to offer a robust developer experience through:
|
|
38
|
-
|
|
39
|
-
- ⚡ **Bun-Native Performance:**
|
|
40
|
-
Leverages Bun's high-performance HTTP server.
|
|
41
|
-
|
|
42
|
-
- 📁 **File-Based Routing:**
|
|
43
|
-
Automatically registers API routes from your file structure using a clear naming convention.
|
|
44
|
-
|
|
45
|
-
- 🔄 **Middleware Architecture:**
|
|
46
|
-
Supports both global and route-specific middleware with a familiar `req, res, next` pattern.
|
|
47
|
-
|
|
48
|
-
- ✅ **Type-Safe Validation:**
|
|
49
|
-
Utilizes Zod for request validation, ensuring full type safety and automatic error reporting.
|
|
50
|
-
|
|
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.
|
|
53
|
-
|
|
54
|
-
- 🔍 **Swagger UI Integration:**
|
|
55
|
-
Provides an out-of-the-box Swagger UI endpoint for interactive API documentation.
|
|
22
|
+
- [Overview](#-overview)
|
|
23
|
+
- [Changelog](#-changelog)
|
|
24
|
+
- [What's Coming Next](#-whats-coming-next)
|
|
25
|
+
- [Contributing](#-contributing)
|
|
26
|
+
- [License](#-license)
|
|
56
27
|
|
|
57
|
-
##
|
|
28
|
+
## 📖 Documentation
|
|
58
29
|
|
|
59
|
-
|
|
30
|
+
For detailed documentation and examples, visit the
|
|
31
|
+
[BurgerAPI official docs](https://burger-api.com/).
|
|
60
32
|
|
|
61
|
-
|
|
62
|
-
Built on Bun's native APIs for exceptional performance.
|
|
63
|
-
|
|
64
|
-
- 📁 **File-Based Routing Engine:**
|
|
65
|
-
Automatically scans directories to register routes.
|
|
66
|
-
|
|
67
|
-
- Supports dynamic routes via folder names like `[id]` for `/api/product/:id`.
|
|
68
|
-
|
|
69
|
-
- 🛠️ **Request & Response Enhancements:**
|
|
70
|
-
|
|
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).
|
|
73
|
-
|
|
74
|
-
- 🔄 **Middleware System:**
|
|
33
|
+
## 🚀 Overview
|
|
75
34
|
|
|
76
|
-
|
|
77
|
-
- **Route-Specific Middleware:** Defined in individual route files.
|
|
78
|
-
- **Validation Middleware:** Automatically validates request data using Zod schemas exported from routes.
|
|
35
|
+
burger-api is built to offer a robust developer experience through:
|
|
79
36
|
|
|
80
|
-
-
|
|
81
|
-
|
|
37
|
+
- ⚡ **Bun-Native Performance:**
|
|
38
|
+
Leverages Bun's high-performance HTTP server.
|
|
82
39
|
|
|
83
|
-
|
|
40
|
+
- 📁 **File-Based Routing:**
|
|
41
|
+
Automatically registers API routes from your file structure using a clear
|
|
42
|
+
naming convention.
|
|
84
43
|
|
|
85
|
-
-
|
|
86
|
-
|
|
44
|
+
- 🔄 **Middleware Architecture:**
|
|
45
|
+
Supports both global and route-specific middleware.
|
|
87
46
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
- Auto-generated parameters and requestBody schemas (using `zod-to-json-schema` for detailed inline JSON schema definitions)
|
|
47
|
+
- ✅ **Type-Safe Validation:**
|
|
48
|
+
Utilizes Zod for request validation, ensuring full type safety and automatic
|
|
49
|
+
error reporting.
|
|
92
50
|
|
|
93
|
-
-
|
|
94
|
-
|
|
51
|
+
- 📚 **Automatic OpenAPI Generation:**
|
|
52
|
+
Generates a complete OpenAPI 3.0 specification (with support for tags,
|
|
53
|
+
summaries, descriptions, operationId, deprecated status, externalDocs, and
|
|
54
|
+
more) directly from your routes and Zod schemas.
|
|
95
55
|
|
|
96
|
-
|
|
56
|
+
- 🔍 **Swagger UI Integration:**
|
|
57
|
+
Provides an out-of-the-box Swagger UI endpoint for interactive API
|
|
58
|
+
documentation.
|
|
97
59
|
|
|
98
|
-
|
|
60
|
+
## 📣 Changelog
|
|
99
61
|
|
|
100
|
-
|
|
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
|
|
62
|
+
### Latest Version: 0.2.0 (April 26, 2025)
|
|
105
63
|
|
|
106
|
-
|
|
64
|
+
- ⚡ **Performance & Core Improvements:**
|
|
65
|
+
- Optimized framework core and improved middleware handling
|
|
66
|
+
- Enhanced OpenAPI documentation and route tracking
|
|
67
|
+
- Updated ID preprocessing logic in schema validation
|
|
68
|
+
- Improved type definitions across the framework
|
|
107
69
|
|
|
108
|
-
|
|
109
|
-
- ⚡ Bun-native HTTP server implementation
|
|
110
|
-
- 📁 File-based API routing
|
|
111
|
-
- ✅ Zod schema validation
|
|
112
|
-
- 📚 OpenAPI/Swagger integration
|
|
113
|
-
- 🔄 Middleware system
|
|
70
|
+
For a complete list of changes, please check the [Changelog](CHANGELOG.md) file.
|
|
114
71
|
|
|
115
72
|
## 🎯 What's Coming Next?
|
|
116
73
|
|
|
117
|
-
We're actively enhancing burger-api with powerful new features
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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.
|
|
132
|
-
|
|
133
|
-
## 📦 Installation
|
|
134
|
-
|
|
135
|
-
Install burger-api via bun:
|
|
136
|
-
|
|
137
|
-
```bash
|
|
138
|
-
bun add burger-api
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
## 🚀 How to Use burger-api
|
|
142
|
-
|
|
143
|
-
### **Basic Usage Example**
|
|
144
|
-
|
|
145
|
-
```ts
|
|
146
|
-
import { Burger } from "burger-api";
|
|
147
|
-
|
|
148
|
-
// Global middleware example: a simple logger.
|
|
149
|
-
const globalLogger = async (req, res, next) => {
|
|
150
|
-
console.log(`[Global Logger] ${req.method} ${req.url}`);
|
|
151
|
-
return next();
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
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
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
// Start the server on port 4000 with a callback
|
|
164
|
-
burger.serve(4000, (port) => {
|
|
165
|
-
console.log(`Server is running on port ${port}`);
|
|
166
|
-
});
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
The `debug` option enables:
|
|
170
|
-
|
|
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
|
|
176
|
-
|
|
177
|
-
This is particularly useful during development to understand how your API is working and troubleshoot issues.
|
|
178
|
-
|
|
179
|
-
### **Recommended Project Structure**
|
|
180
|
-
|
|
181
|
-
Here's a recommended project structure that helps keep your code organized and maintainable:
|
|
182
|
-
|
|
183
|
-
```
|
|
184
|
-
my-api/
|
|
185
|
-
├── src/
|
|
186
|
-
│ ├── api/ # API routes
|
|
187
|
-
│ │ ├── products/
|
|
188
|
-
│ │ │ ├── route.ts # Product routes
|
|
189
|
-
│ │ │ └── [id]/
|
|
190
|
-
│ │ │ └── route.ts # Product detail routes
|
|
191
|
-
│ │ └── users/
|
|
192
|
-
│ │ └── route.ts # User routes
|
|
193
|
-
│ ├── middleware/ # Middleware
|
|
194
|
-
│ │ ├── global/ # Global middleware
|
|
195
|
-
│ │ │ ├── logger.ts
|
|
196
|
-
│ │ │ └── auth.ts
|
|
197
|
-
│ │ └── routes/ # Route-specific middleware
|
|
198
|
-
│ │ ├── products.ts
|
|
199
|
-
│ │ └── users.ts
|
|
200
|
-
│ ├── schemas/ # Zod schemas
|
|
201
|
-
│ │ ├── product.ts
|
|
202
|
-
│ │ └── user.ts
|
|
203
|
-
│ ├── utils/ # Utility functions
|
|
204
|
-
│ │ ├── errors.ts
|
|
205
|
-
│ │ └── helpers.ts
|
|
206
|
-
│ └── index.ts # Main application file
|
|
207
|
-
├── package.json
|
|
208
|
-
└── tsconfig.json
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
### **Example Implementation**
|
|
212
|
-
|
|
213
|
-
Here's how to implement this structure:
|
|
214
|
-
|
|
215
|
-
1. **Global Middleware** (`src/middleware/global/logger.ts`):
|
|
216
|
-
|
|
217
|
-
```ts
|
|
218
|
-
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
219
|
-
|
|
220
|
-
export const logger = async (
|
|
221
|
-
req: BurgerRequest,
|
|
222
|
-
res: BurgerResponse,
|
|
223
|
-
next: () => Promise<Response>
|
|
224
|
-
) => {
|
|
225
|
-
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
|
|
226
|
-
return next();
|
|
227
|
-
};
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
2. **Route-Specific Middleware** (`src/middleware/routes/products.ts`):
|
|
231
|
-
|
|
232
|
-
```ts
|
|
233
|
-
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
234
|
-
|
|
235
|
-
export const validateProductAccess = async (
|
|
236
|
-
req: BurgerRequest,
|
|
237
|
-
res: BurgerResponse,
|
|
238
|
-
next: () => Promise<Response>
|
|
239
|
-
) => {
|
|
240
|
-
// Your middleware logic here
|
|
241
|
-
return next();
|
|
242
|
-
};
|
|
243
|
-
```
|
|
244
|
-
|
|
245
|
-
3. **Schemas** (`src/schemas/product.ts`):
|
|
246
|
-
|
|
247
|
-
```ts
|
|
248
|
-
import { z } from "zod";
|
|
249
|
-
|
|
250
|
-
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
|
-
}),
|
|
261
|
-
};
|
|
262
|
-
```
|
|
263
|
-
|
|
264
|
-
4. **Route File** (`src/api/products/route.ts`):
|
|
265
|
-
|
|
266
|
-
```ts
|
|
267
|
-
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
268
|
-
import { validateProductAccess } from "../../middleware/routes/products";
|
|
269
|
-
import { productSchema } from "../../schemas/product";
|
|
270
|
-
|
|
271
|
-
export const middleware = [validateProductAccess];
|
|
272
|
-
export const schema = {
|
|
273
|
-
post: {
|
|
274
|
-
body: productSchema.create,
|
|
275
|
-
},
|
|
276
|
-
put: {
|
|
277
|
-
body: productSchema.update,
|
|
278
|
-
},
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
export async function GET(req: BurgerRequest, res: BurgerResponse) {
|
|
282
|
-
return res.json({ message: "List of products" });
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
export async function POST(req: BurgerRequest, res: BurgerResponse) {
|
|
286
|
-
const body = req.validated?.body;
|
|
287
|
-
return res.json({ message: "Product created", data: body });
|
|
288
|
-
}
|
|
289
|
-
```
|
|
290
|
-
|
|
291
|
-
5. **Main Application** (`src/index.ts`):
|
|
292
|
-
|
|
293
|
-
```ts
|
|
294
|
-
import { Burger } from "burger-api";
|
|
295
|
-
import { logger } from "./middleware/global/logger";
|
|
296
|
-
|
|
297
|
-
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",
|
|
303
|
-
});
|
|
304
|
-
|
|
305
|
-
burger.serve(4000, (port) => {
|
|
306
|
-
console.log(`Server is running on port ${port}`);
|
|
307
|
-
});
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
This structure provides several benefits:
|
|
311
|
-
|
|
312
|
-
- 🎯 Clear separation of concerns
|
|
313
|
-
- 📁 Easy to find and maintain code
|
|
314
|
-
- 🔄 Reusable components
|
|
315
|
-
- 🧹 Clean and organized codebase
|
|
316
|
-
- 📚 Better scalability
|
|
317
|
-
|
|
318
|
-
### **File-Based Routing Examples**
|
|
319
|
-
|
|
320
|
-
- 📄 **Static API Route:**
|
|
321
|
-
Place a file at `src/api/route.ts` to handle the root API endpoint (e.g., `/api`).
|
|
322
|
-
|
|
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
|
-
```
|
|
331
|
-
|
|
332
|
-
### **Page Directory Structure**
|
|
333
|
-
|
|
334
|
-
burger-api supports serving static pages alongside your API routes. Here's how to use the `pageDir` feature:
|
|
335
|
-
|
|
336
|
-
```ts
|
|
337
|
-
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",
|
|
344
|
-
});
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
#### **Page Directory Structure Example:**
|
|
348
|
-
|
|
349
|
-
```
|
|
350
|
-
my-api/
|
|
351
|
-
├── src/
|
|
352
|
-
│ ├── pages/ # Pages directory
|
|
353
|
-
│ │ ├── index.html # Home page (/)
|
|
354
|
-
│ │ ├── about.html # About page (/about)
|
|
355
|
-
│ │ └── products/
|
|
356
|
-
│ │ ├── index.html # Products list (/products)
|
|
357
|
-
│ │ └── [id]/ # Dynamic product pages
|
|
358
|
-
│ │ └── index.html # Single product (/products/123)
|
|
359
|
-
│ └── api/ # Your API routes
|
|
360
|
-
```
|
|
361
|
-
|
|
362
|
-
#### **Page Routing Features:**
|
|
363
|
-
|
|
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`
|
|
372
|
-
|
|
373
|
-
#### **Example Page Structure:**
|
|
374
|
-
|
|
375
|
-
```html
|
|
376
|
-
<!-- pages/products/[id]/index.html -->
|
|
377
|
-
<!DOCTYPE html>
|
|
378
|
-
<html>
|
|
379
|
-
<head>
|
|
380
|
-
<title>Product Details</title>
|
|
381
|
-
</head>
|
|
382
|
-
<body>
|
|
383
|
-
<h1>Product Details</h1>
|
|
384
|
-
<!-- Content here -->
|
|
385
|
-
</body>
|
|
386
|
-
</html>
|
|
387
|
-
```
|
|
388
|
-
|
|
389
|
-
### **Route File Example**
|
|
390
|
-
|
|
391
|
-
Below is an example route file demonstrating schema validation, route-specific middleware, and OpenAPI metadata.
|
|
392
|
-
|
|
393
|
-
```ts
|
|
394
|
-
// examples/demo/api/product/[id]/route.ts
|
|
395
|
-
|
|
396
|
-
import { z } from "zod";
|
|
397
|
-
import type { BurgerRequest, BurgerResponse } from "burger-api";
|
|
398
|
-
|
|
399
|
-
// OpenAPI metadata for this route
|
|
400
|
-
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
|
-
},
|
|
407
|
-
};
|
|
408
|
-
|
|
409
|
-
// Validation Schemas for GET and POST requests
|
|
410
|
-
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
|
-
},
|
|
428
|
-
};
|
|
429
|
-
|
|
430
|
-
// Route-specific middleware
|
|
431
|
-
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
|
-
},
|
|
440
|
-
];
|
|
441
|
-
|
|
442
|
-
// GET handler: returns product details
|
|
443
|
-
export async function GET(
|
|
444
|
-
req: BurgerRequest,
|
|
445
|
-
res: BurgerResponse,
|
|
446
|
-
params: { id: number }
|
|
447
|
-
) {
|
|
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
|
-
});
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
// POST handler: creates a new product
|
|
459
|
-
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);
|
|
463
|
-
}
|
|
464
|
-
```
|
|
465
|
-
|
|
466
|
-
### **API Documentation Endpoints**
|
|
467
|
-
|
|
468
|
-
- 📚 **OpenAPI JSON:**
|
|
469
|
-
Access `http://localhost:4000/openapi.json` to view the auto-generated OpenAPI specification.
|
|
470
|
-
|
|
471
|
-
- 🔍 **Swagger UI:**
|
|
472
|
-
Access `http://localhost:4000/docs` to view interactive API documentation via Swagger UI.
|
|
74
|
+
We're actively enhancing burger-api with powerful new features Stay tuned for
|
|
75
|
+
updates as we continue to build and improve burger-api! We're committed to
|
|
76
|
+
making it the best API framework for Bun.js.
|
|
473
77
|
|
|
474
78
|
## 🤝 Contributing
|
|
475
79
|
|
|
476
|
-
We welcome contributions from the community! If you have suggestions or
|
|
80
|
+
We welcome contributions from the community! If you have suggestions or
|
|
81
|
+
improvements, please open an issue or submit a pull request. Let's build
|
|
82
|
+
something amazing together.
|
|
477
83
|
|
|
478
84
|
## 📄 License
|
|
479
85
|
|
|
480
|
-
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
481
|
-
|
|
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.
|
|
483
|
-
|
|
484
|
-
## ❓ FAQs & Additional Resources
|
|
485
|
-
|
|
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.
|
|
488
|
-
|
|
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).
|
|
491
|
-
|
|
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.
|
|
494
|
-
|
|
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.
|
|
86
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
87
|
+
for details.
|
|
497
88
|
|
|
498
|
-
|
|
89
|
+
The MIT License is a permissive license that is short and to the point. It lets
|
|
90
|
+
people do anything they want with your code as long as they provide attribution
|
|
91
|
+
back to you and don't hold you liable.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RouteDefinition } from
|
|
1
|
+
import type { RouteDefinition, TrieNode } from '@burgerTypes';
|
|
2
2
|
/**
|
|
3
3
|
* ApiRouter class for handling file-based routing.
|
|
4
4
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
@@ -8,55 +8,63 @@ import type { RouteDefinition } from "../types/index.js";
|
|
|
8
8
|
export declare class ApiRouter {
|
|
9
9
|
private routesDir;
|
|
10
10
|
private prefix;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/** The root of the trie where all routes will begin*/
|
|
12
|
+
private root;
|
|
13
13
|
/**
|
|
14
14
|
* Constructor for the ApiRouter class.
|
|
15
15
|
* @param routesDir The directory path where route modules are located.
|
|
16
16
|
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
17
|
+
* @throws {Error} If the routes directory path is not provided.
|
|
17
18
|
*/
|
|
18
19
|
constructor(routesDir: string, prefix?: string);
|
|
19
20
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
* Getter for the routes trie.
|
|
22
|
+
* @returns The root of the trie.
|
|
23
|
+
*/
|
|
24
|
+
get routes(): TrieNode;
|
|
25
|
+
/**
|
|
26
|
+
* Loads all routes from the routes directory into the trie structure.
|
|
27
|
+
* @returns {Promise<void>} A promise that resolves when all routes are loaded.
|
|
28
|
+
* @throws {Error} If the routes directory is not found or if an error occurs during route loading.
|
|
24
29
|
*/
|
|
25
30
|
loadRoutes(): Promise<void>;
|
|
26
31
|
/**
|
|
27
|
-
*
|
|
28
|
-
* @param
|
|
29
|
-
* @
|
|
30
|
-
|
|
32
|
+
* Inserts a route definition into the trie structure.
|
|
33
|
+
* @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
|
|
34
|
+
* @throws {Error} If the route definition is invalid or causes a conflict in the trie.
|
|
35
|
+
*/
|
|
36
|
+
private insertRoute;
|
|
37
|
+
/**
|
|
38
|
+
* Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
|
|
39
|
+
* @param dir The current directory path to scan.
|
|
40
|
+
* @param basePath The base path used to construct route paths from the directory structure.
|
|
41
|
+
* @returns {Promise<void>} A promise that resolves when the directory scan is complete.
|
|
42
|
+
* @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
|
|
31
43
|
*/
|
|
32
44
|
private scanDirectory;
|
|
33
45
|
/**
|
|
34
|
-
* Loads a route module and
|
|
35
|
-
* @param entryPath
|
|
36
|
-
* @param relativePath
|
|
46
|
+
* Loads a route module from a file and inserts it into the trie.
|
|
47
|
+
* @param entryPath The full file system path to the route module (route.ts).
|
|
48
|
+
* @param relativePath The relative path used to construct the route path.
|
|
49
|
+
* @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
|
|
50
|
+
* @throws {Error} If the route module fails to load or is invalid.
|
|
37
51
|
*/
|
|
38
52
|
private loadRouteModule;
|
|
39
53
|
/**
|
|
40
|
-
* Converts a file path to a route path by processing dynamic segments
|
|
41
|
-
*
|
|
42
|
-
* @
|
|
43
|
-
* @returns The converted route path string.
|
|
54
|
+
* Converts a file path to a route path by processing dynamic segments and applying the prefix.
|
|
55
|
+
* @param filePath The file path to convert (e.g., "users/[id]/route.ts").
|
|
56
|
+
* @returns {string} The converted route path (e.g., "/users/:id").
|
|
44
57
|
*/
|
|
45
58
|
private convertFilePathToRoute;
|
|
46
59
|
/**
|
|
47
|
-
* Resolves
|
|
48
|
-
* @param
|
|
49
|
-
* @
|
|
60
|
+
* Resolves a request to a route definition and its parameters.
|
|
61
|
+
* @param pathname The normalized request pathname.
|
|
62
|
+
* @param method The uppercase HTTP method.
|
|
63
|
+
* @returns {{ route?: RouteDefinition; params: Record<string, string> }} An object containing the matched route (if any) and extracted parameters.
|
|
64
|
+
* @throws {Error} If the request URL is malformed.
|
|
50
65
|
*/
|
|
51
|
-
resolve(
|
|
66
|
+
resolve(pathname: string, method: string): {
|
|
52
67
|
route?: RouteDefinition;
|
|
53
68
|
params: Record<string, string>;
|
|
54
69
|
};
|
|
55
|
-
/**
|
|
56
|
-
* Checks if the request path matches the route path, extracting dynamic parameters if matched.
|
|
57
|
-
* @param requestPath The request path to check.
|
|
58
|
-
* @param routePath The route path to match against.
|
|
59
|
-
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
60
|
-
*/
|
|
61
|
-
private matchRoute;
|
|
62
70
|
}
|