-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.js
175 lines (137 loc) · 4.65 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
const path = require('path');
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const app = express();
app.use(express.json());
/// YOUR ROUTES GO HERE!
/////////////////////////////////////////////
// Totally insecure backend routes below, good only for rapid prototyping
// unsecured front-end applications. Should not be used in production.
// GET for getting existing item
app.get('/api/mongodb/:collectionName/', (request, response) => {
const collectionName = request.params.collectionName;
// Get GET params, if there are any
const query = request.query || {};
// Due to a requirement of MongoDB, whenever we query based on _id field, we
// have to do it like this using ObjectId
if (query._id) {
query._id = ObjectId(query._id);
}
db.collection(collectionName)
.find(query)
.toArray((err, results) => {
// Got data back.. send to client
if (err) throw err;
response.json(results);
});
});
// POST for creating a new item
app.post('/api/mongodb/:collectionName/', (request, response) => {
const collectionName = request.params.collectionName;
const data = request.body;
db.collection(collectionName)
.insert(data, (err, results) => {
// Got data back.. send to client
if (err) throw err;
response.json({
'success': true,
'results': results,
});
});
});
// PUT endpoint for modifying an existing item
app.put('/api/mongodb/:collectionName/', (request, response) => {
const collectionName = request.params.collectionName;
const data = request.body;
const query = request.query;
// Due to a requirement of MongoDB, whenever we query based on _id field, we
// have to do it like this using ObjectId
if (query._id) {
query._id = ObjectId(query._id);
}
// MongoDB disallows _id fields from being updated, delete if it exists
delete data._id;
db.collection(collectionName)
.updateOne(query, {$set: data}, (err, results) => {
if (err) throw err;
// If we modified exactly 1, then success, otherwise failure
if (results.result.nModified === 1) {
response.json({
success: true,
});
} else {
response.json({
success: false,
});
}
});
});
// D in CRUD, delete a single item with given criteria
app.delete('/api/mongodb/:collectionName/', (request, response) => {
const collectionName = request.params.collectionName;
const query = request.query;
// Due to a requirement of MongoDB, whenever we query based on _id field, we
// have to do it like this using ObjectId
if (query._id) {
query._id = ObjectId(query._id);
}
db.collection(collectionName)
.deleteOne(query, (err, results) => {
if (err) throw err;
// If we deleted exactly 1, then success, otherwise failure
if (results.result.n === 1) {
response.json({
success: true,
});
} else {
response.json({
success: false,
});
}
})
});
/////////////////////////////////////////////
// Boilerplate, no need to touch what's below
/////////////////////////////////////////////
// Logger & configuration
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
app.use(logger);
/////////////////////////////////////////////
// For production, handle any requests that don't match the ones above
app.use(express.static(path.join(__dirname, 'client/build')));
// Wild-card, so handle everything else
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build/index.html'));
});
// Set up configuration variables
if (!process.env.MONGODB_URI) {
console.log('- Error - Must specify the following env variables:');
console.log("MONGODB_URI='mongodb://someUser:[email protected]:1234/someDB'");
console.log('- (See README.md)');
process.exit(1);
}
const MONGODB_URL = process.env.MONGODB_URI;
const splitUrl = MONGODB_URL.split('/');
const mongoDbDatabaseName = splitUrl[splitUrl.length - 1];
let db;
// First connect to MongoDB, then start HTTP server
MongoClient.connect(MONGODB_URL, {useNewUrlParser: true}, (err, client) => {
if (err) throw err;
console.log("--MongoDB connection successful");
db = client.db(mongoDbDatabaseName);
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`
*********************************************
* Insecure prototyping backend is running! *
* Only use for prototyping *
* Backend server up at ${PORT} *
*********************************************
`);
})
});