-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe52-api-context-patterns.js
More file actions
340 lines (266 loc) · 11.1 KB
/
Copy pathe52-api-context-patterns.js
File metadata and controls
340 lines (266 loc) · 11.1 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
/**
* Example 52: API Plugin - Context Access Patterns
*
* Demonstrates the 3 different ways to access database and resources
* in custom routes with the API Plugin.
*
* 1. RouteContext Contract (Recommended) - Available in every custom route as `(c, ctx)`
* 2. Context Injection - Direct access via c.get()
* 3. withContext Helper - Explicit wrapper with destructuring
*
* Run: node docs/examples/e52-api-context-patterns.js
*/
import { Database } from '../../src/database.class.js';
import { ApiPlugin, withContext } from '../../src/plugins/api/index.js';
async function main() {
// Create database
const db = new Database({
connectionString: 'memory://api-context-demo/examples'
});
await db.connect();
// Create resources
const urls = await db.createResource({
name: 'urls',
attributes: {
shortId: 'string|required',
target: 'string|required|url',
clicks: 'number|default:0'
}
});
const clicks = await db.createResource({
name: 'clicks',
attributes: {
urlId: 'string|required',
timestamp: 'datetime|required',
ip: 'string|optional'
}
});
// Seed data
await urls.insert({ shortId: 'demo123', target: 'https://example.com', clicks: 0 });
console.log('✅ Created resources: urls, clicks\n');
// ==============================================
// Pattern 1: RouteContext Contract (RECOMMENDED)
// ==============================================
console.log('📦 Pattern 1: RouteContext Contract (Recommended)\n');
const apiEnhanced = new ApiPlugin({
port: 3001,
verbose: false,
docsEnabled: false,
routes: {
// RouteContext is always available as the second argument.
'GET /r/:id': async (c, ctx) => {
console.log(' 🔹 RouteContext Route Handler');
// ✅ Clean resource access with Proxy validation
const url = await ctx.resources.urls.get(ctx.param('id'));
if (!url) {
console.log(' ❌ URL not found');
return ctx.notFound('Short URL not found');
}
console.log(' ✅ Found URL:', url.target);
// ✅ Increment clicks using resource shortcut
await ctx.resources.urls.update(url.id, {
clicks: url.clicks + 1
});
// ✅ Track click event
await ctx.resources.clicks.insert({
urlId: url.id,
timestamp: new Date().toISOString(),
ip: ctx.header('x-forwarded-for') || '127.0.0.1'
});
console.log(' ✅ Tracked click\n');
// ✅ Helper response methods
return ctx.redirect(url.target, 302);
},
'GET /stats/:id': async (c, ctx) => {
console.log(' 🔹 RouteContext with Validation');
// ✅ Param helper
const shortId = ctx.param('id');
// ✅ Resource Proxy automatically validates existence
try {
const url = await ctx.resources.urls.get(shortId);
const clicksList = await ctx.resources.clicks.query({ urlId: url.id });
console.log(` ✅ URL has ${url.clicks} total clicks`);
console.log(` ✅ Found ${clicksList.length} click records\n`);
// ✅ Success helper
return ctx.success({
url: url.target,
clicks: url.clicks,
events: clicksList.length
});
} catch (err) {
console.log(' ❌ Error:', err.message);
return ctx.error(err.message, 404);
}
},
'POST /urls': async (c, ctx) => {
console.log(' 🔹 RouteContext with Validation');
// ✅ Validator helper
const { valid, errors, data } = await ctx.validator.validateBody('urls');
if (!valid) {
console.log(' ❌ Validation failed:', errors);
return ctx.error(errors[0].message, 400);
}
console.log(' ✅ Validation passed');
// ✅ Insert with validated data
const url = await ctx.resources.urls.insert(data);
console.log(' ✅ Created URL:', url.shortId, '\n');
return ctx.success({ url }, 201);
}
}
});
await db.use(apiEnhanced, 'route-context');
console.log('✅ RouteContext API running on port 3001\n');
console.log('Key Benefits:');
console.log(' • One supported `(c, ctx)` contract');
console.log(' • Resource Proxy with validation');
console.log(' • Request helpers (ctx.param, ctx.query, ctx.body)');
console.log(' • Response helpers (ctx.success, ctx.error, ctx.notFound)');
console.log(' • Validator helpers (ctx.validator.validateBody)');
console.log(' • Auth helpers (ctx.user, ctx.hasScope)\n');
// ==============================================
// Pattern 2: Context Injection (Direct)
// ==============================================
console.log('📦 Pattern 2: Context Injection (Direct Access)\n');
const apiDirect = new ApiPlugin({
port: 3002,
verbose: false,
docsEnabled: false,
routes: {
// This handler ignores `ctx` and uses the raw request context directly.
'GET /r/:id': async (c) => {
console.log(' 🔹 Direct Injection Route Handler');
// Direct resource access via c.get()
const urls = c.get('urls');
const clicks = c.get('clicks');
const id = c.req.param('id');
const url = await urls.get(id);
if (!url) {
console.log(' ❌ URL not found');
return c.json({ error: 'Not found' }, 404);
}
console.log(' ✅ Found URL:', url.target);
// Update clicks
await urls.update(url.id, { clicks: url.clicks + 1 });
// Track click
await clicks.insert({
urlId: url.id,
timestamp: new Date().toISOString(),
ip: c.req.header('x-forwarded-for') || '127.0.0.1'
});
console.log(' ✅ Tracked click\n');
return c.redirect(url.target, 302);
},
'GET /health': async (c) => {
console.log(' 🔹 Simple Health Check');
const db = c.get('db');
const urls = c.get('urls');
const count = await urls.count();
console.log(` ✅ Database healthy, ${count} URLs\n`);
return c.json({ healthy: true, urls: count });
}
}
});
await db.use(apiDirect, 'direct');
console.log('✅ Direct Injection API running on port 3002\n');
console.log('Key Benefits:');
console.log(' • Lightweight, minimal abstraction');
console.log(' • Direct request context usage');
console.log(' • Good for simple routes');
console.log(' • No wrapper needed\n');
// ==============================================
// Pattern 3: withContext Helper
// ==============================================
console.log('📦 Pattern 3: withContext Helper (Destructuring)\n');
const apiHelper = new ApiPlugin({
port: 3003,
verbose: false,
docsEnabled: false,
routes: {
// ✨ Explicit wrapper with destructuring
'GET /r/:id': withContext(async (c, { db, resources }) => {
console.log(' 🔹 withContext Helper Route');
// Destructure exactly what you need
const { urls, clicks } = resources;
const id = c.req.param('id');
const url = await urls.get(id);
if (!url) {
console.log(' ❌ URL not found');
return c.json({ error: 'Not found' }, 404);
}
console.log(' ✅ Found URL:', url.target);
await urls.update(url.id, { clicks: url.clicks + 1 });
await clicks.insert({
urlId: url.id,
timestamp: new Date().toISOString(),
ip: c.req.header('x-forwarded-for') || '127.0.0.1'
});
console.log(' ✅ Tracked click\n');
return c.redirect(url.target, 302);
}),
'GET /stats': withContext(async (c, { resources }) => {
console.log(' 🔹 withContext Stats Route');
// Clean destructuring
const { urls, clicks } = resources;
const allUrls = await urls.list({ limit: 10 });
const totalClicks = await clicks.count();
console.log(` ✅ ${allUrls.length} URLs, ${totalClicks} total clicks\n`);
return c.json({
success: true,
data: {
urls: allUrls.length,
clicks: totalClicks
}
});
})
}
});
await db.use(apiHelper, 'helper');
console.log('✅ withContext Helper API running on port 3003\n');
console.log('Key Benefits:');
console.log(' • Explicit wrapper (you control it)');
console.log(' • Clean destructuring syntax');
console.log(' • Resource Proxy with validation');
console.log(' • Functional programming style\n');
// ==============================================
// Test Routes
// ==============================================
console.log('🧪 Testing routes...\n');
// Test RouteContext contract
console.log('Testing RouteContext Contract (3001):');
const res1 = await fetch('http://localhost:3001/stats/demo123');
const json1 = await res1.json();
console.log('Response:', json1, '\n');
// Test direct injection
console.log('Testing Direct Injection (3002):');
const res2 = await fetch('http://localhost:3002/health');
const json2 = await res2.json();
console.log('Response:', json2, '\n');
// Test withContext helper
console.log('Testing withContext Helper (3003):');
const res3 = await fetch('http://localhost:3003/stats');
const json3 = await res3.json();
console.log('Response:', json3, '\n');
// ==============================================
// Comparison Summary
// ==============================================
console.log('📊 Context Pattern Comparison:\n');
console.log('┌─────────────────────┬────────────┬──────────┬─────────────┐');
console.log('│ Feature │ RouteCtx │ Direct │ withContext │');
console.log('├─────────────────────┼────────────┼──────────┼─────────────┤');
console.log('│ Built-in contract │ ✅ │ ✅ │ ❌ │');
console.log('│ Resource Proxy │ ✅ │ ❌ │ ✅ │');
console.log('│ Request Helpers │ ✅ │ ❌ │ ❌ │');
console.log('│ Response Helpers │ ✅ │ ❌ │ ❌ │');
console.log('│ Validator Helpers │ ✅ │ ❌ │ ❌ │');
console.log('│ Auth Helpers │ ✅ │ ⚠️ │ ⚠️ │');
console.log('│ Best For │ Custom │ Simple │ Explicit │');
console.log('└─────────────────────┴────────────┴──────────┴─────────────┘\n');
console.log('💡 Recommendation: Use `RouteContext` (`c, ctx`) for most cases.\n');
// Cleanup
await db.disconnect();
process.exit(0);
}
main().catch(err => {
console.error('Error:', err);
process.exit(1);
});