diff options
Diffstat (limited to 'app/client/api/crud.upload.js')
| -rw-r--r-- | app/client/api/crud.upload.js | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/app/client/api/crud.upload.js b/app/client/api/crud.upload.js new file mode 100644 index 0000000..42aae2b --- /dev/null +++ b/app/client/api/crud.upload.js @@ -0,0 +1,70 @@ +import { as_type } from './crud.types' + +export function 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 function uploadAction(type, id, fd) { + return dispatch => upload(type, id, fd, dispatch) +}
\ No newline at end of file |
