Skip to content

Commit

Permalink
Update price-history.js
Browse files Browse the repository at this point in the history
  • Loading branch information
tripathyr authored Oct 23, 2024
1 parent f6a2a52 commit 6169835
Showing 1 changed file with 88 additions and 0 deletions.
88 changes: 88 additions & 0 deletions routes/price-history.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ function readCsvFile() {
});
}

// Function to parse dates in different formats (e.g., 2024-10-2 or 2024-9-3)
function parseDateString(dateStr) {
const parts = dateStr.split('-');
const year = parseInt(parts[0]);
const month = parseInt(parts[1]) - 1; // Months are 0-indexed in JavaScript Date
const day = parseInt(parts[2]);

return new Date(year, month, day).setHours(0, 0, 0, 0); // Set time to 00:00:00.000
}

// Function to fetch BTC prices in USD and INR from BitPay API
async function fetchBtcPrices() {
try {
Expand Down Expand Up @@ -92,6 +102,84 @@ async function collectAndUpdatePrices() {
}
}

// Route to handle price history requests
router.get("/", async (req, res) => {
console.log('price-history');
try {
let { from, to, on, limit = 100, asset = 'btc', currency, sort, dates } = req.query;
const searchParams = {
asset
};

// Convert 'from' and 'to' dates to proper format
if (from && to) {
from = parseDateString(from);
to = parseDateString(to);
if (from > to) {
const temp = from;
from = to;
to = temp;
}
}

if (from) {
searchParams.date = { $gte: from };
}
if (to) {
searchParams.date = { ...searchParams.date, $lte: to };
}

// If the 'dates' parameter is used
if (dates) {
const datesArray = dates.split(',').map(date => parseDateString(date.trim()));
searchParams.date = { $in: datesArray };
}

// If the 'on' parameter is used for a single date
if (on) {
const onDate = parseDateString(on);
searchParams.date = { $eq: onDate };
}

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 };
}

// Formatting the data to exclude certain fields
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(sort)
.limit(limit === 'all' ? 0 : parseInt(limit))
.lean();

if (!priceHistory || priceHistory.length === 0) {
return res.status(404).json({ message: 'No data found' });
}

res.json(priceHistory);
} catch (err) {
console.log(err);
res.status(500).json({ error: err });
}
});

// Cron job to collect prices every 4 hours
cron.schedule('0 */4 * * *', async () => {
console.log('Starting price collection for daily averaging...');
Expand Down

0 comments on commit 6169835

Please sign in to comment.