-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
244 lines (219 loc) · 9.71 KB
/
server.js
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
const http = require('http');
const url = require('url');
const fs = require('fs');
const Post = require('./model');
const Service = require('./service');
const hostname = 'localhost';
const port = 3002;
const service = new Service('posts.json');
const server = http.createServer((req, res) => {
let pathname = url.parse(req.url).pathname;
console.log(`Path: ${pathname}`);
console.log(`Method: ${req.method}`);
console.log(`Headers: ${JSON.stringify(req.headers)}`);
if (req.method === 'GET') {
let resource = pathname.substr(1);
let path = resource.split('/');
console.log(`PATH: ${path}`);
if (path.length > 1 && path[0] === 'api' || path[0] === 'posts') {
if (typeof path[1] === 'undefined' || path[1] === 'posts') {
if (typeof path[2] === 'undefined') {
service.findAll((err, posts) => {
if (err) {
// 500: File not found
console.error(`Error reading file: ${err.message}`);
res.writeHead(500, { 'Content-Type': 'text/html' }); //TODO set appropriate MIME type
res.end(`
<html>
<body>
<p>Sorry DB file not found</p>
</body>
</html>
`);
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(posts));
}
});
} else {
const postId = path[2];
service.findPost(postId, (err, post) => {
if (err) {
// 500: File not found
console.error(`Error reading file: ${err.message}`);
res.writeHead(500, { 'Content-Type': 'text/html' }); //TODO set appropriate MIME type
res.end(`
<html>
<body>
<p>Sorry DB file not found</p>
</body>
</html>
`);
} else {
console.log(post);
if (post) {
res.writeHead(200, { 'Content-Type': 'application/json' });
console.log(`Post found: ${JSON.stringify(post)}`);
res.end(JSON.stringify(post));
} else {
console.error(`Error fidning post: ${postId}`);
res.writeHead(404, { 'Content-Type': 'text/plain' }); //TODO set appropriate MIME type
res.end(`Post with id=${postId} not found.`);
}
}
});
}
}
} else {
if (resource === '') {
resource = 'index.html';
}
resource = process.cwd() + '/dist/' + resource;
fs.readFile(resource, (err, data) => {
if (err) {
// 404: File not found
console.error(`Error reading file: ${err.message}`, resource);
res.writeHead(404, { 'Content-Type': 'text/plani' }); //TODO set appropriate MIME type
res.end(`File '${resource}' not found.`);
} else {
// 200: OK
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data.toString());
}
res.end();
});
}
} else if (req.method === 'POST') {
let headers = req.headers;
let method = req.method;
let rUrl = req.url;
let body = [];
let resource = pathname.substr(1);
let path = resource.split('/');
if (path.length > 1 && path[0] === 'api') {
if (path[1] === 'posts') {
//Handle req events: data, end, error
req.on('error', function (err) {
console.error(err);
}).on('data', function (chunk) {
body.push(chunk);
}).on('end', function () {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire req body stored in it as a string
console.log('Body:', body);
const newPost = JSON.parse(body);
console.log('After parse:', newPost);
res.on('error', function (err) {
console.error(err);
});
service.add(newPost, (err, posts, newPost) => {
if (err) {
console.log(`${err.error.name}: ${err.error.message}`);
res.writeHead(err.code, { 'Content-Type': 'text/plain' });
res.end(`${err.error.name}: ${err.error.message}`);
} else {
res.writeHead(201, { 'Content-Type': 'application/json', 'Location': `http://localhost:${port}/posts/${newPost.id}` });
res.end(JSON.stringify(newPost));
}
});
});
}
}
} else if (req.method === 'DELETE') {
let headers = req.headers;
let method = req.method;
let rUrl = req.url;
let body = [];
let resource = pathname.substr(1);
let path = resource.split('/');
if (path.length === 3 && path[0] === 'api' && path[1] === 'posts') {
const postId = path[path.length - 1];
res.on('error', function (err) {
console.error(err);
});
// delete post by id
service.delete(postId, (err, posts, deleted) => {
if (err) {
console.log(`${err.error.name}: ${err.error.message}`);
res.writeHead(err.code, { 'Content-Type': 'text/plain' });
res.end(`${err.error.name}: ${err.error.message}`);
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(posts));
}
});
}
} else if (req.method === 'PUT') {
let headers = req.headers;
let method = req.method;
let rUrl = req.url;
let body = [];
let resource = pathname.substr(1);
let path = resource.split('/');
if (path.length === 3 && path[0] === 'api' && path[1] === 'posts') {
const postId = path[path.length - 1];
console.log('PostId to be updated:', postId);
req.on('error', function (err) {
console.error(err);
}).on('data', function (chunk) {
body.push(chunk);
}).on('end', function () {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire req body stored in it as a string
console.log('Body:', body);
const updatePost = JSON.parse(body);
console.log('After parse:', updatePost);
res.on('error', function (err) {
console.error(err);
});
// update post by id
service.update(updatePost, (err, posts, updated) => {
if (err) {
console.log(`${err.error.name}: ${err.error.message}`);
res.writeHead(err.code, { 'Content-Type': 'text/plain' });
res.end(`${err.error.name}: ${err.error.message}`);
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
console.log(`updated`);
res.end(JSON.stringify(updated));
}
});
});
}
} else {
//Handle req events: data, end, error
req.on('error', function (err) {
console.error(err);
}).on('data', function (chunk) {
body.push(chunk);
}).on('end', function () {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire req body stored in it as a string
console.log(body);
//Start emiting res
//Handle res errors
res.on('error', function (err) {
console.error(err);
});
// Retun res - 201 : Created
// res.statusCode = 200;
// res.setHeader('Content-Type', 'application/json');
res.writeHead(201, {
'content-type': 'application/json',
'location': `http://localhost:${port}/echo`
});
var resBody = {
headers: headers,
method: method,
url: rUrl,
body: body
};
res.end(JSON.stringify(resBody));
res.end();
});
}
});
server.listen(port, hostname, (err) => {
if (err) console.error(err);
console.log(`Server running at http://${hostname}:${port}/`);
});