-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
82 lines (70 loc) · 2.43 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
let express = require("express");
let app = express();
let fs = require("fs");
let promise = require("promise");
let allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
};
app.use(allowCrossDomain);
app.get('/api', (req, res) => {
let boardName = req.query.board;
let params = req.query.inputs.split(",");
let response = getDataHits(boardName, params);
res.setHeader('Content-Type', 'application/json');
res.json(response);
});
function isDuplicate(firstTimeData, link){
if(firstTimeData.has(link)){
return true;
}
firstTimeData.add(link);
return false;
}
function getDataHits(boardName, queries){
let contentHitsObject = {};
let firstTimeData = new Set();
let directoryLength = 0;
let files = fs.readdirSync("./boards/"+boardName);
files.forEach(fileName => {
let fileContent = fs.readFileSync(__dirname + "/boards/" + boardName + "/" + fileName, "utf-8");
dataObjs = JSON.parse(fileContent);
dataObjs.forEach(dataObj => {
let dataObjValue = Object.keys(dataObj).map((k) => dataObj[k]).toString().toLowerCase();
let hit = queries.every( query => dataObjValue.includes(query.toLowerCase()));
if(hit && !isDuplicate(firstTimeData, dataObj.link)){
let date = dataObj.date.split(" ");
let year = date[date.length - 1];
if(/^\d+$/.test(year)){
if(!(year in contentHitsObject)){
contentHitsObject[year] = [];
}
let contentHit = {};
contentHit.title = dataObj.title ? dataObj.title : "No title";
contentHit.link = dataObj.link;
contentHit.date = dataObj.date;
contentHitsObject[year].push(contentHit);
}
}
});
Object.keys(contentHitsObject).forEach((year) => {
contentHitsObject[year].sort((a,b)=>{
if(!a.date) a.date = -8640000000000000;
if(!b.date) b.date = -8640000000000000;
return new Date(b.date) - new Date(a.date);
});
});
});
return contentHitsObject;
}
let server = app.listen(process.env.PORT||5000, function(){
let port = server.address().port;
console.log("App running on port %s ",port);
});