template-ivan
Version:
68 lines (60 loc) • 1.63 kB
JavaScript
// @flow
import HTTP_API from '../actions/httpmiddleware'
import type { Dispatch, Actions } from '../actions/index'
/**
* http请求redux中间件
*/
function middleware() {
return (next: Dispatch) => (action: Actions): any => {
if (typeof action[HTTP_API] === 'undefined') {
return next(action)
}
const {
options = {},
types,
url,
} = action[HTTP_API]
if (typeof url !== 'string') {
throw new Error('Please specify a string URL.')
}
if (!Array.isArray(types) || !types.every(x => typeof x === 'string')) {
throw new Error('Please specify a array types. Each of which has to be string.')
}
// {string[]} http请求的四种状态处理类型, [请求成功,请求发起,请求失败,请求出错]
const [
successType,
requestType = 'HTTP_REQUEST',
failureType = 'HTTP_FAILURE',
errorType = 'HTTP_ERROR',
] = types
next({
type: requestType,
HTTP_API: action[HTTP_API],
})
// action.options fetch请求参数
return fetch(url, options)
.then((response) => {
if (response.resultCode === '000000') {
return next({
type: successType,
HTTP_API: action[HTTP_API],
response,
})
}
return next({
type: failureType,
HTTP_API: action[HTTP_API],
response,
})
})
.catch((error) => {
next({
type: errorType,
HTTP_API: action[HTTP_API],
error,
})
throw error
})
}
}
export default middleware