以arc-web项目为例子
1:http/index.js
这个文件主要的作用是 发起http请求,并拿到结果
发起http请求的部分
const invokeApi = (参数1-配置参数) => (参数2-URL等请求参数) => {发起URL请求,返回请求结果}
2:http/requestJson.js : 引入 http/index.js
这个文件的作用主要是提供参数1
3:index.js
在这一步主要是引入第二步的返回结果,作为作为中间的参数使用 reduxRequestMiddleware(httpRequestJson)
中间件的具体写法
export const httpApi = Symbol('call ajax api')
// requestJson为第二步中的返回结果 即invokeApi函数 action这是操作步骤
action :
export function getProductOrderTotalList(queryParam) {
return {
[httpApi]: {
url: '/arc/report/order_summarize/list',
options: {
method: 'POST',
body: queryParam,
},
types: ['GET_PRODUCT_ORDER_TOTAL_LISTT_SUCCESS'],
},
}
}
const middleware = (requestJson, catchError) => store => next => (action) => {
const httpSymbol = action[httpApi] // 拿到action中的httpApi
if (typeof httpSymbol === 'undefined') {
// 如果找不到 httpApi,则不走中间件的流程,直接进行下一步,next(action)的作用就是执行下一步,即发起dispatch(action)
return next(action)
}
const { options, types, url, acceptType } = httpSymbol
// 检验参数,例如URL和type等
if (typeof url !== 'string') {
throw new Error('请指定请求路径!')
}
if (!Array.isArray(types) || !types.every(x => typeof x === 'string')) {
throw new Error('请指定的action types数组,且每个元素为string类型')
}
const actionWith = obj => ({
...action,
[httpApi]: undefined,
requestInformation: httpSymbol,
...obj,
})
const [
successType,
requestType = 'HTTP_REQUEST',
failureType = 'HTTP_FAILURE',
errorType = 'HTTP_ERROR',
requestCompletedType = 'HTTP_REQUEST_COMPLETED',
] = types
// 发起一个action http请求开始
next(actionWith({ type: requestType }))
// 如果发起的请求的类型为blob,则走下面这一步
if (acceptType === 'blob') {
return requestJson(url, options, acceptType)
.then(response => response.blob().then(blob => next(actionWith({
files: {
name: response.headers.get('filename'),
blob,
},
type: successType,
}))).catch(error => next(actionWith({
error,
type: errorType,
}))))
.catch(error => next(actionWith({
error,
type: errorType,
})));
}
// requestJson是一个函数,为第一步的函数,是发起一个http请求,获取服务器资源
return requestJson(url, options).then((response) => {
// 发起一个action 表示请求完成
next(actionWith({ type: requestCompletedType }))
if (response.resultCode === '000000') {
// 如果服务器返回的结果是00000,表示返回成功 发起一个action type为successType,并且返回从服务器拿到的结果
return next(actionWith({
type: successType,
response,
}))
}
// 如果失败,则发起一个action type为failureType
return next(actionWith({
response,
type: failureType,
}))
}).catch((error) => {
next(actionWith({
error,
type: errorType,
}))
if (typeof catchError === 'function') {
catchError(error)
}
})
}
export default middleware
复制代码