-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmiddleware-example.ts
More file actions
363 lines (306 loc) · 9.76 KB
/
Copy pathmiddleware-example.ts
File metadata and controls
363 lines (306 loc) · 9.76 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/**
* Middleware Manager Usage Example
*
* This example demonstrates how to use the MiddlewareManager to organize
* and control middleware execution in your HTTP server.
*/
import { MiddlewareManager } from '@objectstack/runtime';
import type { Middleware } from '@objectstack/core';
/**
* Example: Creating Custom Middleware
*/
// Logging middleware
const loggingMiddleware: Middleware = async (req, res, next) => {
const start = Date.now();
console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
await next();
const duration = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.path} - ${duration}ms`);
};
// Authentication middleware
const authMiddleware: Middleware = async (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
res.status(401).json({ error: 'Authorization required' });
return;
}
// Validate token (simplified example)
const token = authHeader.toString().replace('Bearer ', '');
if (token === 'valid-token') {
// Add user info to request
(req as any).user = { id: '123', name: 'John Doe' };
await next();
} else {
res.status(401).json({ error: 'Invalid token' });
}
};
// CORS middleware
const corsMiddleware: Middleware = async (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.status(200).json({});
return;
}
await next();
};
// Request validation middleware
const validationMiddleware: Middleware = async (req, res, next) => {
// Validate request body if present
if (req.method === 'POST' || req.method === 'PATCH' || req.method === 'PUT') {
if (!req.body) {
res.status(400).json({ error: 'Request body required' });
return;
}
}
await next();
};
// Error handling middleware
const errorMiddleware: Middleware = async (req, res, next) => {
try {
await next();
} catch (error: any) {
console.error('Error:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message
});
}
};
/**
* Example: Setting up Middleware Manager
*/
function setupMiddlewareManager() {
const manager = new MiddlewareManager();
// Register middleware with different priorities
// Lower order values execute first
// 1. Error handling should wrap everything (order: 1)
manager.register({
name: 'error_handler',
type: 'error',
enabled: true,
order: 1,
}, errorMiddleware);
// 2. CORS headers early (order: 10)
manager.register({
name: 'cors',
type: 'custom',
enabled: true,
order: 10,
}, corsMiddleware);
// 3. Logging (order: 20)
manager.register({
name: 'logger',
type: 'logging',
enabled: true,
order: 20,
}, loggingMiddleware);
// 4. Authentication (order: 30)
// Exclude health and metrics endpoints
manager.register({
name: 'auth',
type: 'authentication',
enabled: true,
order: 30,
paths: {
exclude: ['/health', '/metrics', '/api/v1'] // Public endpoints
}
}, authMiddleware);
// 5. Validation (order: 40)
manager.register({
name: 'validation',
type: 'validation',
enabled: true,
order: 40,
}, validationMiddleware);
return manager;
}
/**
* Example: Using Middleware Manager with HTTP Server
*/
function applyMiddlewareToServer(server: any, manager: MiddlewareManager) {
// Get the ordered middleware chain
const chain = manager.getMiddlewareChain();
// Apply each middleware to the server
chain.forEach((middleware: Middleware) => {
server.use(middleware);
});
console.log(`Applied ${chain.length} middleware to server`);
}
/**
* Example: Dynamic Middleware Management
*/
function dynamicMiddlewareControl(manager: MiddlewareManager) {
// Disable authentication temporarily (e.g., for maintenance)
manager.disable('auth');
console.log('Authentication disabled');
// Re-enable after maintenance
manager.enable('auth');
console.log('Authentication re-enabled');
// Get middleware for specific path
const middlewareForApiPath = manager.getMiddlewareChainForPath('/api/v1/data/user');
console.log(`Middleware for /api/v1/data/user: ${middlewareForApiPath.length}`);
const middlewareForHealthPath = manager.getMiddlewareChainForPath('/health');
console.log(`Middleware for /health: ${middlewareForHealthPath.length}`);
// Get middleware by type
const authMiddlewares = manager.getByType('authentication');
console.log(`Authentication middleware count: ${authMiddlewares.length}`);
}
/**
* Example: Advanced Middleware Patterns
*/
// Rate limiting middleware with configuration
function createRateLimitMiddleware(config: {
windowMs: number;
maxRequests: number;
}): Middleware {
const requests = new Map<string, number[]>();
return async (req, res, next) => {
const ip = req.headers['x-forwarded-for']?.toString() || 'unknown';
const now = Date.now();
const windowStart = now - config.windowMs;
// Get request timestamps for this IP
const timestamps = requests.get(ip) || [];
// Filter out old requests
const recentRequests = timestamps.filter(t => t > windowStart);
if (recentRequests.length >= config.maxRequests) {
res.status(429).json({
error: 'Too many requests',
retryAfter: Math.ceil((recentRequests[0] + config.windowMs - now) / 1000)
});
return;
}
// Add current request
recentRequests.push(now);
requests.set(ip, recentRequests);
await next();
};
}
// Caching middleware
function createCacheMiddleware(ttl: number): Middleware {
const cache = new Map<string, { data: any; expiry: number }>();
return async (req, res, next) => {
// Only cache GET requests
if (req.method !== 'GET') {
await next();
return;
}
const cacheKey = `${req.method}:${req.path}`;
const cached = cache.get(cacheKey);
if (cached && cached.expiry > Date.now()) {
res.header('X-Cache', 'HIT');
res.json(cached.data);
return;
}
// Store original json method
const originalJson = res.json.bind(res);
// Override json method to cache response
res.json = (data: any) => {
cache.set(cacheKey, {
data,
expiry: Date.now() + ttl
});
res.header('X-Cache', 'MISS');
return originalJson(data);
};
await next();
};
}
/**
* Example: Complete Setup with Advanced Middleware
*/
function setupAdvancedMiddleware() {
const manager = new MiddlewareManager();
// Basic middleware
manager.register({
name: 'cors',
type: 'custom',
enabled: true,
order: 10,
}, corsMiddleware);
manager.register({
name: 'logger',
type: 'logging',
enabled: true,
order: 20,
}, loggingMiddleware);
// Rate limiting (100 requests per minute)
manager.register({
name: 'rate_limit',
type: 'custom',
enabled: true,
order: 25,
config: {
windowMs: 60000,
maxRequests: 100
}
}, createRateLimitMiddleware({
windowMs: 60000,
maxRequests: 100
}));
// Authentication with exclusions
manager.register({
name: 'auth',
type: 'authentication',
enabled: true,
order: 30,
paths: {
exclude: ['/health', '/metrics', '/api/v1']
}
}, authMiddleware);
// Caching for GET requests (5 minute TTL)
manager.register({
name: 'cache',
type: 'custom',
enabled: true,
order: 35,
paths: {
include: ['/api/v1/meta/*'] // Only cache metadata
}
}, createCacheMiddleware(300000));
manager.register({
name: 'validation',
type: 'validation',
enabled: true,
order: 40,
}, validationMiddleware);
return manager;
}
/**
* Example: Inspecting Middleware
*/
function inspectMiddleware(manager: MiddlewareManager) {
console.log('\n=== Middleware Registry ===');
const all = manager.getAll();
all.forEach(entry => {
console.log(`\n${entry.name}:`);
console.log(` Type: ${entry.type}`);
console.log(` Order: ${entry.order}`);
console.log(` Enabled: ${entry.enabled}`);
if (entry.paths) {
if (entry.paths.include) {
console.log(` Include paths: ${entry.paths.include.join(', ')}`);
}
if (entry.paths.exclude) {
console.log(` Exclude paths: ${entry.paths.exclude.join(', ')}`);
}
}
});
console.log(`\nTotal middleware: ${manager.count()}`);
}
// Export for use in other modules
export {
setupMiddlewareManager,
applyMiddlewareToServer,
dynamicMiddlewareControl,
setupAdvancedMiddleware,
inspectMiddleware,
loggingMiddleware,
authMiddleware,
corsMiddleware,
validationMiddleware,
errorMiddleware,
createRateLimitMiddleware,
createCacheMiddleware
};