-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
122 lines (83 loc) · 2.54 KB
/
index.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
const colors = require('colors');
// /$$$$$$$ /$$$$$$$
// | $$__ $$| $$__ $$
// | $$ \ $$| $$ \ $$
// | $$ | $$| $$$$$$$
// | $$ | $$| $$__ $$
// | $$ | $$| $$ \ $$
// | $$$$$$$/| $$$$$$$/
// |_______/ |_______/
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const params = { useNewUrlParser: true}
const dbName = 'robinhood_db';
let db;
// Connect to database
MongoClient.connect(url, params, function(err, client) {
assert.equal(null, err);
console.log(`Connected to ${dbName} successfully on ${url}`.magenta);
db = client.db(dbName);
// readDB('quote_data', db, (data) => handleQuoteData(data));
init(client);
});
const handleQuoteData = (data) => {
console.log(`quote_data: ${pretty(data)}`.bgCyan.black.bold);
}
// Robinhood
const init = (dbClient, interval) => {
// const quote_data = db.collection('documents');
const credentials = require("./credentials.js");
const Robinhood = require('robinhood')(credentials, ()=> {
const token = Robinhood.auth_token();
if(interval) {
setInterval( e=> {getAndSave(Robinhood) }, interval);
}else {
getAndSave(Robinhood);
}
});
}
// get quote_data
const getAndSave = (Robinhood) => {
Robinhood.quote_data('GOOG', function(error, response, body) {
if (error) { err(error); }
if (body === undefined) {err('body undefined');return false}
// console.log(' quote_data => '.inverse, body.results);
const data = [Object.assign({stamp:Date.now()}, {data:body.results})];
// const data = body.results;
save_data( data, 'quote_data', result => {
console.log(`Inserted: `.yellow, `${result.ops[0]._id}`.bgYellow.black.bold);
});
// dbClient.close();
});
}
const saveDataOninterval = (interval, client) => {
setInterval( e=> {
getAndSave(client)
}, interval);
}
const save_data = (data, locName, callback) => {
// Get the documents collection
let collection = db.collection(locName);
// Insert some documents
collection.insertMany(data, function(err, result) {
assert.equal(err, null);
callback(result);
});
}
const readDB = (query ,db, callback) => {
// Get the documents collection
const collection = db.collection(query);
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
callback(docs);
});
}
const err = (error) => {
console.error(error);
process.exit(1);
}
function pretty(obj) {
return JSON.stringify(obj, null, 2)
}