-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
79 lines (46 loc) · 1.65 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
var mongoose = require('mongoose');
var timeseries = require("timeseries-analysis");
var http = require('http');
var express = require('express');//
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://localhost/bikes');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
var bikeSchema = mongoose.Schema({
timestamp: Date,
free: Number
})
var Bikes = mongoose.model('Bike', bikeSchema);
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
router.get('/Stations/:StationName', function(req, res) {
console.log("Station " + req.params.StationName + " was asked for")
Bikes.find({ name : req.params.StationName}, {'_id': 0, 'free': 1, 'timestamp': 1 }, function (err, Bikes) {
if (err) return console.error(err);
var t = new timeseries.main(timeseries.adapter.fromDB(Bikes, {
date: 'timestamp',
value: 'free'
}));
var chart_url = t.ma({period: 14}).chart({main:true});
res.setHeader( "Access-Control-Allow-Origin", req.headers.origin );
res.write(chart_url );
res.end();
})
});
router.get('/Stations/', function(req, res) {
Bikes
.find()
.distinct('name', function(error, names) {
res.setHeader( "Access-Control-Allow-Origin", req.headers.origin );
res.json(names);
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);