Skip to content

Instantly share code, notes, and snippets.

@fisshy
Created December 5, 2018 20:59
Show Gist options
  • Save fisshy/319d88d904924861c46f057ae2ec006f to your computer and use it in GitHub Desktop.
Save fisshy/319d88d904924861c46f057ae2ec006f to your computer and use it in GitHub Desktop.
Concepts of using redux-observable to refresh token
//Http wrapper
export const post$ = (path, model) => {
return defer(() => {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
let accessToken = storage.get().accessToken
if (accessToken) {
headers['Authorization'] = 'Bearer ' + accessToken;
}
return ajax.post(baseUrl(path), model, headers)
});
}
//Api
export const refreshAuth$ = () => {
let refreshToken = storage.get().refreshToken
return post$('/user/refresh/login', { refreshToken });
}
//Actions
export const refreshAuth = () => ({
type : REFRESH_TOKEN
})
export const httpError = (errors) => ({
type: HTTP_ERROR,
errors
})
//Epics
export const reAuthenticateEpic = (action$, store) =>
action$.pipe(
ofType(REFRESH_TOKEN),
switchMap(() => {
return api.refreshAuth$().pipe(
map(apiResponse => {
var user = authHelper.save(apiResponse.response)
return userFound(user);
}),
catchError((err) => (of(logout()))
)
}));
export const refreshToken = (action$, err, source) =>
action$.pipe(
ofType(USER_FOUND),
takeUntil(action$.pipe(ofType(LOGOUT))),
take(1),
mergeMapTo(source),
merge(of(refreshAuth()))
);
export const handleError = action$ => (error, source) => {
return error.status === 401 ? refreshToken(action$, error, source) : of(httpError(error.response.errors))
}
// Actual epic doing HTTP.
// catchError is handeling the error checking
export const getAccountEpic = (action$, state) => {
return action$.pipe(
ofType(GET_DATA),
switchMap((action) => api.getData$(action.id).pipe(
map(response => getDataSuccess(response)),
catchError(handleError(action$))
))
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment