-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13.js
86 lines (74 loc) · 1.61 KB
/
13.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
/**
*Simple Express example for serving an API.
*/
var app = require('express')(),
bodyParser = require('body-parser'),
morgan = require('morgan'),
port = process.env.PORT || 3000,
MongoClient = require('mongodb').MongoClient,
mongoUrl = 'mongodb://localhost:27017/expressdemo',
_db;
app.use(morgan('dev'));
app.use(bodyParser.json());
MongoClient.connect(mongoUrl, function(err, db) {
if (err) {
console.error(err);
} else {
console.log('connected to mongo');
_db = db;
app.listen(port, function() {
console.log('listening for requests on localhost:%s', port);
});
}
});
app.get('/users', function(req, res) {
var collection = _db.collection('data');
collection.find({}).toArray(function(err, result) {
if (err) {
console.error(err);
res.status(500).end();
} else {
res.send({
success: true,
users: result
});
}
});
});
app.get('/users/:name', function(req, res) {
var name = req.params.name;
var collection = _db.collection('data');
collection.findOne({
name: name
}, function(err, user) {
if (err) {
console.error(err);
res.status(500).end();
} else {
var result = user ? {
success: true,
user: user
} : {
success: false,
reason: 'user not found: ' + name
};
res.send(result);
}
});
});
app.post('/users', function(req, res) {
var user = req.body;
var collection = _db.collection('data');
// validate user, make sure doesn't already exist, etc.
collection.insert(user, function(err, users) {
if (err) {
console.error(err);
res.status(500).end();
} else {
res.send({
success: true,
user: user
});
}
});
});