37 lines
955 B
JavaScript
Raw Normal View History

2023-01-27 18:08:58 -06:00
const cache = new Map()
const expiresIn = 30000 // in milliseconds
2023-05-07 10:44:57 -05:00
async function fetchPrice (fiat) {
2023-01-27 18:08:58 -06:00
const url = `https://api.coinbase.com/v2/prices/BTC-${fiat}/spot`
2023-04-03 09:08:15 -05:00
const price = await fetch(url)
.then((res) => res.json())
.then((body) => parseFloat(body.data.amount))
.catch((err) => {
2023-01-27 18:08:58 -06:00
console.error(err)
return -1
})
cache.set(fiat, { price, createdAt: Date.now() })
return price
}
2023-05-07 10:44:57 -05:00
async function getPrice (fiat) {
fiat ??= 'USD'
if (cache.has(fiat)) {
const { price, createdAt } = cache.get(fiat)
const expired = createdAt + expiresIn < Date.now()
if (expired) fetchPrice(fiat).catch(console.error) // update cache
return price // serve stale price (this on the SSR critical path)
2023-05-10 19:26:07 -05:00
} else {
fetchPrice(fiat).catch(console.error)
2023-05-07 10:44:57 -05:00
}
2023-05-10 19:26:07 -05:00
return null
2023-05-07 10:44:57 -05:00
}
export default {
Query: {
price: async (parent, { fiatCurrency }, ctx) => {
2023-05-10 19:26:07 -05:00
return await getPrice(fiatCurrency)
2023-01-27 18:08:58 -06:00
}
}
}