Handling response codes
See original GitHub issueHi everybody, this is a question not an actual issue but I don’t know where to ask so here it goes.
I’m building an app that has a public and a private section and we are using sagas to manage side effects, most of the time we call
a function that retrieves data from a backend.
Because sessions may be expired (we use jwt that provide a TTL for each token) or unauthorized we wrapped the call
method to something with a little more semantic to us, here is an example:
//sagas/utils.js
import { sessionExpired, resourceForbidden, resourceUnauthorized } from '../actionCreators'
export function* callCheckingAuthentication(fn, ...rest) {
const response = yield call(fn, ...rest)
const code = response.code
if(code === 419) { //419: When the session has expired
yield put(sessionExpired())
}
if(code === 403) { //403: When the resource is forbidden
yield put(resourceForbidden())
}
if(code === 401) { //401: When the resource is unauthorized
yield put(resourceUnauthorized())
}
return Promise.resolve(response)
}
I know callCheckingAuthentication
is a terrible name but it is a WIP and I can’t figure out a better name.
The main idea is to use this new function when making an authenticated request, like this:
import { dataLoaded } from '../actionCreators'
export function* dataRequested() {
let action = null
while(action = yield take('DATA_REQUESTED')) {
const result = yield callCheckingAuthentication(fetchData)
yield put(dataLoaded(result.data))
}
}
This allow us to put
relevant actions (SESSION_EXPIRED
, RESOURCE_FORBIDDEN
, etc) so they can be take
en by other sagas or reduced by any interested reducers. The key thing is to always return the original result so we don’t break the regular flow of the generator waiting for this result.
I was wondering if this is a valid approach or if it has any drawbacks, so far we haven’t experienced any issue with this approach but maybe somebody can came up with one.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:12
- Comments:11 (5 by maintainers)
Top GitHub Comments
What about making the error codes handling a normal function, a function which returns an action ?
@cherta, that’s an interesting piece of code. I tried to implement something similar but failed with the
fetchData
promise. Can you share the code of that? Thanks, Karel