nuxt-graphql-middleware icon indicating copy to clipboard operation
nuxt-graphql-middleware copied to clipboard

[Question] Retry original operation

Open d0peCode opened this issue 1 year ago • 4 comments

Hello, awesome project. I'm moving my app to this package instead nuxt-apollo.

With apollo we could use onError to create errorLink on which we've been refreshing the tokens and then performing original query/mutation again:

case 'UNAUTHENTICATED':
  return fromPromise(
    refreshAccessToken(`${refreshToken}`, `${codeVerifier}`, event),
  )
    .filter(value => Boolean(value))
    .flatMap((accessToken) => {
      const oldHeaders = operation.getContext().headers
      operation.setContext({
        headers: {
          ...oldHeaders,
          authorization: `Bearer ${accessToken}`,
        },
      })

      return forward(operation)

I've seen onServerError in docs:

import type { H3Event } from 'h3'
import type { FetchError } from 'ofetch'

export default defineNuxtConfig({
  graphqlMiddleware: {
    onServerError(
      event: H3Event,
      error: FetchError,
      operation: string,
      operationName: string,
    ) {
      event.setHeader('cache-control', 'no-cache')
      return {
        data: {},
        errors: [error.message]
      }
    }
  }
})

With above configuration we could set new httpOnly cookies with tokens when we detect 401 response from our graph.

After that new tokens will be added automatically by serverFetchOptions where we take access_token from httpOnly cookie and add as header to the request. (we can do because all happens on nuxt server)

But my concern is there is no forward argument in the onServerError so I wonder is it possible to somehow retry the original mutation/query which failed after setting new cookies with just refreshed tokens?

d0peCode avatar Sep 13 '23 16:09 d0peCode