-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
65 lines (47 loc) · 1.49 KB
/
app.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
var express = require('express'),
app = express(),
pkg = require('./package.json'),
bodyParser = require('body-parser'),
morgan = require('morgan'),
users = require('./lib/users')(getDB);
module.exports = app;
app.use(morgan('dev'));
app.use(bodyParser.json());
function getDB() {
return app.get('db');
}
app.get('/', function(req, res) {
res.json({ name: pkg.name, version: pkg.version });
});
app.get('/users', function(req, res) {
users.getUsers(function(err, result) {
if (err) {
// just an example (we don't actually throw any errors in getUsers)
return res.status(500).json( { success: false, reason: err.message });
}
res.send({ success: true, users: result });
});
});
app.get('/users/:id', function(req, res) {
var id = req.params.id;
users.getUser(id, function(err, result) {
if (err) {
// just an example (bad request)
return res.status(400).json( { success: false, reason: err.message });
}
if (!result) {
return res.status(404).json( { success: false, reason: 'user id not found' });
}
res.send({ success: true, user: result });
});
});
app.post('/users', function(req, res) {
var user = req.body;
users.addUser(user, function(err, result) {
if (err) {
// just an example (bad request) since the only error that we throw is if missing user name
return res.status(400).json( { success: false, reason: err.message });
}
res.send({ success: true, user: result });
});
});