2023-01-28 00:08:58 +00:00
|
|
|
const cache = new Map()
|
|
|
|
const expiresIn = 30000 // in milliseconds
|
2023-01-27 23:20:33 +00:00
|
|
|
|
2023-05-07 15:44:57 +00:00
|
|
|
async function fetchPrice (fiat) {
|
2023-01-28 00:08:58 +00:00
|
|
|
const url = `https://api.coinbase.com/v2/prices/BTC-${fiat}/spot`
|
2023-04-03 14:08:15 +00:00
|
|
|
const price = await fetch(url)
|
2023-01-27 23:20:33 +00:00
|
|
|
.then((res) => res.json())
|
|
|
|
.then((body) => parseFloat(body.data.amount))
|
|
|
|
.catch((err) => {
|
2023-01-28 00:08:58 +00:00
|
|
|
console.error(err)
|
|
|
|
return -1
|
|
|
|
})
|
|
|
|
cache.set(fiat, { price, createdAt: Date.now() })
|
|
|
|
return price
|
2023-01-27 23:20:33 +00:00
|
|
|
}
|
|
|
|
|
2023-05-07 15:44:57 +00: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-11 00:26:07 +00:00
|
|
|
} else {
|
|
|
|
fetchPrice(fiat).catch(console.error)
|
2023-05-07 15:44:57 +00:00
|
|
|
}
|
2023-05-11 00:26:07 +00:00
|
|
|
return null
|
2023-05-07 15:44:57 +00:00
|
|
|
}
|
|
|
|
|
2023-01-27 23:20:33 +00:00
|
|
|
export default {
|
|
|
|
Query: {
|
|
|
|
price: async (parent, { fiatCurrency }, ctx) => {
|
2023-05-11 00:26:07 +00:00
|
|
|
return await getPrice(fiatCurrency)
|
2023-01-28 00:08:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|