Skip to content

Let getFreshValue know whether the update is happening in the background or not #24

Closed
@kentcdodds

Description

@kentcdodds

Here's what I've got:

function abortTimeoutSignal(timeMs: number) {
  const abortController = new AbortController()
  void new Promise(resolve => setTimeout(resolve, timeMs)).then(() => {
    abortController.abort()
  })
  return abortController.signal
}

async function gravatarExistsForEmail({
  email,
  request,
  timings,
  forceFresh,
}: {
  email: string
  request: Request
  timings?: Timings
  forceFresh?: boolean
}) {
  return cachified({
    key: `gravatar-exists-for:${email}`,
    cache: lruCache,
    request,
    timings,
    forceFresh,
    ttl: 1000 * 20,
    staleWhileRevalidate: 1000 * 60 * 60 * 24 * 365,
    checkValue: prevValue => typeof prevValue === 'boolean',
    getFreshValue: async () => {
      const gravatarUrl = getAvatar(email, {fallback: '404'})
      try {
        const avatarResponse = await fetch(gravatarUrl, {
          method: 'HEAD',
          signal: abortTimeoutSignal(1000 * 2),
        })
        return avatarResponse.status === 200
      } catch (error: unknown) {
        console.error(`Error getting gravatar for ${email}:`, error)
        return false
      }
    },
  })
}

I have the abortTimeoutSignal thing in place so gravatar won't cause me issues if my page is waiting on it. I think if my page is waiting on it I'd prefer that the timeout time be more like 500ms, but if the update is happening in the background (SWR) then I'm fine with it taking even 10 seconds. Thoughts? Maybe an argument passed to getFreshValue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions