[英]Call multiple API with NodeJS and merge them together
我正在改變問題,因為我認為我解釋錯了。
我目前正在使用 1 個 API 端點來接收我需要的數據。 我需要添加第二個端點以同時從兩個端點接收數據,將它們合並在一起並存儲在數據庫中。
第一個端點 -
https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1
第二個端點 - https://api.binance.com/api/v3/ticker/24hr?symbol=${symbol}
這是我從第一個端點接收數據的方式
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);
};
我從這個端點返回 4 個參數
我需要從第二個端點獲取一個參數並將其與第一個端點的參數結合起來。
我需要來自第二個端點的這個參數 - "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.
完整代碼
小解釋 - 目標是從兩個端點獲取數據並將其存儲在 MongoDB 以及計算最近 200 天的quoteVolume
平均值。
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) } };
你可以用同樣的方法來做。
作為回應,你得到了一個兒子 object。
你需要做 res["quoteVolume"] 來獲取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.