Last active
March 17, 2018 19:15
-
-
Save Kelin2025/2bab6a520fd3fde210c90404e76513bb to your computer and use it in GitHub Desktop.
Refresh token once
This file contains hidden or 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
/* API base */ | |
const ApiRoot = new ApiService(fetch, { | |
url: '/api' | |
}) | |
/* Auth service */ | |
const AuthService = ApiRoot.extend({ | |
url: 'auth', | |
method: 'POST' | |
}).on('done', res => localStorage.setItem('token', res.body.token)) | |
/* Service with auth logic */ | |
const WithAuth = ApiRoot.extend({ | |
hooks: { | |
/* Pass token there */ | |
before ({ payload, meta, next }) { | |
if (!meta.requiresAuth) return next(payload) | |
const token = localStorage.getItem('token') | |
next(withToken(token, payload)) | |
}, | |
/* Handle error and try to refresh token */ | |
async fail ({ meta, result, payload, next, retry }) { | |
if (!meta.requiresAuth) return next(result) | |
if (result.status !== 401) return next(result) | |
/* Check this one */ | |
const { success } = await AuthService.doSingleRequest() | |
if (success) { | |
retry(payload) | |
} else { | |
next(result) | |
} | |
} | |
} | |
}) | |
/* | |
Then we can forget about auth | |
and just extend from WithAuth service | |
*/ | |
const GetProfile = WithAuth.extend({ | |
url: 'profile' | |
}) | |
const CreatePost = WithAuth.extend({ | |
url: 'profile', | |
method: 'POST', | |
meta: { requiresAuth: true } | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment