From 4e7a1b276c3b4670defe4dee6222cfa0f4418f6a Mon Sep 17 00:00:00 2001 From: sairaj mote Date: Sat, 13 Jan 2024 03:09:21 +0530 Subject: [PATCH] adding more query params --- index.html | 6 ++++++ index.min.html | 2 +- routes/price-history.js | 34 +++++++++++++++------------------- routes/price-history.min.js | 2 +- 4 files changed, 23 insertions(+), 21 deletions(-) diff --git a/index.html b/index.html index 3881725..d25e400 100644 --- a/index.html +++ b/index.html @@ -107,6 +107,12 @@ None YYYY-MM-DD + + sort + No + desc + asc | desc | ascending | descending | 1 | -1 + limit No diff --git a/index.min.html b/index.min.html index f20c4a3..18f7c9b 100644 --- a/index.min.html +++ b/index.min.html @@ -1 +1 @@ - RanchiMall Utility APIs

Welcome to the RanchiMall Utility APIs!

Endpoints:

  1. /price-history

    Query parameters:

    Parameter Required Default format | values
    from No None YYYY-MM-DD
    to No None YYYY-MM-DD
    on No None YYYY-MM-DD
    limit No 100 all | <number>
    asset No btc btc
    currency No All usd | inr

    Example:

    /price-history?from=2020-01-01&to=2020-01-31
  2. /hash

    Type POST
    Body JSON
    Body parameter urls [Array]

    Example:

    fetch('https://utility-api.ranchimall.net/hash',{
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ urls: [url] })
    }).then(res => res.json()).then(console.log)

    Output:
    [{
      "url": url,
      "hash": hash
    }]
\ No newline at end of file + RanchiMall Utility APIs

Welcome to the RanchiMall Utility APIs!

Endpoints:

  1. /price-history

    Query parameters:

    Parameter Required Default format | values
    from No None YYYY-MM-DD
    to No None YYYY-MM-DD
    on No None YYYY-MM-DD
    sort No desc asc | desc | ascending | descending | 1 | -1
    limit No 100 all | <number>
    asset No btc btc
    currency No All usd | inr

    Example:

    /price-history?from=2020-01-01&to=2020-01-31
  2. /hash

    Type POST
    Body JSON
    Body parameter urls [Array]

    Example:

    fetch('https://utility-api.ranchimall.net/hash',{
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ urls: [url] })
    }).then(res => res.json()).then(console.log)

    Output:
    [{
      "url": url,
      "hash": hash
    }]
\ No newline at end of file diff --git a/routes/price-history.js b/routes/price-history.js index dd2e622..ffe8ae7 100644 --- a/routes/price-history.js +++ b/routes/price-history.js @@ -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 diff --git a/routes/price-history.min.js b/routes/price-history.min.js index f97c0ad..ee9f70b 100644 --- a/routes/price-history.min.js +++ b/routes/price-history.min.js @@ -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{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;ires.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)}))}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