// request is a module that makes http calls easier
const request = require('request');
const MongoClient = require('mongodb').MongoClient;
const dsn = "mongodb://192.168.99.100:37017";
// Generic function that fetches the closing bitcoin dates of the last month from a public API
function fetchFromAPI(callback) {
// We are using fat arrow (=>) syntax here. This is a new way to create anonymous functions in Node
// Please review the Node.js documentation if this looks unfamiliar to you
request.get('https://api.coindesk.com/v1/bpi/historical/close.json', (err, raw, body) => {
return callback(err, JSON.parse(body));
});
}
function insertMongodb(collection, data) {
const insertedPromises = [];
if(collection.countDocuments() === 0) {
Object.keys(data).forEach((key) => {
insertedPromises.push(collection.insertOne({date: key, value: data[key]}));
});
}
return Promise.all(insertedPromises);
}
MongoClient.connect(dsn, { useNewUrlParser: true }, (err, client) => {
console.time('mongodb');
if(err) throw err;
console.log("connected to MongoDB successfully");
fetchFromAPI((err, data) => {
if (err) throw err;
const collection = client.db('maxcoin').collection('value');
console.log(data.bpi);
insertMongodb(collection, data.bpi)
.then((result) => {
console.log(`${result.length} has been inserted successfully`);
const options = {'sort': [['value', -1]]};
collection.findOne({}, options, (err, result) => {
if(err) throw err;
console.log(`The highest value of bitcoin was ${result.value} on ${result.date}`);
console.timeEnd('mongodb');
client.close();
})
})
.catch((err) => {
console.log(err);
process.exit();
})
});
})