-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
74 lines (64 loc) · 1.98 KB
/
server.js
File metadata and controls
74 lines (64 loc) · 1.98 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
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 8000;
const mongoHost = process.env.MONGO_HOST;
const mongoPort = process.env.MONGO_PORT || '27017';
const mongoDBName = process.env.MONGO_DATABASE;
const mongoUser = process.env.MONGO_USER;
const mongoPassword = process.env.MONGO_PASSWORD;
const mongoReplSetName = process.env.MONGO_REPL_SET_NAME;
const mongoReplSetOption = mongoReplSetName ? `?replicaSet=${mongoReplSetName}` : "";
const mongoURL = `mongodb://${mongoUser}:${mongoPassword}@${mongoHost}:${mongoPort}/${mongoDBName}${mongoReplSetOption}`;
let mongoDB = null;
app.use(bodyParser.json());
function getAllCats() {
return mongoDB.collection('cats').find({}).toArray();
}
app.get('/cats', function (req, res) {
getAllCats()
.then((cats) => {
res.status(200).json({ cats: cats });
})
.catch((err) => {
res.status(500).json({ error: "Error fetching cats" });
});
});
function insertNewCat(cat) {
const catDocument = { url: cat.url };
return mongoDB.collection('cats').insertOne(catDocument)
.then((result) => {
return Promise.resolve(result.insertedId);
});
}
app.post('/cats', function (req, res) {
if (req.body && req.body.url) {
insertNewCat(req.body)
.then((id) => {
res.status(201).json({ _id: id });
})
.catch((err) => {
res.status(500).json({ error: "Failed to insert new cat." });
});
} else {
res.status(400).json({
error: "Request doesn't contain a valid cat."
});
}
});
app.use('*', function (req, res, next) {
res.status(404).json({
err: "Path " + req.originalUrl + " does not exist"
});
});
MongoClient.connect(mongoURL, function (err, client) {
if (!err) {
mongoDB = client.db(mongoDBName);
app.listen(port, function() {
console.log("== Server is running on port", port);
});
} else {
throw err;
}
});