All files / publisher/listing/hooks useMutateListingData.ts

3.57% Statements 1/28
0% Branches 0/16
20% Functions 1/5
3.57% Lines 1/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88                                                          6x                                                                                                                    
import { useMutation } from "react-query";
 
import { addDateToFilename, getChanges } from "../utils";
 
import type { Data } from "../types";
 
type Options = {
  data: Data;
  dirtyFields: any;
  getDefaultData: Function;
  refetch: Function;
  reset: Function;
  setShowSuccessNotification: Function;
  setUpdateMetadataOnRelease: Function;
  shouldShowUpdateMetadataWarning: Function;
  snapName: string | undefined;
};
 
function useMutateListingData({
  data,
  dirtyFields,
  getDefaultData,
  refetch,
  reset,
  setShowSuccessNotification,
  setUpdateMetadataOnRelease,
  shouldShowUpdateMetadataWarning,
  snapName,
}: Options) {
  return useMutation({
    mutationFn: async (values: any) => {
      const formData = new FormData();
 
      const changes = getChanges(dirtyFields, values, data);
 
      formData.set("csrf_token", window.CSRF_TOKEN);
      formData.set("snap_id", data.snap_id);
 
      if (values.icon && values.icon.length > 0) {
        formData.append("icon", values.icon[0]);
      }
 
      if (values.banner && values.banner.length > 0) {
        formData.append("banner-image", values.banner[0]);
      }
 
      if (values.screenshots) {
        values.screenshots.forEach((screenshot: FileList) => {
          if (screenshot[0]) {
            const oldName = screenshot[0].name;
            const newFile = addDateToFilename(screenshot[0], new Date());
 
            formData.append("screenshots", newFile);
 
            const imageIndex = changes.images.findIndex(
              (image: any) => image.name === oldName,
            );
            changes.images[imageIndex].name = newFile.name;
            changes.images[imageIndex].url = URL.createObjectURL(newFile);
          }
        });
      }
 
      formData.set("changes", JSON.stringify(changes));
 
      const response = await fetch(`/api/${snapName}/listing`, {
        method: "POST",
        body: formData,
      });
 
      if (shouldShowUpdateMetadataWarning(values)) {
        setUpdateMetadataOnRelease(false);
      }
 
      if (!response.ok) {
        throw new Error("There was a problem saving listing data");
      }
    },
    onSuccess: async () => {
      setShowSuccessNotification(true);
      const response = await refetch();
      reset(getDefaultData(response.data));
    },
  });
}
 
export default useMutateListingData;