-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
168 lines (149 loc) · 5.54 KB
/
Copy pathserver.js
File metadata and controls
168 lines (149 loc) · 5.54 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
const http = require('http');
const url = require('url');
function fetchUserData(userId, callback) {
const apiUrl = `http://jsonplaceholder.typicode.com/users/${userId}`;
http.get(apiUrl, (response) => {
let data = '';
response.on('data', chunk => data += chunk);
response.on('end', () => {
try {
const userData = JSON.parse(data);
const formattedData = {
id: userData.id,
name: userData.name,
username: userData.username,
email: userData.email,
city: userData.address?.city,
company: userData.company?.name
};
callback(null, formattedData);
} catch (error) {
callback(error, null);
}
});
}).on('error', error => callback(error, null));
}
function fetchPostData(postId, callback) {
const apiUrl = `http://jsonplaceholder.typicode.com/posts/${postId}`;
http.get(apiUrl, (response) => {
let data = '';
response.on('data', chunk => data += chunk);
response.on('end', () => {
try {
const postData = JSON.parse(data);
const formattedData = {
id: postData.id,
userId: postData.userId,
title: postData.title,
body: postData.body
};
callback(null, formattedData);
} catch (error) {
callback(error, null);
}
});
}).on('error', error => callback(error, null));
}
function fetchTodoData(todoId, callback) {
const apiUrl = `http://jsonplaceholder.typicode.com/todos/${todoId}`;
http.get(apiUrl, (response) => {
let data = '';
response.on('data', chunk => data += chunk);
response.on('end', () => {
try {
const todoData = JSON.parse(data);
const formattedData = {
id: todoData.id,
userId: todoData.userId,
title: todoData.title,
completed: todoData.completed
};
callback(null, formattedData);
} catch (error) {
callback(error, null);
}
});
}).on('error', error => callback(error, null));
}
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const query = parsedUrl.query;
if (pathname === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<h1>Welcome to My Simple REST API</h1>
<p>Available endpoints:</p>
<ul>
<li>GET /users?id=1</li>
<li>GET /posts?id=1</li>
<li>GET /todos?id=1</li>
</ul>
`);
}
else if (pathname === '/users' && req.method === 'GET') {
const id = query.id;
if (!id) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing user id' }));
return;
}
fetchUserData(id, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to fetch user data' }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
});
}
else if (pathname === '/posts' && req.method === 'GET') {
const id = query.id;
if (!id) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing post id' }));
return;
}
fetchPostData(id, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to fetch post data' }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
});
}
else if (pathname === '/todos' && req.method === 'GET') {
const id = query.id;
if (!id) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing todo id' }));
return;
}
fetchTodoData(id, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to fetch todo data' }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
});
}
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Route not found',
availableEndpoints: [
'/users?id={userId}',
'/posts?id={postId}',
'/todos?id={todoId}'
]
}));
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});