reduce io blocking ssr

This commit is contained in:
keyan 2023-05-07 10:44:57 -05:00
parent 3465eb7aba
commit 3c8ea0db22
4 changed files with 20 additions and 13 deletions

View File

@ -1,15 +1,7 @@
const cache = new Map() const cache = new Map()
const expiresIn = 30000 // in milliseconds const expiresIn = 30000 // in milliseconds
async function getPrice (fiat) { async function fetchPrice (fiat) {
fiat ??= 'USD'
if (cache.has(fiat)) {
const { price, createdAt } = cache.get(fiat)
const expired = createdAt + expiresIn < Date.now()
if (!expired) {
return price
}
}
const url = `https://api.coinbase.com/v2/prices/BTC-${fiat}/spot` const url = `https://api.coinbase.com/v2/prices/BTC-${fiat}/spot`
const price = await fetch(url) const price = await fetch(url)
.then((res) => res.json()) .then((res) => res.json())
@ -22,6 +14,17 @@ async function getPrice (fiat) {
return price return price
} }
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)
}
return await fetchPrice(fiat)
}
export default { export default {
Query: { Query: {
price: async (parent, { fiatCurrency }, ctx) => { price: async (parent, { fiatCurrency }, ctx) => {

View File

@ -62,12 +62,15 @@ async function authMethods (user, args, { models, me }) {
export default { export default {
Query: { Query: {
me: async (parent, args, { models, me }) => { me: async (parent, { skipUpdate }, { models, me }) => {
if (!me) { if (!me) {
return null return null
} }
return await models.user.update({ where: { id: me.id }, data: { lastSeenAt: new Date() } }) if (!skipUpdate) {
models.user.update({ where: { id: me.id }, data: { lastSeenAt: new Date() } }).catch(console.error)
}
return await models.user.findUnique({ where: { id: me.id } })
}, },
settings: async (parent, args, { models, me }) => { settings: async (parent, args, { models, me }) => {
if (!me) { if (!me) {

View File

@ -44,7 +44,8 @@ export function getGetServerSideProps (query, variables = null, notFoundFunc, re
const client = await getSSRApolloClient(req) const client = await getSSRApolloClient(req)
const { data: { me } } = await client.query({ const { data: { me } } = await client.query({
query: ME query: ME,
variables: { skipUpdate: true }
}) })
const { data: { price } } = await client.query({ const { data: { price } } = await client.query({

View File

@ -2,7 +2,7 @@ import { gql } from 'apollo-server-micro'
export default gql` export default gql`
extend type Query { extend type Query {
me: User me(skipUpdate: Boolean): User
settings: User settings: User
user(name: String!): User user(name: String!): User
users: [User!] users: [User!]