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
|
const http = require('node:http');
class Router {
constructor() {
this.routes = [];
this.middlewares = [];
}
/**
* パスパターンを正規表現に変換する
*/
pathToRegex(pattern) {
const paramNames = [];
const regexPattern = pattern
.replace(/\*([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, name) => {
paramNames.push(name);
return '(.*)';
})
.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, name) => {
paramNames.push(name);
return '([^/]+)';
});
return {
regex: new RegExp(`^${regexPattern}$`),
paramNames
};
}
/**
* ミドルウェアを追加する
*/
use(middleware) {
this.middlewares.push(middleware);
}
/**
* ルートを追加する
*/
addRoute(method, pattern, handler) {
const { regex, paramNames } = this.pathToRegex(pattern);
this.routes.push({
method: method.toUpperCase(),
pattern,
regex,
paramNames,
handler
});
return this;
}
get(pattern, handler) { return this.addRoute('GET', pattern, handler); }
post(pattern, handler) { return this.addRoute('POST', pattern, handler); }
put(pattern, handler) { return this.addRoute('PUT', pattern, handler); }
patch(pattern, handler) { return this.addRoute('PATCH', pattern, handler); }
delete(pattern, handler) { return this.addRoute('DELETE', pattern, handler); }
/**
* ルートを検索する
*/
findRoute(method, pathname) {
for (const route of this.routes) {
if (route.method !== method) continue;
const match = pathname.match(route.regex);
if (match) {
const params = {};
route.paramNames.forEach((name, index) => {
params[name] = decodeURIComponent(match[index + 1]);
});
return { route, params };
}
}
return null;
}
/**
* ミドルウェアチェーンを実行する
*/
async runMiddlewares(req, res, context) {
for (const middleware of this.middlewares) {
let nextCalled = false;
await middleware(req, res, context, () => {
nextCalled = true;
});
if (!nextCalled) return false;
}
return true;
}
/**
* リクエストハンドラーを返す
*/
handler() {
return async (req, res) => {
try {
const baseUrl = `http://${req.headers.host}`;
const url = new URL(req.url, baseUrl);
const context = {
url,
params: {},
query: url.searchParams,
queryObject: Object.fromEntries(url.searchParams)
};
// ミドルウェアを実行
const shouldContinue = await this.runMiddlewares(req, res, context);
if (!shouldContinue) return;
// ルートを検索
const result = this.findRoute(req.method, url.pathname);
if (result) {
context.params = result.params;
await result.route.handler(req, res, context);
} else {
this.sendNotFound(res, url.pathname);
}
} catch (error) {
this.sendError(res, error);
}
};
}
sendNotFound(res, path) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Not Found',
message: `パス ${path} は見つかりませんでした`
}));
}
sendError(res, error) {
console.error('Server Error:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Internal Server Error',
message: process.env.NODE_ENV === 'development' ? error.message : 'サーバーエラーが発生しました'
}));
}
}
// JSONボディパーサーミドルウェア
function jsonBodyParser() {
return (req, res, context, next) => {
return new Promise((resolve) => {
if (req.method === 'GET' || req.method === 'DELETE') {
next();
resolve();
return;
}
const contentType = req.headers['content-type'] || '';
if (!contentType.includes('application/json')) {
next();
resolve();
return;
}
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
context.body = body ? JSON.parse(body) : {};
} catch {
context.body = {};
}
next();
resolve();
});
});
};
}
// ロギングミドルウェア
function requestLogger() {
return (req, res, context, next) => {
const start = Date.now();
console.log(`→ ${req.method} ${context.url.pathname}`);
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`← ${req.method} ${context.url.pathname} ${res.statusCode} (${duration}ms)`);
});
next();
};
}
// ===== 使用例 =====
const router = new Router();
// ミドルウェアを登録
router.use(requestLogger());
router.use(jsonBodyParser());
// ユーザーAPI
router.get('/api/users', (req, res, { queryObject }) => {
const { page = 1, limit = 10 } = queryObject;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
],
pagination: {
page: Number(page),
limit: Number(limit),
total: 100
}
}));
});
router.get('/api/users/:id', (req, res, { params }) => {
const userId = params.id;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
id: userId,
name: `User ${userId}`,
email: `user${userId}@example.com`
}));
});
router.post('/api/users', (req, res, { body }) => {
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
id: Date.now(),
...body,
createdAt: new Date().toISOString()
}));
});
router.put('/api/users/:id', (req, res, { params, body }) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
id: params.id,
...body,
updatedAt: new Date().toISOString()
}));
});
router.delete('/api/users/:id', (req, res) => {
res.writeHead(204);
res.end();
});
// ネストされたリソース
router.get('/api/users/:userId/posts', (req, res, { params, queryObject }) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
userId: params.userId,
posts: [
{ id: 1, title: '最初の投稿' },
{ id: 2, title: '2番目の投稿' }
],
query: queryObject
}));
});
router.get('/api/users/:userId/posts/:postId', (req, res, { params }) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
userId: params.userId,
postId: params.postId,
title: `投稿 ${params.postId}`,
content: 'これは投稿の内容です。'
}));
});
// ヘルスチェック
router.get('/health', (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', timestamp: new Date().toISOString() }));
});
const server = http.createServer(router.handler());
server.listen(3000, () => {
console.log('サーバーが http://localhost:3000 で起動しました');
console.log('利用可能なエンドポイント:');
console.log(' GET /api/users');
console.log(' GET /api/users/:id');
console.log(' POST /api/users');
console.log(' PUT /api/users/:id');
console.log(' DELETE /api/users/:id');
console.log(' GET /api/users/:userId/posts');
console.log(' GET /api/users/:userId/posts/:postId');
console.log(' GET /health');
});
|