-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvanced.tsx
More file actions
351 lines (292 loc) · 9.01 KB
/
advanced.tsx
File metadata and controls
351 lines (292 loc) · 9.01 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
import React from 'react';
import {
createServer,
Server,
Route,
Get,
Post,
Put,
Delete,
Middleware,
} from 'react-http';
import type { RequestContext, MiddlewareHandler } from 'react-http';
// =============================================================================
// MIDDLEWARES
// =============================================================================
const logger: MiddlewareHandler = async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.path} - ${ctx.res.statusCode} - ${ms}ms`);
};
const cors: MiddlewareHandler = async (ctx, next) => {
ctx.res.setHeader('Access-Control-Allow-Origin', '*');
ctx.res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
ctx.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (ctx.method === 'OPTIONS') {
ctx.res.statusCode = 204;
ctx.res.end();
return;
}
await next();
};
const authRequired: MiddlewareHandler = async (ctx, next) => {
const authHeader = ctx.req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
ctx.res.statusCode = 401;
ctx.res.setHeader('Content-Type', 'application/json');
ctx.res.end(JSON.stringify({ error: 'Unauthorized', message: 'Bearer token required' }));
return;
}
// Simulate token validation
const token = authHeader.slice(7);
if (token !== 'secret-token') {
ctx.res.statusCode = 403;
ctx.res.setHeader('Content-Type', 'application/json');
ctx.res.end(JSON.stringify({ error: 'Forbidden', message: 'Invalid token' }));
return;
}
await next();
};
// =============================================================================
// IN-MEMORY DATABASE
// =============================================================================
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user';
}
interface Post {
id: number;
userId: number;
title: string;
content: string;
createdAt: string;
}
const db = {
users: [
{ id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin' as const },
{ id: 2, name: 'Bob', email: 'bob@example.com', role: 'user' as const },
{ id: 3, name: 'Charlie', email: 'charlie@example.com', role: 'user' as const },
],
posts: [
{ id: 1, userId: 1, title: 'Hello World', content: 'My first post', createdAt: '2024-01-01' },
{ id: 2, userId: 1, title: 'React HTTP', content: 'Building servers with JSX', createdAt: '2024-01-02' },
{ id: 3, userId: 2, title: 'Node.js Tips', content: 'Some useful tips', createdAt: '2024-01-03' },
],
nextUserId: 4,
nextPostId: 4,
};
// =============================================================================
// HANDLERS
// =============================================================================
// Users handlers
function listUsers(ctx: RequestContext) {
const { role, search } = ctx.query;
let users = db.users;
if (role) {
users = users.filter(u => u.role === role);
}
if (search) {
users = users.filter(u =>
u.name.toLowerCase().includes(search.toLowerCase()) ||
u.email.toLowerCase().includes(search.toLowerCase())
);
}
return { users, count: users.length };
}
function getUser(ctx: RequestContext) {
const id = parseInt(ctx.params.id);
const user = db.users.find(u => u.id === id);
if (!user) {
ctx.res.statusCode = 404;
return { error: 'User not found' };
}
return user;
}
function createUser(ctx: RequestContext) {
const { name, email, role = 'user' } = ctx.body || {};
if (!name || !email) {
ctx.res.statusCode = 400;
return { error: 'Name and email are required' };
}
const user: User = {
id: db.nextUserId++,
name,
email,
role,
};
db.users.push(user);
ctx.res.statusCode = 201;
return user;
}
function updateUser(ctx: RequestContext) {
const id = parseInt(ctx.params.id);
const user = db.users.find(u => u.id === id);
if (!user) {
ctx.res.statusCode = 404;
return { error: 'User not found' };
}
const { name, email, role } = ctx.body || {};
if (name) user.name = name;
if (email) user.email = email;
if (role) user.role = role;
return user;
}
function deleteUser(ctx: RequestContext) {
const id = parseInt(ctx.params.id);
const index = db.users.findIndex(u => u.id === id);
if (index === -1) {
ctx.res.statusCode = 404;
return { error: 'User not found' };
}
db.users.splice(index, 1);
ctx.res.statusCode = 204;
return undefined;
}
// Posts handlers
function listPosts(ctx: RequestContext) {
const { userId } = ctx.query;
let posts = db.posts;
if (userId) {
posts = posts.filter(p => p.userId === parseInt(userId));
}
return { posts, count: posts.length };
}
function getUserPosts(ctx: RequestContext) {
const userId = parseInt(ctx.params.id);
const posts = db.posts.filter(p => p.userId === userId);
return { posts, count: posts.length };
}
function getPost(ctx: RequestContext) {
const id = parseInt(ctx.params.postId);
const post = db.posts.find(p => p.id === id);
if (!post) {
ctx.res.statusCode = 404;
return { error: 'Post not found' };
}
// Include author info
const author = db.users.find(u => u.id === post.userId);
return { ...post, author };
}
function createPost(ctx: RequestContext) {
const { userId, title, content } = ctx.body || {};
if (!userId || !title || !content) {
ctx.res.statusCode = 400;
return { error: 'userId, title and content are required' };
}
const post: Post = {
id: db.nextPostId++,
userId,
title,
content,
createdAt: new Date().toISOString().split('T')[0],
};
db.posts.push(post);
ctx.res.statusCode = 201;
return post;
}
// Health & info
function healthCheck() {
return { status: 'ok', timestamp: new Date().toISOString() };
}
function serverInfo() {
return {
name: 'react-http-advanced-example',
version: '1.0.0',
endpoints: [
'GET /health',
'GET /api/users',
'POST /api/users',
'GET /api/users/:id',
'PUT /api/users/:id',
'DELETE /api/users/:id',
'GET /api/users/:id/posts',
'GET /api/posts',
'POST /api/posts',
'GET /api/posts/:postId',
'GET /admin/stats (requires auth)',
],
};
}
// Admin handlers (protected)
function getStats() {
return {
users: db.users.length,
posts: db.posts.length,
usersByRole: {
admin: db.users.filter(u => u.role === 'admin').length,
user: db.users.filter(u => u.role === 'user').length,
},
};
}
// =============================================================================
// APP COMPONENT
// =============================================================================
function App() {
return (
<Server port={3000}>
{/* Global middlewares */}
<Middleware use={logger} />
<Middleware use={cors} />
{/* Public endpoints */}
<Route path="/health">
<Get handler={healthCheck} />
</Route>
<Route path="/info">
<Get handler={serverInfo} />
</Route>
{/* API routes */}
<Route path="/api">
{/* Users CRUD */}
<Route path="/users">
<Get handler={listUsers} />
<Post handler={createUser} />
<Route path="/:id">
<Get handler={getUser} />
<Put handler={updateUser} />
<Delete handler={deleteUser} />
<Route path="/posts">
<Get handler={getUserPosts} />
</Route>
</Route>
</Route>
{/* Posts */}
<Route path="/posts">
<Get handler={listPosts} />
<Post handler={createPost} />
<Route path="/:postId">
<Get handler={getPost} />
</Route>
</Route>
</Route>
{/* Protected admin routes */}
<Route path="/admin">
<Middleware use={authRequired} />
<Route path="/stats">
<Get handler={getStats} />
</Route>
</Route>
</Server>
);
}
// =============================================================================
// START SERVER
// =============================================================================
const server = createServer(<App />);
server.listen().then(() => {
console.log('\nReact HTTP Advanced Example');
console.log('============================\n');
console.log('Try these commands:\n');
console.log(' curl http://localhost:3000/info');
console.log(' curl http://localhost:3000/api/users');
console.log(' curl "http://localhost:3000/api/users?role=admin"');
console.log(' curl http://localhost:3000/api/users/1');
console.log(' curl http://localhost:3000/api/users/1/posts');
console.log(' curl http://localhost:3000/api/posts');
console.log(' curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d \'{"name":"Dave","email":"dave@example.com"}\'');
console.log(' curl http://localhost:3000/admin/stats # Will return 401');
console.log(' curl http://localhost:3000/admin/stats -H "Authorization: Bearer secret-token"');
console.log('');
});