-
-
Notifications
You must be signed in to change notification settings - Fork 461
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(auth): Implement new initializer function API (#3012)
- Loading branch information
Showing
7 changed files
with
737 additions
and
586 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
--- | ||
'@urql/exchange-auth': major | ||
--- | ||
|
||
Implement new `authExchange` API, which removes the need for an `authState` (i.e. an internal authentication state) and removes `getAuth`, replacing it with a separate `refreshAuth` flow. | ||
|
||
The new API requires you to now pass an initializer function. This function receives a `utils` | ||
object with `utils.mutate` and `utils.appendHeaders` utility methods. | ||
It must return the configuration object, wrapped in a promise, and this configuration is similar to | ||
what we had before, if you're migrating to this. Its `refreshAuth` method is now only called after | ||
authentication errors occur and not on initialization. Instead, it's now recommended that you write | ||
your initialization logic in-line. | ||
|
||
```js | ||
authExchange(async utils => { | ||
let token = localStorage.getItem('token'); | ||
let refreshToken = localStorage.getItem('refreshToken'); | ||
return { | ||
addAuthToOperation(operation) { | ||
return utils.appendHeaders(operation, { | ||
Authorization: `Bearer ${token}`, | ||
}); | ||
}, | ||
didAuthError(error) { | ||
return error.graphQLErrors.some(e => e.extensions?.code === 'FORBIDDEN'); | ||
}, | ||
async refreshAuth() { | ||
const result = await utils.mutate(REFRESH, { token }); | ||
if (result.data?.refreshLogin) { | ||
token = result.data.refreshLogin.token; | ||
refreshToken = result.data.refreshLogin.refreshToken; | ||
localStorage.setItem('token', token); | ||
localStorage.setItem('refreshToken', refreshToken); | ||
} | ||
}, | ||
}; | ||
}); | ||
``` |
Oops, something went wrong.