简体   繁体   中英

Call multiple API with NodeJS and merge them together

I'm changing the question cause I think I explain myself wrong.

I'm using currently 1 API endpoint to receive data which I need. I need to add a second end point to receive data from both end points in the same time, merge them together and store in Database.

First endpoint -

https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1

Second endpoint - https://api.binance.com/api/v3/ticker/24hr?symbol=${symbol}

Here is how I receive Data from first endpoint

const getBTCData = async symbol => {
    let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1`).then(res => res.json());
    const btcusdtdata = data.map(d => {
        return {
            Open: parseFloat(d[1]),
            High: parseFloat(d[2]),
            Low: parseFloat(d[3]),
            Close: parseFloat(d[4]),
            Timespan: 30,
        }
    });
    console.log(btcusdtdata);
    saveToDatebase(symbol, btcusdtdata);
};

Im returning 4 parameters from this endpoint

And I need to take one parameter from second endpoint and combine it with parameters from first one.

I need this parameter from second endpoint - "quoteVolume": "15.30000000"

I founded that Promise.all can be a solution but I don't understand it properly on how I can return data from 2 api and merge them together in a single object to save in MongoDB.

FULL CODE

Small explanation - goal is to take data from both endpoints and store it in MongoDB as well as calculating the average for quoteVolume on last 200 days.

 const { MongoClient } = require('mongodb'); const schedule = require('node-schedule'); const fetch = require("node-fetch"); require('dotenv').config() "use strict"; // This is ES6 specific. Help's to run code faster(IMPORTANT FOR NOTIFICATION SYSTEM) const nodemailer = require("nodemailer"); const symbols = ["ADABTC", "AEBTC","AIONBTC"]; //a descriptive name helps your future self and others understand code easier const getBTCData = async symbol => { let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1`).then(res => res.json()); const btcusdtdata = data.map(d => { return { Open: parseFloat(d[1]), High: parseFloat(d[2]), Low: parseFloat(d[3]), Close: parseFloat(d[4]), Volume: parseFloat(d[5]), Timespan: 30, } }); console.log(btcusdtdata); saveToDatebase(symbol, btcusdtdata); //recursive functions are complicated, we can get rid of it here //by moving the responsibility to the caller }; //helper function for an awaitable timeout const sleep = ms => new Promise(res => setTimeout(res, ms)); const j = schedule.scheduleJob('* * * * * *', async() => { //expand this function to be responsible for looping the data for (let symbol of symbols) { await getBTCData(symbol); await sleep(8000); } }); const getDateTime = () => { let today = new Date(); let date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); return date + ' ' + time; }; const saveToDatebase = async(symbol, BTCdata) => { try { const url = 'mongodb://username:password@ip.adress.com:port/dbname?retryWrites=true&w=majority'; let dateTime = getDateTime(); let db = await MongoClient.connect(url, { useUnifiedTopology: true }); const dbo = db.db('Crypto'); const myobj = Object.assign({ Name: symbol, Date: dateTime }, BTCdata[0]); await dbo.collection(symbol).insertOne(myobj); const average = await dbo.collection(symbol).aggregate([{ $addFields: { DateObj: { $regexFindAll: { input: "$Date", regex: "\\d+" } } } }, { $set: { DateObj: { $dateFromParts: { year: { $toInt: { $arrayElemAt: ["$DateObj.match", 0] } }, month: { $toInt: { $arrayElemAt: ["$DateObj.match", 1] } }, day: { $toInt: { $arrayElemAt: ["$DateObj.match", 2] } }, hour: { $toInt: { $arrayElemAt: ["$DateObj.match", 3] } }, minute: { $toInt: { $arrayElemAt: ["$DateObj.match", 4] } }, second: { $toInt: { $arrayElemAt: ["$DateObj.match", 5] } }, timezone: "Europe/London" } } } }, { $match: { $expr: { $gte: ["$DateObj", { $subtract: ["$$NOW", 201 * 60 * 60 * 24 * 1000] }] } } }, { "$group": { _id: null, "Volume": { "$avg": "$Volume" } } } ]).toArray(); console.log('1 document inserted'); console.log(BTCdata[0].Volume); console.log(average[0].Volume); const RealTimeDataVolume = parseInt(BTCdata[0].Volume); const HistoricalTimeDataVolume = parseInt(average[0].Volume); // 201 DAYS VOLUME HERE 3286033.4285714286 const DayTimesRealAverage = RealTimeDataVolume * 48; // 1 DAY REAL TIME DATA HERE 196579344 const Previous200dVolume = (HistoricalTimeDataVolume - DayTimesRealAverage) / 200; const MultiplePrevious200dVolume = Previous200dVolume * 5; if (MultiplePrevious200dVolume < DayTimesRealAverage) { async function main() { let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, // true for 465, false for other ports auth: { user: process.env.DB_USER, // OUR ALARM EMAIL pass: process.env.DB_PASS, // OUR ALARM PASSWORD }, }); let info = await transporter.sendMail({ from: process.env.DB_USER, // sender address to: process.env.DB_RECEIVER, // list of receivers subject: symbol + 'Is UP', // Subject line text: symbol + " IS UP", // plain text body }); console.log("Message sent: %s", info.messageId, symbol); } main().catch(console.error); } else { console.log('false'); } console.log(DayTimesRealAverage); console.log(MultiplePrevious200dVolume); } catch (e) { console.error(e) } };

You can do it in the same way.

In response you are getting a son object.

You need to do res["quoteVolume"] to get the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM