-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodeJS_server.js
61 lines (51 loc) · 1.7 KB
/
nodeJS_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
const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const urlMongo = 'mongodb://localhost:27017/bigchain'
var express = require('express');
var app = express();
var str = "";
console.log("Server running")
var queryMongo = function(querySortByCount, callback) {
MongoClient.connect(urlMongo, querySortByCount, function(err, db) {
if (err) throw err;
console.log("Connected successfully to server")
executeAggregateQuery(querySortByCount, db, function(err, data) {
callback(err, data);
db.close();
});
})
}
var executeAggregateQuery = function(querySortByCount, db, callback) {
const client = db.db();
const collection = client.collection('assets');
collection.aggregate([querySortByCount]).toArray(function(err, docs) {
callback(err, docs);
});
};
//CORS middleware
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//routes
app.get('/', function(req, res, next) {
console.log("Someone connected.")
var querySortByCount = req.query.querySortByCount;
console.log(req.query.querySortByCount);
console.log(querySortByCount);
switch(querySortByCount){
case 'queryVote':
querySortByCount = {$sortByCount:"$data.Vote"};
break;
//to be completed with District vote percentage
}
console.log(JSON.stringify(querySortByCount));
queryMongo(querySortByCount, function(err, data) {
if(err)
res.status(500).json({error: err});
else
res.json(data);
})
})
var server = app.listen(3000, function() {});