-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbasic.ts
More file actions
101 lines (96 loc) · 2.5 KB
/
basic.ts
File metadata and controls
101 lines (96 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { BunGateway } from '../src'
import { BunGateLogger } from '../src'
const logger = new BunGateLogger({
level: 'error',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
},
serializers: {
req: (req) => ({
method: req.method,
url: req.url,
}),
res: (res) => ({
statusCode: res.status,
}),
},
})
const gateway = new BunGateway({
logger,
server: { port: 3000, development: false },
})
// Basic rate limiting example
gateway.addRoute({
pattern: '/api/simple/*',
target: 'http://localhost:8080',
proxy: {
pathRewrite: (path) => {
return path.replace('/api/simple', '')
},
},
// rateLimit: {
// windowMs: 60000,
// max: 100, // 100 requests per user per minute
// keyGenerator: async (req) => {
// // Use user ID from JWT token or IP address as fallback
// return req.ctx?.user?.id || req.headers.get("x-forwarded-for") || "anonymous";
// },
// },
})
// Basic rate limiting example
gateway.addRoute({
pattern: '/api/lb/*',
// rateLimit: {
// windowMs: 60000, // 1 minute
// max: 100, // 100 requests per user per minute
// keyGenerator: async (req) => {
// // Use user ID from JWT token or IP address as fallback
// return req.ctx?.user?.id || req.headers.get("x-forwarded-for") || "anonymous";
// },
// },
loadBalancer: {
healthCheck: {
enabled: true,
interval: 5000, // Check every 5 seconds
timeout: 2000, // Timeout after 2 seconds
path: '/get',
},
targets: [
{ url: 'http://localhost:8080', weight: 1 },
{ url: 'http://localhost:8081', weight: 1 },
],
strategy: 'least-connections',
},
proxy: {
pathRewrite: (path) => {
return path.replace('/api/lb', '')
},
},
hooks: {
afterCircuitBreakerExecution: async (req, result) => {
logger.info(
`Circuit breaker ${result.success ? 'succeeded' : 'failed'} for ${req.url} after ${result.executionTimeMs} ms`,
)
},
},
circuitBreaker: {
enabled: true,
failureThreshold: 3, // Fail after 3 consecutive errors
resetTimeout: 10000, // Reset after 10 seconds
timeout: 2000, // Timeout after 2 seconds
},
})
// Start the server
await gateway.listen(3000)
console.log('Gateway running on http://localhost:3000')
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('\nShutting down...')
await gateway.close()
process.exit(0)
})