-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
96 lines (74 loc) · 2.28 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
var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs');
var jsonfilepath = path.join(__dirname, 'public', 'data.json');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
app.use(express.static("./"));
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next){
console.log(`${req.method} for ${req.url}`);
next();
});
app.get('/api', function(req, res){
fs.readFile("./src/data.json", function(err, data){
var parseddata = JSON.parse(data);
var queryString = req.query.scroll;
var data= filter_json(parseddata, queryString);
if(data){
res.send(data)}
else{
res.status(500).send('No such scroll exists!');
};
});
myEmitter.emit('connect');
});
app.post('/api', updateMissions);
function updateMissions(req, res){
console.log(req.body);
fs.readFile("./src/data.json", function(err, data){
var currentData = JSON.parse(data);
var DupData = filter_json(currentData, req.body.scroll);
if(DupData.length>0 && req.body.overwrite===false){
res.status(500).send('There is already a scroll by that name! Overwrite?');
res.end();
}
else{
if(req.body.overwrite===false){
console.log("newitem");
delete req.body.overwrite;
console.log(req.body);
currentData.push(req.body);
console.log("newData" + currentData);}
else if(req.body.overwrite===true){
currentData= neg_filter_json(currentData, req.body.scroll);
delete req.body.overwrite;
currentData.push(req.body);
}
fs.writeFile("./public/data.json", JSON.stringify(currentData, null, 2), 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
res.json("success");
});
}
});
};
myEmitter.on('connect', function(){console.log('API call made')});
app.listen(port);
function filter_json(jsonObj, scrollName){
return jsonObj.filter(function(obj){
return obj.scroll===scrollName;
})
}
function neg_filter_json(jsonObj, scrollName){
return jsonObj.filter(function(obj){
return obj.scroll!==scrollName;
})
}