import { as_type } from './crud.types' export function crud_upload(type, id, fd, dispatch) { return new Promise( (resolve, reject) => { const xhr = new XMLHttpRequest() xhr.upload.addEventListener("progress", uploadProgress, false) xhr.addEventListener("load", uploadComplete, false) xhr.addEventListener("error", uploadFailed, false) xhr.addEventListener("abort", uploadCanceled, false) xhr.open("POST", '/' + type + '/' + id + '/upload/') xhr.send(fd) dispatch && dispatch({ type: as_type(type, 'upload_loading')}) function uploadProgress (e) { if (e.lengthComputable) { dispatch && dispatch({ type: as_type(type, 'upload_progress'), percent: Math.round(e.loaded * 100 / e.total), [type]: id, }) } else { dispatch && dispatch({ type: as_type(type, 'upload_error'), error: 'unable to compute upload progress', [type]: id, }) } } function uploadComplete (e) { try { const data = JSON.parse(e.target.responseText) } catch (e) { dispatch && dispatch({ type: as_type(type, 'upload_error'), error: 'upload failed', [type]: id, }) return } dispatch && dispatch({ type: as_type(type, 'upload_complete'), data, [type]: id, }) } uploadFailed = function (evt) { dispatch && dispatch({ type: as_type(type, 'upload_error'), error: 'upload failed', [type]: id, }) } uploadCancelled = function (evt) { dispatch && dispatch({ type: as_type(type, 'upload_error'), error: 'upload cancelled', [type]: id, }) } }) } export const upload_action = (type, id, fd) => dispatch => crud_upload(type, id, fd, dispatch)