Created
September 10, 2018 07:20
-
-
Save AlexKott/d0b36882e873ec931d69f5d9cc2c7e7f to your computer and use it in GitHub Desktop.
Example of a more complex request middleware
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
import * as t from '@/actions/types'; | |
import ajax from '@/adapters'; | |
import getEndpoint from '@/constants/endpoints'; | |
export default store => next => async action => { | |
const { type, payload } = action; | |
if (type === t.SEND_REQUEST) { | |
const { | |
data, | |
entity, | |
method, | |
name, | |
onSuccess = [], | |
onError = [], | |
onFinally = [], | |
} = payload; | |
const { headers, url } = getEndpoint(name, entity); | |
const token = getAuthToken(store.getState()); | |
try { | |
const response = await ajax({ | |
data, | |
headers, | |
method, | |
token, | |
url, | |
}); | |
onSuccess.forEach(method => method(response)); | |
} catch(error) { | |
onError.forEach(method => method(error)); | |
} finally { | |
onFinally.forEach(method => method()); | |
} | |
} | |
next(action); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment