make rewards query less aggressive

This commit is contained in:
keyan 2023-10-23 19:46:51 -05:00
parent d2697477a0
commit a85af82460

View File

@ -4,9 +4,26 @@ import { serializeInvoicable } from './serial'
import { ANON_USER_ID } from '../../lib/constants' import { ANON_USER_ID } from '../../lib/constants'
import { getItem } from './item' import { getItem } from './item'
export default { const rewardCache = new Map()
Query: {
rewards: async (parent, { when }, { models }) => { async function updateCachedRewards (when, models) {
const rewards = await getRewards(when, models)
rewardCache.set(when, { rewards, createdAt: Date.now() })
return rewards
}
async function getCachedRewards (staleIn, when, models) {
if (rewardCache.has(when)) {
const { rewards, createdAt } = rewardCache.get(when)
const expired = createdAt + staleIn < Date.now()
if (expired) updateCachedRewards(when, models).catch(console.error)
return rewards // serve stale rewards
}
return await updateCachedRewards(when, models)
}
async function getRewards (when, models) {
console.log('getRewards', when)
if (when) { if (when) {
if (when.length > 2) { if (when.length > 2) {
throw new GraphQLError('too many dates', { extensions: { code: 'BAD_USER_INPUT' } }) throw new GraphQLError('too many dates', { extensions: { code: 'BAD_USER_INPUT' } })
@ -63,7 +80,12 @@ export default {
ORDER BY days_cte.day ASC` ORDER BY days_cte.day ASC`
return results.length ? results : [{ total: 0, time: '0', sources: [] }] return results.length ? results : [{ total: 0, time: '0', sources: [] }]
}, }
export default {
Query: {
rewards: async (parent, { when }, { models }) =>
when ? await getRewards(when, models) : await getCachedRewards(5000, when, models),
meRewards: async (parent, { when }, { me, models }) => { meRewards: async (parent, { when }, { me, models }) => {
if (!me) { if (!me) {
return null return null