adding more query params

This commit is contained in:
sairaj mote 2024-01-13 03:09:21 +05:30
parent b73bdf2490
commit 4e7a1b276c
4 changed files with 23 additions and 21 deletions

View File

@ -107,6 +107,12 @@
<td>None</td>
<td>YYYY-MM-DD</td>
</tr>
<tr>
<td>sort</td>
<td>No</td>
<td>desc</td>
<td>asc | desc | ascending | descending | 1 | -1</td>
</tr>
<tr>
<td>limit</td>
<td>No</td>

View File

@ -1 +1 @@
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>RanchiMall Utility APIs</title> <style>body{font-family:sans-serif}h1{font-size:2rem;margin-bottom:2rem}ol li{margin-bottom:5rem}a{color:inherit}table{border-collapse:collapse}table,td,th{border:1px solid #000;padding:.5rem}code{display:inline-block;background-color:#eee;padding:.3rem;border-radius:.2rem;font:monospace;font-size:inherit}@media (prefers-color-scheme:dark){body{background-color:#222;color:#eee}table,td,th{border-color:#eee}code{background-color:#333;color:#eee}}</style> </head> <body> <section style="padding:4vw"> <h1> Welcome to the RanchiMall Utility APIs! </h1> <h2> Endpoints: </h2> <ol> <li> <h3> <a href="/price-history">/price-history</a> </h3> <h4> Query parameters: </h4> <table> <thead> <tr> <th>Parameter</th> <th>Required</th> <th>Default</th> <th>format | values</th> </tr> </thead> <tbody> <tr> <td>from</td> <td>No</td> <td>None</td> <td>YYYY-MM-DD</td> </tr> <tr> <td>to</td> <td>No</td> <td>None</td> <td>YYYY-MM-DD</td> </tr> <tr> <td>on</td> <td>No</td> <td>None</td> <td>YYYY-MM-DD</td> </tr> <tr> <td>limit</td> <td>No</td> <td>100</td> <td>all | &lt;number&gt;</td> </tr> <tr> <td>asset</td> <td>No</td> <td>btc</td> <td>btc</td> </tr> <tr> <td>currency</td> <td>No</td> <td>All</td> <td>usd | inr</td> </tr> </tbody> </table> <h4> Example: </h4> <code> /price-history?from=2020-01-01&to=2020-01-31 </code> </li> <li> <h3> <a href="/hash">/hash</a> </h3> <table> <tbody> <tr> <td>Type</td> <td>POST</td> </tr> <tr> <td>Body</td> <td>JSON</td> </tr> <tr> <td>Body parameter</td> <td>urls [Array]</td> </tr> </tbody> </table> <h4> Example: </h4> <code> fetch('https://utility-api.ranchimall.net/hash',{ <br> &nbsp; method: 'POST',<br> &nbsp; headers: {<br> &nbsp; &nbsp; 'Content-Type': 'application/json'<br> &nbsp; },<br> &nbsp; body: JSON.stringify({ urls: [url] })<br> }).then(res => res.json()).then(console.log) <br> <br> Output: <br> [{<br> &nbsp; "url": url,<br> &nbsp; "hash": hash<br> }] </code> </li> </ol> </section>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>RanchiMall Utility APIs</title> <style>body{font-family:sans-serif}h1{font-size:2rem;margin-bottom:2rem}ol li{margin-bottom:5rem}a{color:inherit}table{border-collapse:collapse}table,td,th{border:1px solid #000;padding:.5rem}code{display:inline-block;background-color:#eee;padding:.3rem;border-radius:.2rem;font:monospace;font-size:inherit}@media (prefers-color-scheme:dark){body{background-color:#222;color:#eee}table,td,th{border-color:#eee}code{background-color:#333;color:#eee}}</style> </head> <body> <section style="padding:4vw"> <h1> Welcome to the RanchiMall Utility APIs! </h1> <h2> Endpoints: </h2> <ol> <li> <h3> <a href="/price-history">/price-history</a> </h3> <h4> Query parameters: </h4> <table> <thead> <tr> <th>Parameter</th> <th>Required</th> <th>Default</th> <th>format | values</th> </tr> </thead> <tbody> <tr> <td>from</td> <td>No</td> <td>None</td> <td>YYYY-MM-DD</td> </tr> <tr> <td>to</td> <td>No</td> <td>None</td> <td>YYYY-MM-DD</td> </tr> <tr> <td>on</td> <td>No</td> <td>None</td> <td>YYYY-MM-DD</td> </tr> <tr> <td>sort</td> <td>No</td> <td>desc</td> <td>asc | desc | ascending | descending | 1 | -1</td> </tr> <tr> <td>limit</td> <td>No</td> <td>100</td> <td>all | &lt;number&gt;</td> </tr> <tr> <td>asset</td> <td>No</td> <td>btc</td> <td>btc</td> </tr> <tr> <td>currency</td> <td>No</td> <td>All</td> <td>usd | inr</td> </tr> </tbody> </table> <h4> Example: </h4> <code> /price-history?from=2020-01-01&to=2020-01-31 </code> </li> <li> <h3> <a href="/hash">/hash</a> </h3> <table> <tbody> <tr> <td>Type</td> <td>POST</td> </tr> <tr> <td>Body</td> <td>JSON</td> </tr> <tr> <td>Body parameter</td> <td>urls [Array]</td> </tr> </tbody> </table> <h4> Example: </h4> <code> fetch('https://utility-api.ranchimall.net/hash',{ <br> &nbsp; method: 'POST',<br> &nbsp; headers: {<br> &nbsp; &nbsp; 'Content-Type': 'application/json'<br> &nbsp; },<br> &nbsp; body: JSON.stringify({ urls: [url] })<br> }).then(res => res.json()).then(console.log) <br> <br> Output: <br> [{<br> &nbsp; "url": url,<br> &nbsp; "hash": hash<br> }] </code> </li> </ol> </section>

View File

@ -37,7 +37,7 @@ loadHistoricToDb();
router.get("/", async (req, res) => {
console.log('price-history');
try {
const { from, to, on, limit = 100, asset = 'btc', currency } = req.query;
let { from, to, on, limit = 100, asset = 'btc', currency, sort, dates } = req.query;
const searchParams = {
asset
}
@ -47,12 +47,25 @@ router.get("/", async (req, res) => {
if (to) {
searchParams.date = { ...searchParams.date, $lte: new Date(to).getTime() };
}
if (dates) {
const datesArray = dates.split(',');
searchParams.date = { $in: datesArray.map(date => new Date(date).getTime()) };
}
if (on) {
searchParams.date = { $eq: new Date(on).getTime() };
}
if (currency) {
searchParams[currency] = { $exists: true };
}
if (sort) {
if (['asc', 'desc', 'ascending', 'descending', '1', '-1'].includes(sort))
sort = { date: sort === 'asc' || sort === 'ascending' || sort === '1' ? 1 : -1 };
else
return res.status(400).json({ error: 'Invalid sort. Valid values are asc | desc | ascending | descending | 1 | -1' });
} else {
sort = { date: -1 };
}
const dataFormat = { _id: 0, __v: 0, asset: 0 };
if (currency === 'inr') {
dataFormat.usd = 0;
@ -61,7 +74,7 @@ router.get("/", async (req, res) => {
dataFormat.inr = 0;
}
const priceHistory = await PriceHistory.find(searchParams, dataFormat)
.sort({ date: -1 })
.sort(sort)
.limit(limit === 'all' ? 0 : parseInt(limit));
res.json(priceHistory);
} catch (err) {
@ -70,23 +83,6 @@ router.get("/", async (req, res) => {
}
})
router.post("/", async (req, res) => {
try {
const { 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 {
// will return a csv file

View File

@ -1 +1 @@
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;
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{let{from:from,to:to,on:on,limit:limit=100,asset:asset="btc",currency:currency,sort:sort,dates:dates}=req.query;const searchParams={asset:asset};if(from&&(searchParams.date={$gte:new Date(from).getTime()}),to&&(searchParams.date={...searchParams.date,$lte:new Date(to).getTime()}),dates){const datesArray=dates.split(",");searchParams.date={$in:datesArray.map((date=>new Date(date).getTime()))}}if(on&&(searchParams.date={$eq:new Date(on).getTime()}),currency&&(searchParams[currency]={$exists:!0}),sort){if(!["asc","desc","ascending","descending","1","-1"].includes(sort))return res.status(400).json({error:"Invalid sort. Valid values are asc | desc | ascending | descending | 1 | -1"});sort={date:"asc"===sort||"ascending"===sort||"1"===sort?1:-1}}else sort={date:-1};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(sort).limit("all"===limit?0:parseInt(limit));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;