burger-api 0.1.4 → 0.2.1

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
@@ -5,6 +5,7 @@
5
5
  [![Under Development](https://img.shields.io/badge/under%20development-red.svg)](https://github.com/isfhan/burger-api)
6
6
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
7
  [![Bun](https://img.shields.io/badge/Bun-1.2.4-black?logo=bun)](https://bun.sh)
8
+ [![Version](https://img.shields.io/badge/version-0.2.0-green.svg)](https://github.com/isfhan/burger-api/releases)
8
9
 
9
10
  **burger-api** is a modern, open source API framework built on
10
11
  [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
@@ -19,22 +20,15 @@ yet.**
19
20
  ## 📚 Table of Contents
20
21
 
21
22
  - [Overview](#-overview)
22
- - [Features](#-features)
23
- - [Core Features](#core-features)
24
23
  - [Changelog](#-changelog)
25
24
  - [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
25
  - [Contributing](#-contributing)
36
26
  - [License](#-license)
37
- - [FAQs & Resources](#-faqs--additional-resources)
27
+
28
+ ## 📖 Documentation
29
+
30
+ For detailed documentation and examples, visit the
31
+ [BurgerAPI official docs](https://burger-api.com/).
38
32
 
39
33
  ## 🚀 Overview
40
34
 
@@ -48,8 +42,7 @@ burger-api is built to offer a robust developer experience through:
48
42
  naming convention.
49
43
 
50
44
  - 🔄 **Middleware Architecture:**
51
- Supports both global and route-specific middleware with a familiar
52
- `req, res, next` pattern.
45
+ Supports both global and route-specific middleware.
53
46
 
54
47
  - ✅ **Type-Safe Validation:**
55
48
  Utilizes Zod for request validation, ensuring full type safety and automatic
@@ -64,434 +57,23 @@ burger-api is built to offer a robust developer experience through:
64
57
  Provides an out-of-the-box Swagger UI endpoint for interactive API
65
58
  documentation.
66
59
 
67
- ## ✨ Features
68
-
69
- ### Core Features
70
-
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).
86
-
87
- - 🔄 **Middleware System:**
88
-
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.
93
-
94
- - ✅ **Zod-Based Schema Validation:**
95
- Automatically validates request params, query, and body using Zod.
96
-
97
- - Supports preprocessing (e.g., converting URL parameters from string to
98
- number).
99
-
100
- - 📚 **Automatic OpenAPI Specification Generation:**
101
- Generates an OpenAPI 3.0 document using route metadata and Zod schemas.
102
-
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)
109
-
110
- - 🔍 **Swagger UI Integration:**
111
- Provides a `/docs` endpoint serving an interactive Swagger UI that reads
112
- from `/openapi.json`.
113
-
114
60
  ## 📣 Changelog
115
61
 
116
- For detailed release notes, please refer to the [Changelog](CHANGELOG.md) file.
62
+ ### Latest Version: 0.2.0 (April 26, 2025)
117
63
 
118
- ### Version 0.1.3 (March 15, 2024)
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
119
69
 
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
70
+ For a complete list of changes, please check the [Changelog](CHANGELOG.md) file.
127
71
 
128
72
  ## 🎯 What's Coming Next?
129
73
 
130
- We're actively enhancing burger-api with powerful new features:
131
-
132
- ### 🎨 Page Serving Enhancements (In Development)
133
-
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.
149
-
150
- ## 📦 Installation
151
-
152
- Install burger-api via bun:
153
-
154
- ```bash
155
- bun add burger-api
156
- ```
157
-
158
- ## 🚀 How to Use burger-api
159
-
160
- ### **Basic Usage Example**
161
-
162
- ```ts
163
- import { Burger } from 'burger-api';
164
-
165
- // Global middleware example: a simple logger.
166
- const globalLogger = async (req, res, next) => {
167
- console.log(`[Global Logger] ${req.method} ${req.url}`);
168
- return next();
169
- };
170
-
171
- const burger = new Burger({
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
178
- });
179
-
180
- // Start the server on port 4000 with a callback
181
- burger.serve(4000, (port) => {
182
- console.log(`Server is running on port ${port}`);
183
- });
184
- ```
185
-
186
- The `debug` option enables:
187
-
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.
196
-
197
- ### **Recommended Project Structure**
198
-
199
- Here's a recommended project structure that helps keep your code organized and
200
- maintainable:
201
-
202
- ```
203
- my-api/
204
- ├── src/
205
- │ ├── api/ # API routes
206
- │ │ ├── products/
207
- │ │ │ ├── route.ts # Product routes
208
- │ │ │ └── [id]/
209
- │ │ │ └── route.ts # Product detail routes
210
- │ │ └── users/
211
- │ │ └── route.ts # User routes
212
- │ ├── middleware/ # Middleware
213
- │ │ ├── global/ # Global middleware
214
- │ │ │ ├── logger.ts
215
- │ │ │ └── auth.ts
216
- │ │ └── routes/ # Route-specific middleware
217
- │ │ ├── products.ts
218
- │ │ └── users.ts
219
- │ ├── schemas/ # Zod schemas
220
- │ │ ├── product.ts
221
- │ │ └── user.ts
222
- │ ├── utils/ # Utility functions
223
- │ │ ├── errors.ts
224
- │ │ └── helpers.ts
225
- │ └── index.ts # Main application file
226
- ├── package.json
227
- └── tsconfig.json
228
- ```
229
-
230
- ### **Example Implementation**
231
-
232
- Here's how to implement this structure:
233
-
234
- 1. **Global Middleware** (`src/middleware/global/logger.ts`):
235
-
236
- ```ts
237
- import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
238
-
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();
246
- };
247
- ```
248
-
249
- 2. **Route-Specific Middleware** (`src/middleware/routes/products.ts`):
250
-
251
- ```ts
252
- import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
253
-
254
- export const validateProductAccess = async (
255
- req: BurgerRequest,
256
- res: BurgerResponse,
257
- next: BurgerNext
258
- ) => {
259
- // Your middleware logic here
260
- return next();
261
- };
262
- ```
263
-
264
- 3. **Schemas** (`src/schemas/product.ts`):
265
-
266
- ```ts
267
- import { z } from 'zod';
268
-
269
- export const productSchema = {
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
- }),
280
- };
281
- ```
282
-
283
- 4. **Route File** (`src/api/products/route.ts`):
284
-
285
- ```ts
286
- import type { BurgerRequest, BurgerResponse } from 'burger-api';
287
- import { validateProductAccess } from '../../middleware/routes/products';
288
- import { productSchema } from '../../schemas/product';
289
-
290
- export const middleware = [validateProductAccess];
291
- export const schema = {
292
- post: {
293
- body: productSchema.create,
294
- },
295
- put: {
296
- body: productSchema.update,
297
- },
298
- };
299
-
300
- export async function GET(req: BurgerRequest, res: BurgerResponse) {
301
- return res.json({ message: 'List of products' });
302
- }
303
-
304
- export async function POST(req: BurgerRequest, res: BurgerResponse) {
305
- const body = req.validated?.body;
306
- return res.json({ message: 'Product created', data: body });
307
- }
308
- ```
309
-
310
- 5. **Main Application** (`src/index.ts`):
311
-
312
- ```ts
313
- import { Burger } from 'burger-api';
314
- import { logger } from './middleware/global/logger';
315
-
316
- const burger = new Burger({
317
- title: 'Product API',
318
- description: 'API for managing products',
319
- apiDir: 'api',
320
- globalMiddleware: [logger],
321
- version: '1.0.0',
322
- });
323
-
324
- burger.serve(4000, (port) => {
325
- console.log(`Server is running on port ${port}`);
326
- });
327
- ```
328
-
329
- This structure provides several benefits:
330
-
331
- - 🎯 Clear separation of concerns
332
- - 📁 Easy to find and maintain code
333
- - 🔄 Reusable components
334
- - 🧹 Clean and organized codebase
335
- - 📚 Better scalability
336
-
337
- ### **File-Based Routing Examples**
338
-
339
- - 📄 **Static API Route:**
340
- Place a file at `src/api/route.ts` to handle the root API endpoint (e.g.,
341
- `/api`).
342
-
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
- ```
410
-
411
- ### **Route File Example**
412
-
413
- Below is an example route file demonstrating schema validation, route-specific
414
- middleware, and OpenAPI metadata.
415
-
416
- ```ts
417
- // examples/demo/api/product/[id]/route.ts
418
-
419
- import { z } from 'zod';
420
- import type { BurgerRequest, BurgerResponse, BurgerNext } from 'burger-api';
421
-
422
- // OpenAPI metadata for this route
423
- export const openapi = {
424
- get: {
425
- summary: 'Get Product Details',
426
- description: 'Retrieves product details by product ID.',
427
- tags: ['Product'],
428
- operationId: 'getProductDetails',
429
- },
430
- };
431
-
432
- // Validation Schemas for GET and POST requests
433
- export const schema = {
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
- },
451
- };
452
-
453
- // Route-specific middleware
454
- export const middleware = [
455
- async (req: BurgerRequest, res: BurgerResponse, next: BurgerNext) => {
456
- console.log('[Product Middleware] Executing product route middleware');
457
- return next();
458
- },
459
- ];
460
-
461
- // GET handler: returns product details
462
- export async function GET(
463
- req: BurgerRequest,
464
- res: BurgerResponse,
465
- params: { id: number }
466
- ) {
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
- });
476
- }
477
-
478
- // POST handler: creates a new product
479
- export async function POST(req: BurgerRequest, res: BurgerResponse) {
480
- console.log('[POST] Product route invoked');
481
- const body = req.validated?.body || (await req.json());
482
- return res.json(body);
483
- }
484
- ```
485
-
486
- ### **API Documentation Endpoints**
487
-
488
- - 📚 **OpenAPI JSON:**
489
- Access `http://localhost:4000/openapi.json` to view the auto-generated
490
- OpenAPI specification.
491
-
492
- - 🔍 **Swagger UI:**
493
- Access `http://localhost:4000/docs` to view interactive API documentation
494
- 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.
495
77
 
496
78
  ## 🤝 Contributing
497
79
 
@@ -507,24 +89,3 @@ for details.
507
89
  The MIT License is a permissive license that is short and to the point. It lets
508
90
  people do anything they want with your code as long as they provide attribution
509
91
  back to you and don't hold you liable.
510
-
511
- ## ❓ FAQs & Additional Resources
512
-
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.
516
-
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).
520
-
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.
524
-
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.
528
-
529
- _burger-api_ aims to revolutionize your API development experience with
530
- simplicity, speed, and cutting-edge features. Happy coding! 🚀
@@ -1,4 +1,4 @@
1
- import type { RouteDefinition } from '../types/index.js';
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
- /** Array of loaded route definitions */
12
- routes: RouteDefinition[];
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
- * Loads route modules from the specified directory and adds them to the routes array.
21
- * After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
22
- * @returns A promise that resolves when all route modules have been loaded and sorted.
23
- * @throws Error if the routes directory doesn't exist or can't be accessed
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
- * Recursively scans the directory for route modules and adds them to the routes array.
28
- * @param dir The current directory to scan.
29
- * @param basePath The base path for constructing the route path.
30
- * @throws Error if multiple dynamic folders are found at the same level or if directory access fails
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 adds it to the routes array
35
- * @param entryPath Full path to the route file
36
- * @param relativePath Relative path used to construct the route
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
- * removing certain directory indicators, and applying a prefix if specified.
42
- * @param filePath The file path to convert into a route path.
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 the given request by finding a matching route and extracting dynamic parameters.
48
- * @param request The request to resolve.
49
- * @returns An object containing the matched route and parameters, or an empty params object if no match.
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(request: Request): {
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
  }