-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
80 lines (65 loc) · 1.94 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
72
73
74
75
76
77
78
79
80
var request = require('request');
var mongoose = require('mongoose');
var express = require('express');
var app = express();
var Hospitals = require('./hospital.model');
var crontab = require('node-crontab');
var cors = require('cors');
var q = require('q');
app.use(cors());
mongoose.connect('mongodb://localhost/hospital');
var jobId = crontab.scheduleJob("55 * * * *", function(){
addToDatabase();
});
function addToDatabase() {
request('http://apis.is/hospital', function (error, response, body) {
if (!error && response.statusCode == 200) {
var hos = new Hospitals();
hos.hospitalData = JSON.parse(body);
hos.save(function(err) {
if (err) {
console.log(err);
}
});
}
});
}
function getCurrentData() {
var deferred = q.defer();
request('http://apis.is/hospital', function (error, response, body) {
if (!error && response.statusCode == 200) {
deferred.resolve(JSON.parse(body));
}
deferred.reject(error);
});
return deferred.promise;
}
app.get('/hospitals', function (req, res) {
Hospitals.find({}, function(err, response) {
if (err) {
return res.send(err);
}
return res.json(response);
})
});
app.get('/hospitals/:from/:to', function (req, res) {
var from = req.params.from;
var to = req.params.to;
Hospitals.find({ 'date': {"$gte": new Date(req.params.from), "$lt": new Date(req.params.to)}}, function(err, response) {
if (err) {
return res.send(err);
}
getCurrentData().then(function(data) {
var returnData = {
selectedData: response,
currentData: data
};
return res.json(returnData);
});
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});