Update price-history.min.js
This commit is contained in:
parent
a2015c741c
commit
41250af061
2
routes/price-history.min.js
vendored
2
routes/price-history.min.js
vendored
@ -1 +1 @@
|
||||
const express=require('express'),router=express.Router(),cron=require('node-cron'),fs=require('fs'),path=require('path'),csv=require('csv-parser'),PriceHistory=require('../models/price-history'),CSV_FILE_PATH='/home/production/deployed/utility-api/btc_price_history_full.csv';function readCsvFile(){return new Promise((e,r)=>{const t=[];fs.createReadStream(CSV_FILE_PATH).pipe(csv()).on('data',e=>t.push(e)).on('end',()=>e(t)).on('error',e=>r(e))})}async function loadHistoricToDb(){const e=parseInt(Date.now()/1e3);try{const[r,t]=await Promise.all([fetch(`https://query1.finance.yahoo.com/v7/finance/download/BTC-USD?period1=1410912000&period2=${e}&interval=1d&events=history&includeAdjustedClose=true`).then(e=>e.text()),fetch(`https://query1.finance.yahoo.com/v7/finance/download/BTC-INR?period1=1410912000&period2=${e}&interval=1d&events=history&includeAdjustedClose=true`).then(e=>e.text())]);const a=r.split("").slice(1),i=t.split("").slice(1),n=[];for(let e=0;e<a.length;e++){const[r,t,l,o,c,s,p]=a[e].split(","),[u,d,f,g,m,v,h]=i[e].split(",");n.push({updateOne:{filter:{date:new Date(r).getTime(),asset:"btc"},update:{$set:{usd:parseFloat(parseFloat(c).toFixed(2)),inr:parseFloat(parseFloat(m).toFixed(2))}},upsert:!0}})}await PriceHistory.bulkWrite(n),console.log("Data upserted successfully from API.")}catch(r){console.error("Failed to fetch data. Falling back to CSV file:",r);try{const e=await readCsvFile(),r=e.map(e=>({updateOne:{filter:{date:new Date(e.date).getTime(),asset:"btc"},update:{$set:{usd:parseFloat(e.usd),inr:parseFloat(e.inr)}},upsert:!0}}));await PriceHistory.bulkWrite(r),console.log("Data upserted successfully from CSV.")}catch(e){console.error("Error reading CSV file:",e)}}}loadHistoricToDb(),router.get("/",async(e,r)=>{console.log("price-history");try{let{from:t,to:a,on:i,limit:n=100,asset:l="btc",currency:o,sort:c,dates:s}=e.query;const p={asset:l};if(t&&a){if(t=new Date(t).getTime(),a=new Date(a).getTime(),t>a){const e=t;t=a,a=e}}t&&(p.date={$gte:new Date(t).getTime()}),a&&(p.date={...p.date,$lte:new Date(a).getTime()}),s&&(p.date={$in:s.split(",").map(e=>new Date(e).getTime())}),i&&(p.date={$eq:new Date(i).getTime()}),o&&(p[o]={$exists:!0}),c=["asc","desc","ascending","descending","1","-1"].includes(c)?{date:"asc"===c||"ascending"===c||"1"===c?1:-1}:{date:-1};const u={_id:0,__v:0,asset:0};"inr"===o&&(u.usd=0),"usd"===o&&(u.inr=0);const d=await PriceHistory.find(p,u).sort(c).limit("all"===n?0:parseInt(n)).lean();r.json(d)}catch(e){console.log(e),r.status(500).json({error:e})}}),cron.schedule("0 */4 * * *",async()=>{await loadHistoricToDb()}),module.exports=router;
|
||||
const express=require("express"),router=express.Router(),cron=require("node-cron"),axios=require("axios"),fs=require("fs"),path=require("path"),csv=require("csv-parser"),PriceHistory=require("../models/price-history"),CSV_FILE_PATH="/home/production/deployed/utility-api/btc_price_history_full.csv";function readCsvFile(){return new Promise(((e,r)=>{const t=[];fs.createReadStream(CSV_FILE_PATH).pipe(csv()).on("data",(e=>t.push(e))).on("end",(()=>e(t))).on("error",(e=>r(e)))}))}async function fetchBtcPrices(){try{const e=(await axios.get("https://bitpay.com/api/rates")).data,r=e.find((e=>"USD"===e.code&&"US Dollar"===e.name)).rate;return{usd:r,inr:e.find((e=>"INR"===e.code&&"Indian Rupee"===e.name)).rate}}catch(e){return console.error("Error fetching BTC prices from BitPay:",e),null}}async function updateDailyAverage(e){const r=(new Date).setHours(0,0,0,0);try{const t=await PriceHistory.findOne({date:r,asset:"btc"});if(t){const a=(t.usd*t.count+e.usd)/(t.count+1),c=(t.inr*t.count+e.inr)/(t.count+1);await PriceHistory.updateOne({date:r,asset:"btc"},{$set:{usd:a,inr:c,count:t.count+1}})}else await PriceHistory.create({date:r,asset:"btc",usd:e.usd,inr:e.inr,count:1});console.log("Daily average updated successfully.")}catch(e){console.error("Error updating daily average:",e)}}async function collectAndUpdatePrices(){const e=await fetchBtcPrices();e&&await updateDailyAverage(e)}cron.schedule("0 */4 * * *",(async()=>{console.log("Starting price collection for daily averaging..."),await collectAndUpdatePrices()})),module.exports=router;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user