Skip to content

Instantly share code, notes, and snippets.

@ripesunflower
Created July 13, 2018 20:28
Show Gist options
  • Save ripesunflower/40717cfd6485b0b9b6ab1c161d346c9e to your computer and use it in GitHub Desktop.
Save ripesunflower/40717cfd6485b0b9b6ab1c161d346c9e to your computer and use it in GitHub Desktop.
// in addUploadFeature.js
/**
* Convert a `File` object returned by the upload input into a base 64 string.
* That's not the most optimized way to store images in production, but it's
* enough to illustrate the idea of data provider decoration.
*/
const convertFileToBase64 = (file: any) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file.rawFile);
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
/**
* Convert uploaded image in base 64 and attach it to
* the `picture` sent property, with `src` and `title` attributes.
*/
const addUploadFeature = (requestHandler: any) => (type: any, resource: any, params: any) => {
if (type === 'UPDATE' || type === 'CREATE') {
if (params.data.upload_images && params.data.upload_images.length) {
const newPictures = params.data.upload_images.filter((p: any) => p.rawFile instanceof File);
return Promise.all(newPictures.map(convertFileToBase64))
.then((base64Pictures) => requestHandler(type, resource, {
...params,
data: {
...params.data,
upload_images: [...base64Pictures],
},
}));
}
}
// for other request types and reources, fall back to the defautl request handler
return requestHandler(type, resource, params);
};
export default addUploadFeature;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment