diff --git a/index.js b/index.js index 1a82768..627a5ff 100644 --- a/index.js +++ b/index.js @@ -93,25 +93,25 @@ app.get("/", (req, res) => { from No None - DD-MM-YYYY + YYYY-MM-DD to No None - DD-MM-YYYY + YYYY-MM-DD on No None - DD-MM-YYYY + YYYY-MM-DD limit No 100 - all | number + all | <number> asset @@ -122,8 +122,8 @@ app.get("/", (req, res) => { currency No - usd - usd, inr + All + usd | inr @@ -133,7 +133,7 @@ app.get("/", (req, res) => { @@ -170,21 +170,21 @@ function loadHistoricToDb() { }) } // run loadHistoricToDb() only once when the server starts and no data is present in the database -PriceHistory.countDocuments({}, (err, count) => { - if (err) { +PriceHistory.countDocuments() + .then((count) => { + if (count === 0) { + loadHistoricToDb(); + } + }) + .catch((err) => { console.log(err); - } - if (count === 0) { - loadHistoricToDb(); - } -}) + }) app.get("/price-history", async (req, res) => { try { - const { from, to, on, limit = 100, asset = 'btc', currency = 'usd' } = req.query; + const { from, to, on, limit = 100, asset = 'btc', currency } = req.query; const searchParams = { - asset, - [currency]: { $exists: true } + asset } if (from) { searchParams.date = { $gte: new Date(from).getTime() }; @@ -195,7 +195,17 @@ app.get("/price-history", async (req, res) => { if (on) { searchParams.date = { $eq: new Date(on).getTime() }; } - const priceHistory = await PriceHistory.find(searchParams, { _id: 0, __v: 0 }) + if (currency) { + searchParams[currency] = { $exists: true }; + } + const dataFormat = { _id: 0, __v: 0, asset: 0 }; + if (currency === 'inr') { + dataFormat.usd = 0; + } + if (currency === 'usd') { + dataFormat.inr = 0; + } + const priceHistory = await PriceHistory.find(searchParams, dataFormat) .sort({ date: -1 }) .limit(limit === 'all' ? 0 : parseInt(limit)); res.json(priceHistory); diff --git a/index.min.js b/index.min.js index 9fa64dc..45bdcf4 100644 --- a/index.min.js +++ b/index.min.js @@ -1 +1 @@ -require("dotenv").config();const express=require("express"),mongoose=require("mongoose"),cors=require("cors"),cron=require("node-cron"),rateLimit=require("express-rate-limit"),app=express(),PORT=3e3,HOST="0.0.0.0";app.use(express.json()),app.use(cors());const limiter=rateLimit({windowMs:6e4,max:20});app.use(limiter),mongoose.connect("mongodb://localhost/price-history");const db=mongoose.connection;db.on("error",console.error.bind(console,"connection error:")),db.once("open",(()=>{console.log("Connected to MongoDB")})),app.get("/",((req,res)=>{res.send('\n RanchiMall Price History API\n \n \n
\n

\n Welcome to the RanchiMall Price History API!\n

\n

\n Available endpoints:\n

\n \n

\n Query parameters:\n

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ParameterRequiredDefaultformat | values
fromNoNoneDD-MM-YYYY
toNoNoneDD-MM-YYYY
onNoNoneDD-MM-YYYY
limitNo100all | number
assetNobtcbtc
currencyNousdusd, inr
\n

\n Example:\n

\n \n
\n ')}));const 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{console.log(err)}))}PriceHistory.countDocuments({},((err,count)=>{err&&console.log(err),0===count&&loadHistoricToDb()})),app.get("/price-history",(async(req,res)=>{try{const{from:from,to:to,on:on,limit:limit=100,asset:asset="btc",currency:currency="usd"}=req.query,searchParams={asset:asset,[currency]:{$exists:!0}};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()});const priceHistory=await PriceHistory.find(searchParams,{_id:0,__v:0}).sort({date:-1}).limit("all"===limit?0:parseInt(limit));res.json(priceHistory)}catch(err){console.log(err),res.status(500).json({error:err})}})),app.post("/price-history",(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});res.json(priceHistory)}catch(err){console.log(err),res.status(500).json({error:err})}})),app.listen(3e3,HOST,(()=>{console.log(`Listening on ${HOST}:3000`)})),cron.schedule("0 12 * * *",(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{console.log("Connected to MongoDB")})),app.get("/",((req,res)=>{res.send('\n RanchiMall Price History API\n \n \n
\n

\n Welcome to the RanchiMall Price History API!\n

\n

\n Available endpoints:\n

\n
    \n
  • /price-history
  • \n
\n

\n Query parameters:\n

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ParameterRequiredDefaultformat | values
fromNoNoneYYYY-MM-DD
toNoNoneYYYY-MM-DD
onNoNoneYYYY-MM-DD
limitNo100all | <number>
assetNobtcbtc
currencyNoAllusd | inr
\n

\n Example:\n

\n
    \n
  • \n \n /price-history?from=2020-01-01&to=2020-01-31\n \n
  • \n
\n
\n ')}));const 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{console.log(err)}))}PriceHistory.countDocuments().then((count=>{0===count&&loadHistoricToDb()})).catch((err=>{console.log(err)})),app.get("/price-history",(async(req,res)=>{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})}})),app.post("/price-history",(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});res.json(priceHistory)}catch(err){console.log(err),res.status(500).json({error:err})}})),app.listen(3e3,HOST,(()=>{console.log(`Listening on ${HOST}:3000`)})),cron.schedule("0 12 * * *",(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