Skip to content

Commit 56f14d2

Browse files
authored
Introducing built-in middlewares (#9)
* introducing built-in middlewares
1 parent 61882cd commit 56f14d2

22 files changed

+10229
-10
lines changed

README.md

Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ A high-performance, minimalist HTTP framework for [Bun](https://bun.sh/), inspir
55
## Key Benefits
66

77
- **🚀 Bun-Native Performance**: Optimized for Bun's runtime with minimal overhead
8-
- **⚡ Zero Dependencies**: Core framework uses only essential, lightweight dependencies
98
- **🔧 TypeScript First**: Full TypeScript support with comprehensive type definitions
109
- **🎯 Minimalist API**: Clean, intuitive API that's easy to learn and use
1110
- **🔄 Middleware Support**: Flexible middleware system with async/await support
@@ -203,6 +202,42 @@ Bun.serve({
203202
})
204203
```
205204

205+
## Middleware Support
206+
207+
0http-bun includes a comprehensive middleware system with built-in middlewares for common use cases:
208+
209+
- **[Body Parser](./lib/middleware/README.md#body-parser)** - Automatic request body parsing (JSON, form data, text)
210+
- **[CORS](./lib/middleware/README.md#cors)** - Cross-Origin Resource Sharing with flexible configuration
211+
- **[JWT Authentication](./lib/middleware/README.md#jwt-authentication)** - JSON Web Token authentication and authorization
212+
- **[Logger](./lib/middleware/README.md#logger)** - Request logging with multiple output formats
213+
- **[Rate Limiting](./lib/middleware/README.md#rate-limiting)** - Flexible rate limiting with sliding window support
214+
215+
### Quick Example
216+
217+
```javascript
218+
// Import middleware functions from the middleware module
219+
const {
220+
createCORS,
221+
createLogger,
222+
createBodyParser,
223+
createJWTAuth,
224+
createRateLimit,
225+
} = require('0http-bun/lib/middleware')
226+
227+
const {router} = http()
228+
229+
// Apply middleware stack
230+
router.use(createCORS()) // Enable CORS
231+
router.use(createLogger()) // Request logging
232+
router.use(createBodyParser()) // Parse request bodies
233+
router.use(createRateLimit({max: 100})) // Rate limiting
234+
235+
// Protected routes
236+
router.use('/api/*', createJWTAuth({secret: process.env.JWT_SECRET}))
237+
```
238+
239+
📖 **[Complete Middleware Documentation](./lib/middleware/README.md)**
240+
206241
### Error Handling
207242

208243
```typescript
@@ -245,8 +280,9 @@ router.get('/api/risky', (req: ZeroRequest) => {
245280

246281
- **Minimal overhead**: Direct use of Web APIs
247282
- **Efficient routing**: Based on the proven `trouter` library
248-
- **Fast parameter parsing**: Optimized URL parameter extraction
249-
- **Query string parsing**: Uses `fast-querystring` for performance
283+
- **Fast parameter parsing**: Optimized URL parameter extraction with caching
284+
- **Query string parsing**: Uses `fast-querystring` for optimal performance
285+
- **Memory efficient**: Route caching and object reuse to minimize allocations
250286

251287
### Benchmark Results
252288

@@ -256,18 +292,51 @@ Run benchmarks with:
256292
bun run bench
257293
```
258294

295+
_Performance characteristics will vary based on your specific use case and middleware stack._
296+
259297
## TypeScript Support
260298

261299
Full TypeScript support is included with comprehensive type definitions:
262300

263301
```typescript
302+
// Main framework types
264303
import {
265304
ZeroRequest,
266305
StepFunction,
267306
RequestHandler,
268307
IRouter,
269308
IRouterConfig,
270309
} from '0http-bun'
310+
311+
// Middleware-specific types
312+
import {
313+
LoggerOptions,
314+
JWTAuthOptions,
315+
APIKeyAuthOptions,
316+
RateLimitOptions,
317+
CORSOptions,
318+
BodyParserOptions,
319+
MemoryStore,
320+
} from '0http-bun/lib/middleware'
321+
322+
// Example typed middleware
323+
const customMiddleware: RequestHandler = (
324+
req: ZeroRequest,
325+
next: StepFunction,
326+
) => {
327+
req.ctx = req.ctx || {}
328+
req.ctx.timestamp = Date.now()
329+
return next()
330+
}
331+
332+
// Example typed route handler
333+
const typedHandler = (req: ZeroRequest): Response => {
334+
return Response.json({
335+
params: req.params,
336+
query: req.query,
337+
context: req.ctx,
338+
})
339+
}
271340
```
272341

273342
## License

common.d.ts

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {Pattern, Methods} from 'trouter'
2+
import {Logger} from 'pino'
23

34
export interface IRouterConfig {
45
defaultRoute?: RequestHandler
@@ -8,10 +9,44 @@ export interface IRouterConfig {
89

910
export type StepFunction = (error?: unknown) => Response | Promise<Response>
1011

11-
type ZeroRequest = Request & {
12+
export interface ParsedFile {
13+
name: string
14+
size: number
15+
type: string
16+
data: File
17+
}
18+
19+
export type ZeroRequest = Request & {
1220
params: Record<string, string>
1321
query: Record<string, string>
14-
ctx?: Record<string, any>
22+
// Legacy compatibility properties (mirrored from ctx)
23+
user?: any
24+
jwt?: {
25+
payload: any
26+
header: any
27+
token: string
28+
}
29+
apiKey?: string
30+
// Context object for middleware data
31+
ctx?: {
32+
log?: Logger
33+
user?: any
34+
jwt?: {
35+
payload: any
36+
header: any
37+
token: string
38+
}
39+
apiKey?: string
40+
rateLimit?: {
41+
limit: number
42+
used: number
43+
remaining: number
44+
resetTime: Date
45+
}
46+
body?: any
47+
files?: Record<string, ParsedFile | ParsedFile[]>
48+
[key: string]: any
49+
}
1550
}
1651

1752
export type RequestHandler = (

0 commit comments

Comments
 (0)