This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
102 lines (83 loc) · 2.45 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
require('dotenv').config();
const express = require("express");
const cors = require('cors');
const server = express();
server.use(cors());
const body_parser = require("body-parser");
const ObjectId = require("mongodb").ObjectId;
// config
server.use(body_parser.json());
const port = process.env.PORT;
// db setup
const db = require("./db");
const dbName = "performance";
const collectionName = "loadtimes";
// db init
db.initialize(
dbName,
collectionName,
function (dbCollection) {
// POST
server.post("/time", (request, response) => {
let item = request.body;
const toDate = new Date();
const datetime = toDate;
const timestamp = toDate.getTime();
item.datetime = datetime;
item.time = timestamp;
dbCollection.insertOne(item, (error, result) => {
if (error) throw error;
dbCollection.find().toArray((_error, _result) => {
if (_error) throw _error;
response.json(_result);
});
});
});
// GET ALL
server.post("/loadtimes", (request, response) => {
const bodyData = request.body;
const bodyDataSize = Object.keys(bodyData).length;
if(bodyDataSize === 0){
dbCollection.find().toArray((_error, _result) => {
if (_error) throw _error;
response.json(_result);
});
} else if(bodyDataSize > 0){
dbCollection.find({time : {$gte: new Date().getTime()-(bodyData.timeInterval*60*1000) } } ).toArray((_error, _result) => {
if (_error) throw _error;
response.json(_result);
});
}
});
// GET BY ID
server.get("/loadtimes/:id", (request, response) => {
const itemId = request.params.id;
dbCollection.findOne({ _id: ObjectId(itemId) }, (error, result) => {
if (error) throw error;
response.json(result);
});
});
// DELETE BY ID
server.delete("/loadtimes/:id", (request, response) => {
const itemId = request.params.id;
dbCollection.deleteOne({ id: itemId }, function (error, result) {
if (error) throw error;
dbCollection.find().toArray(function (_error, _result) {
if (_error) throw _error;
response.json(_result);
});
});
});
},
function (err) {
throw err;
}
);
// Static Files
server.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// Listen
server.listen(port, () => {
console.log(`Server listening at ${port}`);
});