-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresponse-patterns-example.ts
More file actions
476 lines (382 loc) · 13.3 KB
/
response-patterns-example.ts
File metadata and controls
476 lines (382 loc) · 13.3 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/**
* Standardized Response Patterns Example
*
* This example demonstrates all the standardized response helpers
* available in MoroJS for creating consistent API responses.
*
* Three ways to send responses:
* 1. res.success() / res.error() / res.notFound() etc. - Most intuitive, built into response object
* 2. response.* helpers - For building response objects (notFound, unauthorized, etc.)
* 3. ResponseBuilder - For complex scenarios with chaining
*
* Covers all available methods:
* - res.success() / res.error()
* - res.created() / res.noContent() / res.paginated()
* - res.unauthorized() / res.forbidden() / res.notFound()
* - res.badRequest() / res.conflict() / res.internalError()
* - res.validationError() / res.rateLimited()
*/
import { createApp, response, z, ResponseBuilder } from '../src/index';
import type { ApiSuccessResponse, ApiErrorResponse } from '../src/index';
const app = await createApp();
// ===== Mock Database =====
interface User {
id: number;
name: string;
email: string;
role: 'user' | 'admin';
age?: number;
}
const users: User[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com', role: 'user' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'admin', age: 28 },
];
let nextId = 3;
// ===== Validation Schemas =====
const UserSchema = z.object({
name: z.string().min(2).max(50),
email: z.string().email(),
age: z.number().min(18).optional(),
});
const UpdateUserSchema = UserSchema.partial();
// ===== Example 1: Using res.success() and res.error() (Recommended) =====
// Basic success response using res.success()
app.get('/users', async (req, res) => {
res.success(users);
});
// Success with message using res.success()
app.get('/users/with-message', async (req, res) => {
res.success(users, `Found ${users.length} users`);
});
// Using res.created() - sets 201 status automatically
app
.post('/users/create-admin')
.body(UserSchema)
.handler(async (req, res) => {
const user = {
id: nextId++,
...req.body,
role: 'admin' as const,
};
users.push(user);
// res.created() automatically sets 201 status and can include Location header
res.created(user, `/users/${user.id}`);
});
// ===== Example 2: Using res.error() Method =====
// Basic error response using res.error()
app.get('/error-example', async (req, res) => {
res.status(500).error('Something went wrong');
});
// Error with code and message using res.error()
app.get('/error-detailed', async (req, res) => {
res
.status(500)
.error(
'Database connection failed',
'DB_ERROR',
'Unable to connect to the database. Please try again later.'
);
});
// ===== Example 3: Using res.notFound() Method (Automatic Status Code) =====
// res.notFound() automatically sets 404 status
app
.get('/users/:id')
.params(z.object({ id: z.coerce.number() }))
.handler(async (req, res) => {
// Zod coerces to number, but TypeScript doesn't know this
const userId = req.params.id as unknown as number;
const user = users.find(u => u.id === userId);
if (!user) {
return res.notFound('User');
}
res.success(user);
});
// ===== Example 4: res.unauthorized() - Automatic 401 =====
app.get('/profile', async (req, res) => {
// Simulate auth check
const isAuthenticated = req.headers['authorization'];
if (!isAuthenticated) {
return res.unauthorized('Please log in to access your profile');
}
res.success({ name: 'User Profile' });
});
// ===== Example 5: res.forbidden() - Automatic 403 =====
app
.delete('/users/:id')
.params(z.object({ id: z.coerce.number() }))
.handler(async (req, res) => {
// Simulate role check
const userRole = req.headers['x-user-role'];
if (userRole !== 'admin') {
return res.forbidden('Only admins can delete users');
}
// Zod coerces to number, but TypeScript doesn't know this
const userId = req.params.id as unknown as number;
const userIndex = users.findIndex(u => u.id === userId);
if (userIndex === -1) {
return res.notFound('User');
}
const deletedUser = users.splice(userIndex, 1)[0];
res.success(deletedUser, 'User deleted successfully');
});
// ===== Example 6: res.badRequest() - Automatic 400 =====
app.post('/upload', async (req, res) => {
if (!req.files || !req.files.file) {
return res.badRequest('File is required');
}
res.success({ uploaded: true }, 'File uploaded successfully');
});
// ===== Example 7: res.conflict() - Automatic 409 =====
app
.post('/users')
.body(UserSchema)
.handler(async (req, res) => {
// Check for duplicate email
const existing = users.find(u => u.email === req.body.email);
if (existing) {
return res.conflict('Email already in use');
}
const newUser = {
id: nextId++,
...req.body,
role: 'user' as const,
};
users.push(newUser);
// Using res.created() for 201 status
res.created(newUser, `/users/${newUser.id}`);
});
// ===== Example 8: res.validationError() - Automatic 422 =====
app.post('/users/manual-validation', async (req, res) => {
const errors: Array<{ field: string; message: string; code?: string }> = [];
if (!req.body.name || req.body.name.length < 2) {
errors.push({
field: 'name',
message: 'Name must be at least 2 characters',
code: 'MIN_LENGTH',
});
}
if (!req.body.email || !req.body.email.includes('@')) {
errors.push({
field: 'email',
message: 'Invalid email format',
code: 'INVALID_EMAIL',
});
}
if (req.body.age && req.body.age < 18) {
errors.push({
field: 'age',
message: 'Must be at least 18 years old',
code: 'AGE_RESTRICTION',
});
}
if (errors.length > 0) {
return res.validationError(errors);
}
const newUser = {
id: nextId++,
...req.body,
role: 'user' as const,
};
users.push(newUser);
res.success(newUser, 'User created successfully');
});
// ===== Example 9: res.rateLimited() - Automatic 429 with Retry-After Header =====
// Simulate rate limiting
const rateLimitMap = new Map<string, number>();
app.post('/api/send-email', async (req, res) => {
const ip = req.ip || 'unknown';
const count = rateLimitMap.get(ip) || 0;
if (count >= 5) {
// res.rateLimited() automatically sets 429 status and Retry-After header
return res.rateLimited(60);
}
rateLimitMap.set(ip, count + 1);
// Reset after 60 seconds
setTimeout(() => {
rateLimitMap.delete(ip);
}, 60000);
res.success({ sent: true }, 'Email sent successfully');
});
// ===== Example 10: res.internalError() - Automatic 500 =====
app.get('/unstable-endpoint', async (req, res) => {
try {
// Simulate an error
if (Math.random() > 0.5) {
throw new Error('Random failure occurred');
}
res.success({ data: 'Success!' });
} catch (error) {
res.internalError('An unexpected error occurred');
}
});
// ===== Example 11: Using ResponseBuilder =====
app
.get('/users/builder-example')
.query(z.object({ limit: z.coerce.number().default(10) }))
.handler(async (req, res) => {
// Zod coerces to number, but TypeScript doesn't know this
const limit = req.query.limit as unknown as number;
const limitedUsers = users.slice(0, limit);
return ResponseBuilder.success(limitedUsers)
.message(`Successfully retrieved ${limitedUsers.length} users`)
.build();
});
app
.get('/users/:id/builder-error')
.params(z.object({ id: z.coerce.number() }))
.handler(async (req, res) => {
// Zod coerces to number, but TypeScript doesn't know this
const userId = req.params.id as unknown as number;
const user = users.find(u => u.id === userId);
if (!user) {
return res
.status(404)
.json(
ResponseBuilder.error('User not found', 'USER_NOT_FOUND')
.message('The requested user does not exist in our system')
.details({ userId: req.params.id, timestamp: new Date() })
.build()
);
}
return ResponseBuilder.success(user).build();
});
// ===== Example 12: Complete CRUD with Standardized Responses =====
// Update user
app
.put('/users/:id')
.params(z.object({ id: z.coerce.number() }))
.body(UpdateUserSchema)
.handler(async (req, res) => {
// Zod coerces to number, but TypeScript doesn't know this
const userId = req.params.id as unknown as number;
const userIndex = users.findIndex(u => u.id === userId);
if (userIndex === -1) {
return res.status(404).json(response.notFound('User'));
}
// Check email uniqueness if being updated
if (req.body.email) {
const existing = users.find(u => u.email === req.body.email && u.id !== userId);
if (existing) {
return res.status(409).json(response.conflict('Email already in use'));
}
}
users[userIndex] = {
...users[userIndex],
...req.body,
};
return response.success(users[userIndex], 'User updated successfully');
});
// ===== Example 13: Using res.success() and res.error() Methods =====
// Most intuitive - use the response methods directly
app.get('/simple/users', async (req, res) => {
res.success(users);
});
app.get('/simple/users/:id', async (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).error('User not found', 'USER_NOT_FOUND');
}
res.success(user);
});
app.get('/simple/protected', async (req, res) => {
if (!req.headers['authorization']) {
return res.status(401).error('Authentication required', 'AUTH_REQUIRED');
}
if (req.headers['x-user-role'] !== 'admin') {
return res.status(403).error('Admin access required', 'FORBIDDEN');
}
res.success({ secret: 'Protected data' });
});
app.post('/simple/create', async (req, res) => {
const newUser = {
id: nextId++,
name: 'New User',
email: 'new@example.com',
role: 'user' as const,
};
users.push(newUser);
// Success with message using res.success()
res.status(201).success(newUser, 'User created successfully');
});
// ===== Example 14: res.noContent() - Automatic 204 (No Response Body) =====
app
.delete('/users/:id/avatar')
.params(z.object({ id: z.coerce.number() }))
.handler(async (req, res) => {
const userId = req.params.id as unknown as number;
const user = users.find(u => u.id === userId);
if (!user) {
return res.notFound('User');
}
// Simulate avatar deletion
// No response body needed for delete operations
res.noContent();
});
// ===== Example 15: res.paginated() - Automatic Pagination Metadata =====
app
.get('/users/paginated')
.query(
z.object({
page: z.coerce.number().min(1).default(1),
limit: z.coerce.number().min(1).max(100).default(10),
})
)
.handler(async (req, res) => {
const page = req.query.page as unknown as number;
const limit = req.query.limit as unknown as number;
// Calculate pagination
const start = (page - 1) * limit;
const paginatedUsers = users.slice(start, start + limit);
// res.paginated() automatically adds pagination metadata
res.paginated(paginatedUsers, {
page,
limit,
total: users.length,
});
// Response includes: data, pagination: { page, limit, total, totalPages, hasNext, hasPrev }
});
// ===== Example 16: Type-Safe Responses with response helpers =====
async function getUserSafely(id: number): Promise<ApiSuccessResponse<User> | ApiErrorResponse> {
const user = users.find(u => u.id === id);
if (!user) {
return response.notFound('User');
}
return response.success(user);
}
app.get('/type-safe/users/:id', async (req, res) => {
const id = parseInt(req.params.id);
const result = await getUserSafely(id);
if (!result.success) {
return res.status(404).json(result);
}
// TypeScript knows result.data is User here
return result;
});
// ===== Start Server =====
const PORT = Number(process.env.PORT) || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log('\nExample endpoints demonstrating all response methods:');
console.log(' GET /users - res.success()');
console.log(' GET /users/:id - res.notFound()');
console.log(' POST /users - res.conflict(), res.created()');
console.log(' POST /users/create-admin - res.created() with Location header');
console.log(' PUT /users/:id - Full CRUD example');
console.log(' DELETE /users/:id - res.forbidden()');
console.log(' DELETE /users/:id/avatar - res.noContent()');
console.log(' GET /users/paginated?page=1&limit=10 - res.paginated()');
console.log(' GET /profile - res.unauthorized()');
console.log(' POST /upload - res.badRequest()');
console.log(' POST /users/manual-validation - res.validationError()');
console.log(' POST /api/send-email - res.rateLimited()');
console.log(' GET /unstable-endpoint - res.internalError()');
console.log('\nAll responses follow the standardized format!');
console.log('\nDirect res.* methods automatically set status codes:');
console.log(' res.success(data) - 200, res.created(data, location) - 201');
console.log(' res.noContent() - 204, res.paginated(data, pagination) - 200');
console.log(' res.badRequest() - 400, res.unauthorized() - 401');
console.log(' res.forbidden() - 403, res.notFound() - 404');
console.log(' res.conflict() - 409, res.validationError() - 422');
console.log(' res.rateLimited() - 429, res.internalError() - 500');
});