-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
136 lines (102 loc) · 2.85 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
var express = require('express');
var app = express();
var request = require('request');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var morgan = require('morgan')
app.use(morgan('dev'));
app.use('/public', express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + "/public/index.html");
});
app.get('/api/stock', (req, res) => {
});
let currentStock = {tickers:[],data:[]};
io.on('connection', function (socket) {
console.log('connection~~');
socket.on('delete-stock',function(index){
currentStock.tickers.splice(index,1);
currentStock.data.splice(index,1);
io.emit('stock', {
type:'stock',
currentStock: currentStock
});
});
// io.emit('stock', "stock");
io.emit('stock', {
type:'stock',
currentStock: currentStock
});
socket.on('stock', function (msg) {
msg = msg.trim();
//檢查有沒有重複的company name
for(let i in currentStock.tickers){
if(currentStock.tickers[i]==msg)
{
io.emit('stock',{
type:'error',
data: 'duplicate company name'
});
return;
}
}
let url = `
https://www.quandl.com/api/v3/datatables/WIKI/PRICES.json?ticker=` + msg + `&date.gte=20160101&date.lt=
` + getCurrentDate() + `&qopts.columns=date,open&api_key=
`;
console.log(url);
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('requested');
let data = JSON.parse(body).datatable.data;
if(data.length==0){
io.emit('stock',{
type:'error',
data: 'no data was found'
});
return;
}
for (let d in data) {
//convert date to utc
let date = data[d][0].split('-');
let year = date[0];
let month = date[1];
let day = date[2];
let utc = Date.UTC(year, month-1, day); //month預設是從00開始 所以要-1
data[d][0] = utc;
}
currentStock.tickers.push(msg);
currentStock.data.push(data);
io.emit('stock', {
type:'stock',
currentStock: currentStock
});
// res.json(JSON.stringify());
}
// stock api error
else{
io.emit('stock', {
type:'error',
data: 'stock api error'
});
}
});
});
});
http.listen(process.env.PORT||3000,function(){
console.log("Listening to "+process.env.PORT||3000)
});
function getCurrentDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '/' + mm + '/' + yyyy;
return yyyy + mm + dd;
}