Last active
May 17, 2019 18:03
-
-
Save iamstarkov/87741d3b3fbf979a5e77c40805c92125 to your computer and use it in GitHub Desktop.
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
``` | |
// src/modules/jwt-fetch.js | |
let token; | |
const updateToken = x => { token = x }; | |
const getToken = () => fetch('/api/jwt/token').then(extractTokenFromRes); | |
const refreshToken = () => fetch('/api/jwt/token/refresh').then(extractTokenFromRes); | |
const jwtFetch = async (url, opts) => { | |
if (!token) { await getToken().then(updateToken); } | |
return fetch(url, { ... opts, headers: { ...opts.headers, token }}) | |
.then(res => { | |
if (hasTokenExpired(res)) { | |
return refreshToken().then(updateToken).then(() => jwtFetch(url, opts)) | |
} | |
return res; | |
} | |
} | |
export default jwtFetch; | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment