Created
November 15, 2018 15:07
-
-
Save jeremyadavis/1188a6a7329e54ba2dc1be9815a54d9a to your computer and use it in GitHub Desktop.
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
| // saga.js | |
| export function* processSaveAttachment(action) { | |
| const files = action && action.payload; | |
| const requestData = new FormData(); | |
| files.forEach((file) => requestData.append('upfile', file)); | |
| // console.log('[files]', files); | |
| // for (const pair of requestData.entries()) { | |
| // console.log(`${pair[0]}, ${pair[1]}`); | |
| // } | |
| try { | |
| const payload = yield call(attachmentsApi.createAttachments, requestData); // Basic POST request | |
| yield put(saveAttachmentsSuccess(payload)); | |
| } catch (e) { | |
| yield put(saveAttachmentsFailure(new Error(e))); | |
| } | |
| } | |
| // apiHelper.js | |
| export default function request(url, method, data) { | |
| return setupRequest(url, method, data) | |
| .then((formattedRequest) => fetch(formattedRequest.url, formattedRequest.options)) | |
| .then(checkStatus) | |
| .then(parseJSON) | |
| .then(processJSON) | |
| .catch(handleError); | |
| } | |
| function setupRequest(url, method = 'GET', data) { | |
| const requestHasData = method === 'POST' || method === 'PUT'; | |
| const options = { | |
| method, | |
| credentials: 'same-origin', | |
| headers: { | |
| Accept: 'application/json', | |
| 'Content-Type': 'application/json', | |
| }, | |
| }; | |
| if (requestHasData) { | |
| if (typeof (data) !== 'object') { | |
| return new Error('Unknown data type given'); | |
| } | |
| const objectClass = Object.prototype.toString.call(data).slice(8, -1); | |
| if (objectClass !== 'FormData') { | |
| options.body = JSON.stringify(data); | |
| } else { | |
| options.body = data; | |
| options.headers = { Accept: '*/*' }; | |
| } | |
| } | |
| return Promise.resolve({ | |
| url, | |
| options, | |
| }); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment