actionCreators.js
import * as actionTypes from './actionTypes';
import { FETCH_DATA } from '@/store/middleware/api';
import { getSaleStatementDetail } from '@/service/sale/statement';
const saleStatementDetailTypes = ({ params, callback }) => ({
[FETCH_DATA]: {
types: [
actionTypes.STATEMENT_START_LOADING,
actionTypes.GET_STATEMENT_DETAIL_SUCCESS,
actionTypes.STATEMENT_END_LOADING,
],
config: {
params: getSaleStatementDetail(params),
callback
}
}
});
// 销售结算单明细ActionCreators
export const sdActionCreators = {
// 获取销售结算单明细数据
fetchSaleStatementDetail: (params, callback) => {
return dispatch => {
return dispatch(saleStatementDetailTypes({ params, callback }))
}
},
}
中间件api.js
import { request } from '@/axios';
// 经过中间件处理的action所具有的标识
export const FETCH_DATA = 'FETCH_DATA';
export default store => next => action => {
const callAPI = action[FETCH_DATA];
if (typeof callAPI === 'undefined') {
return next(action)
}
const { types, config } = callAPI
if (!Array.isArray(types) && types.length !== 3) {
throw new Error('需要指定一个包含3个action type的数据')
}
if (!types.every(type => typeof type === 'string')) {
throw new Error('action type 必须为字符串类型')
}
const actionWith = data => {
const finalAction = { ...action, ...data }
delete finalAction[FETCH_DATA]
return finalAction
}
const [requestType, successType, failureType] = types;
// 开始发送请求
next(actionWith({ type: requestType }))
return request(config.params)
.then(response => {
// 发送请求成功
const { data: { data, code, msg } } = response;
if (code === 200) {
config.callback && config.callback({
success: true,
data,
message: msg || '数据请求成功'
})
} else {
config.callback && config.callback({
success: false,
data,
message: msg || '数据请求失败'
})
}
return next(actionWith({
type: successType,
data,
}))
})
.catch(error => {
const { response } = error;
// 发送请求失败
config.callback && config.callback({
success: false,
message: response?.data?.msg || '数据请求失败'
})
return next(actionWith({
type: failureType,
message: response?.data?.msg || '数据请求失败'
}))
})
}