utility-api/routes/price-history.min.js
2024-01-12 15:30:24 +05:30

1 line
3.1 KiB
JavaScript

const express=require("express"),router=express.Router(),cron=require("node-cron"),PriceHistory=require("../models/price-history");function loadHistoricToDb(){const now=parseInt(Date.now()/1e3);Promise.all([fetch(`https://query1.finance.yahoo.com/v7/finance/download/BTC-USD?period1=1410912000&period2=${now}&interval=1d&events=history&includeAdjustedClose=true`).then((res=>res.text())),fetch(`https://query1.finance.yahoo.com/v7/finance/download/BTC-INR?period1=1410912000&period2=${now}&interval=1d&events=history&includeAdjustedClose=true`).then((res=>res.text()))]).then((async([usd,inr])=>{const usdData=usd.split("\n").slice(1),inrData=inr.split("\n").slice(1),priceHistoryData=[];for(let i=0;i<usdData.length;i++){const[date,open,high,low,close,adjClose,volume]=usdData[i].split(","),[date2,open2,high2,low2,close2,adjClose2,volume2]=inrData[i].split(",");priceHistoryData.push({date:new Date(date).getTime(),asset:"btc",usd:parseFloat(parseFloat(close).toFixed(2)),inr:parseFloat(parseFloat(close2).toFixed(2))})}await PriceHistory.deleteMany({asset:"btc"}),await PriceHistory.insertMany(priceHistoryData)})).catch((err=>{console.log(err)}))}loadHistoricToDb(),router.get("/",(async(req,res)=>{console.log("price-history");try{const{from:from,to:to,on:on,limit:limit=100,asset:asset="btc",currency:currency}=req.query,searchParams={asset:asset};from&&(searchParams.date={$gte:new Date(from).getTime()}),to&&(searchParams.date={...searchParams.date,$lte:new Date(to).getTime()}),on&&(searchParams.date={$eq:new Date(on).getTime()}),currency&&(searchParams[currency]={$exists:!0});const dataFormat={_id:0,__v:0,asset:0};"inr"===currency&&(dataFormat.usd=0),"usd"===currency&&(dataFormat.inr=0);const priceHistory=await PriceHistory.find(searchParams,dataFormat).sort({date:-1}).limit("all"===limit?0:parseInt(limit));res.json(priceHistory)}catch(err){console.log(err),res.status(500).json({error:err})}})),router.post("/",(async(req,res)=>{try{const{dates:dates}=req.body;if(!dates)return res.status(400).json({error:"dates is required"});if(!Array.isArray(dates))return res.status(400).json({error:"dates must be an array"});const priceHistory=await PriceHistory.find({date:{$in:dates}},{_id:0,__v:0,asset:0});res.json(priceHistory)}catch(err){console.log(err),res.status(500).json({error:err})}})),cron.schedule("0 */4 * * *",(async()=>{try{const[usd,inr]=await Promise.all([fetch("https://query1.finance.yahoo.com/v7/finance/download/BTC-USD").then((res=>res.text())),fetch("https://query1.finance.yahoo.com/v7/finance/download/BTC-INR").then((res=>res.text()))]),usdData=usd.split("\n").slice(1),inrData=inr.split("\n").slice(1);for(let i=0;i<usdData.length;i++){const[date,open,high,low,close,adjClose,volume]=usdData[i].split(","),[date2,open2,high2,low2,close2,adjClose2,volume2]=inrData[i].split(","),priceHistoryData={date:new Date(date).getTime(),asset:"btc",usd:parseFloat(parseFloat(close).toFixed(2)),inr:parseFloat(parseFloat(close2).toFixed(2))};await PriceHistory.findOneAndUpdate({date:priceHistoryData.date,asset:priceHistoryData.asset},priceHistoryData,{upsert:!0})}}catch(err){console.log(err)}})),module.exports=router;