-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
71 lines (63 loc) · 1.83 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
65
66
67
68
69
70
71
"use strict"; // so we can use const, let, etc.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connect to mongodb server
let db;
const url = 'mongodb://localhost:27017/betternote';
MongoClient.connect(url, function(err, database) {
if (err) {
console.log(err);
throw new Error("Unable to connect to database server.");
}
console.log("Connected correctly to database server.");
db = database;
app.listen(3001, function () {
console.log('API server listening on port 3001.');
});
});
app.use(bodyParser.json());
app.use(function(err, req, res, next) {
if (err) {
// TODO: determine if this error was the result of bad
// JSON sent to the server
console.log(err);
res.status(500).send({
error: "A server error occurred."
});
} else {
next();
}
});
app.get('/api/test-logs', function (req, res) {
const collection = db.collection("test-logs");
collection.find({}).toArray(function (err, logs) {
if (err) {
console.log(err);
res.status(500).send({
error: "Unable to access database of test logs."
});
} else {
console.log("Found " + logs.length + " test logs.");
res.status(200).send(logs);
}
});
});
app.post('/api/test-logs', function (req, res) {
const collection = db.collection("test-logs");
console.log("POST request:")
console.log(req.body);
collection.insertOne(req.body, function (err, result) {
if (err) {
console.log(err);
res.status(500).send({
error: "Unable to insert test log into database."
});
} else {
console.log("Successfully saved new test log.");
res.status(201).end("Test log successfully saved in database.");
}
});
});