Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active June 23, 2021 16:00
Show Gist options
  • Save gladchinda/bb57c063b68911996804b274fe7bb285 to your computer and use it in GitHub Desktop.
Save gladchinda/bb57c063b68911996804b274fe7bb285 to your computer and use it in GitHub Desktop.
{
displayPrice: (function() {
const PRICE_CACHE = [];
return function _displayPrice(eventIndex) {
if (!PRICE_CACHE[eventIndex]) {
const tickets = this.ticketsByEvent[eventIndex];
if (tickets && tickets.length > 0) {
tickets.sort((a, b) => a.price - b.price);
const min = tickets[0].price;
const max = tickets.slice(-1)[0].price;
PRICE_CACHE[eventIndex] = `N${min}${min === max ? "" : ` - N${max}`}`;
} else return "";
}
return PRICE_CACHE[eventIndex];
};
})()
}
{
async asyncData({ error }) {
try {
const events = await EventService.getEvents();
(function _fetchEventTickets() {
const REFETCH_DELAY_DURATION = 10 * 1000; // 10s
const FAILED_ATTEMPTS = new Map();
function _fetchEventTicket(id, index) {
return EventService.getEventTicketTypes(id)
.then(tickets => { events[index].tickets = tickets })
.catch(() => { FAILED_ATTEMPTS.set(id, index) });
}
function _refetchEventTickets() {
_fetchEventTicketsPromises(
[...FAILED_ATTEMPTS.entries()].map(([id, index]) => {
FAILED_ATTEMPTS.delete(id);
return _fetchEventTicket(id, index);
})
);
}
function _scheduleRefetchEventTickets() {
if (FAILED_ATTEMPTS.size > 0) {
setTimeout(_refetchEventTickets, REFETCH_DELAY_DURATION);
}
}
function _fetchEventTicketsPromises(promises) {
Promise.all(promises).then(
_scheduleRefetchEventTickets,
_scheduleRefetchEventTickets
);
}
_fetchEventTicketsPromises(
events.map(({ id }, index) => _fetchEventTicket(id, index))
);
})();
return { events }
} catch (err) {
error(err);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment