Untitled
unknown
javascript
3 years ago
2.3 kB
7
Indexable
export const uploadImages = ({ images, errorCallback = () => {} }) => async (dispatch, getState) => { // Identify the part of the file name that excludes the (optional) sequence number const keyedImages = images.map((image) => [ image.imageFileName.replace(/-\w+\.\w+$/, ""), image, ]); // Create a group for each such prefix const map = new Map(keyedImages.map(([key]) => [key, []])); // Populate those groups for (const [key, image] of keyedImages) map.get(key).push(image); // And extract those groups into an array (of subarrays) const imageGroups = [...map.values()]; let index = 0; // Keep the index counter separate imageGroups.forEach(async (images) => { // Iterate the groups that can run in parallel for (const image of images) { // Iterate the images that should run sequentially const id = index++; // Get the next unique id const formData = new FormData(); formData.append(image?.imageFileName, image?.imageFile); try { dispatch({ type: constants.UPLOAD_IMAGES_REQUEST, }); const state = getState(); const widgetState = state[ID]; const response = await getAxiosService(state, dispatch).post( widgetState.apiLinks.uploadImages, formData, { onUploadProgress({ loaded, total }) { dispatch( setUploadProgress({ id, loaded, total, }) ); }, } ); const responseImages = response?.data?.map((image) => { return { productName: image?.uploadResult?.productTitle, imageFile: images.find((img) => img?.imageFileName === image?.mediaCode) ?.imageFile || null, }; }); dispatch({ type: constants.UPLOAD_IMAGES_SUCCESS, payload: [...(responseImages || [])], }); } catch (error) { dispatch({ type: constants.UPLOAD_IMAGES_FAILURE, }); errorCallback(error); } } }); };
Editor is loading...