From 0296adc3ace0e36b92a56ec3a01a933b9bbd2e99 Mon Sep 17 00:00:00 2001 From: Jules Laplace Date: Tue, 29 May 2018 01:48:20 +0200 Subject: write a buncha crud code --- app/client/api/crud.upload.js | 70 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 app/client/api/crud.upload.js (limited to 'app/client/api/crud.upload.js') 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 -- cgit v1.2.3-70-g09d2