-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-api-routing.ts
More file actions
61 lines (46 loc) Β· 1.91 KB
/
02-api-routing.ts
File metadata and controls
61 lines (46 loc) Β· 1.91 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
/**
* API Routing Example
*
* Demonstrates how PatternEmitter can handle API-style event routing
* with both exact endpoints and pattern-based handlers
*/
import {PatternEmitter} from '../src/index';
const router = new PatternEmitter();
console.log('=== API ROUTING EXAMPLE ===\n');
// General request logger - catches ALL requests
router.on(/^request/, (method: string, path: string) => {
console.log(` π [Logger] ${method} ${path}`);
});
// Specific endpoint - exact match
router.on('request:users:list', () => {
console.log(' β Handler: GET /users - Listing all users');
// Return value would be: ['Alice', 'Bob', 'Charlie']
});
// Pattern for all user-related endpoints
router.on(/^request:users:/, (action: string) => {
console.log(` π [Middleware] User action: ${action}`);
});
// Pattern for all creation endpoints
router.on(/:create$/, (resource: string) => {
console.log(` β¨ [Analytics] Creating new ${resource}`);
});
// Specific endpoint - create user
router.on('request:users:create', (userData: any) => {
console.log(` β Handler: POST /users - Creating user: ${userData.name}`);
});
// Admin-only endpoints
router.on(/^request:admin:/, (endpoint: string) => {
console.log(` π [Auth] Admin access required for ${endpoint}`);
});
console.log('--- API Requests ---\n');
console.log('Request 1: List Users');
router.emit('request:users:list', 'GET', '/users');
console.log('\nRequest 2: Create User');
router.emit('request:users:create', 'POST', '/users', {name: 'David'});
console.log('\nRequest 3: Admin Dashboard');
router.emit('request:admin:dashboard', 'GET', '/admin/dashboard');
// Show routing statistics
console.log('\n--- Routing Statistics ---\n');
console.log(`Total endpoints: ${router.eventNames().length}`);
console.log(`Total patterns: ${router.eventPatterns().length}`);
console.log(`Handlers for "request:users:create": ${router.listenerCount('request:users:create')}`);