og

dispatch+http=dispatchX

直接上代码

        
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
/* A relax dispatch lib based on dispatch */ // In redux store where the loading queue is const XHR_PENDING_ACTION = { type: 'APP/XHRInLoading' } // Storage data of dispatch loader const actionOptions = { requestHeaders: { ['Content-Type']: 'application/json' } } // Set/Get setting of dispatch loader export const actionOption = { set: (key, value) => { return actionOptions[key] = value }, get: (key) => { return actionOptions[key] } } export const setRequestHeaders = (headers) => { actionOptions.requestHeaders = Object.assign(actionOptions.requestHeaders, headers) } export const getRequestHeaders = () => { return actionOptions.requestHeaders } // Dispatch loading queue to redux state export const dispatchRequestState = (dispatch) => { const requestQueue = actionOptions['requestQueue'] || [] return new Promise((rs) => { rs(dispatch({ type: XHR_PENDING_ACTION.type, payload: requestQueue })) }) } // Add a request action.type to the loading queue export const addRequestQueue = (dispatch, actionType) => { const requestQueue = actionOptions['requestQueue'] || [] requestQueue.push(actionType) actionOptions['requestQueue'] = requestQueue return dispatchRequestState(dispatch) } // Remove a request action.type to the loading queue export const removeRequestQueue = (dispatch, actionType) => { const requestQueue = actionOptions['requestQueue'] || [] actionOptions['requestQueue'] = requestQueue.filter((queueItem) => {return queueItem !== actionType}) return dispatchRequestState(dispatch) } // Caution: this only runs after redux store initialized export const initXHRPendingQueue = (dispatch) => dispatchRequestState.call({}, dispatch) // It works when you start a GET method XHR export const mapObjectToQueryString = (queryObject) => { let queryString = '' if (queryObject) { const urlQueryKeys = Object.keys(queryObject) if (urlQueryKeys.length) { const urlQueryKeyValue = [] urlQueryKeys.map((key) => { urlQueryKeyValue.push(`${key}=${queryObject[key]}`) }) queryString = `?${urlQueryKeyValue.join('&')}` } } return queryString } // Using fetch to do XHR. const doXHR = (dispatch, action) => { addRequestQueue(dispatch, action.type) return fetch(action.url, { method: action.method, credentials: 'include', headers: action.headers, body: action.XHRBody }).then((response) => { // Request success removeRequestQueue(dispatch, action.type) // Dispatch payload data to redux store const emitResponse = (payload) => { // if response code is ok(Status Code: 200 / 304) if (response.ok) { action.payload = payload } else { // Request failed with response error action.payload = { ...payload, failed: 1, fetchFailed: 0, response: response } } (new Promise((rs) => { dispatch(action) if (action.callback) { action.callback(action.payload) } rs() })).catch((err) => { throw new Error(console.error(err)) }) } const _response = response.clone() // Get response body as text response.text().then((responseText) => { let responseBody = responseText // automatic try parsing response as a JSON string try { responseBody = JSON.parse(responseBody) // if parsing success then return an Object } catch (err) { // if parsing failed the return an original response responseBody = _response } emitResponse(responseBody) }).catch((error) => { // Unexpected response body throw new Error(console.error('DispatchX: Try parse response content error, ', error)) }) }).catch((error) => { // Request failed with network error removeRequestQueue(dispatch, action.type) action.payload = { failed: 1, fetchFailed: 1, error: error }; (new Promise((rs) => { dispatch(action) rs() })).catch((err) => { throw new Error(console.error(err)) }) if (action.callback) { action.callback(action.payload) } }) } // caution: runs when redux store initialed export const dispatch_x = (dispatch, action = {}) => { // check action.type if (!action.type) { throw new Error(console.error('dispatch canceled, because of missing action.type!')) } // if this is a XHR action if (!action.url) { return dispatch(action) } else { action.headers = Object.assign(Object.assign({}, actionOptions['requestHeaders']), action.headers || {}) action.patchName = action.url action.method = (action.method || 'GET').toUpperCase() if (action.method === 'GET') { action.url = action.url + mapObjectToQueryString(action.payload) } else { if (action.headers['Content-Type'] === 'application/json') { action.XHRBody = JSON.stringify(action.payload) } } return doXHR(dispatch, action) } } // set dispatchX based on dispatch export const dispatchX = (action) => { const { store } = actionOptions const hookedDispatch = store.hooks.onAction(store)(store.dispatch) let dispatchPromise = (new Promise((rs) => {rs(-1)})) try { dispatchPromise = dispatch_x(hookedDispatch, action) } catch (err) { store.hooks.onError(err, store.dispatch) } return dispatchPromise }

Article created at   2020/10/27 AM  in category  code ,   59  Views

Related tags: react js

Article Address: https://www.hooyim.com/article/8