-
-
Save srttk/41451410c5df3806bfa82843f21e1795 to your computer and use it in GitHub Desktop.
urql + auth-exchange + aws-amplify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeOperation } from '@urql/svelte' | |
import { authExchange } from '@urql/exchange-auth' | |
import { Auth } from 'aws-amplify' | |
import produce from 'immer' | |
import { set } from 'lodash' | |
const amplifyAuthExchange = authExchange({ | |
addAuthToOperation: ({ authState, operation }) => { | |
if (!authState?.token) { | |
return operation | |
} | |
const newContext = produce(operation.context, context => { | |
set(context, 'fetchOptions.headers.Authorization', authState.token) | |
}) | |
return makeOperation(operation.kind, operation, newContext) | |
}, | |
willAuthError: ({ authState }) => { | |
try { | |
const [,payload] = authState.token.split('.') | |
const { exp } = JSON.parse(Buffer.from(payload, 'base64')) | |
return exp * 1000 < Date.now() | |
} catch(e) { | |
return true | |
} | |
}, | |
didAuthError: ({ error }) => | |
error.graphQLErrors.some(e => e.message === 'Unauthorized'), | |
getAuth: async () => { | |
const session = await Auth.currentSession() | |
if (session) { | |
// defines the authState elsewhere | |
return { | |
token: session.getAccessToken().getJwtToken(), | |
} | |
} | |
Auth.signOut() | |
return null | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment