-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
60 lines (42 loc) · 1.21 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
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
// other comment.
// test comment.
function log(logTxt) {
console.log(logTxt);
}
const app = express();
const url = '/users';
const users = require('./users.json');
app.use(bodyParser.json());
app.get(url, function (req, res) {
log('Get All Request');
res.status(200).json(users);
});
app.get(url + '/:id', function (req, res) {
// First read existing users.
const userId = parseInt(req.params.id);
log('Get User Request for id ' + userId);
const foundUser = users.find(function(user) {
return user.id === userId;
});
if (!foundUser) {
res.status(404).end();
return;
}
res.status(200).json(foundUser);
});
app.post(url, function (req, res) {
var newUser = req.body;
newUser.id = users.length;
users.push(newUser);
log('User added ' + newUser + ' with id: ' + newUser.id);
res.status(201).json(newUser);
});
const PORT = process.env.PORT || 8088;
var server = app.listen(PORT, function () {
const host = server.address().address;
const port = server.address().port;
log('Example app listening at http://' + host + ':' + port);
});