Newer
Older
taehui / taehui-fe / src / forum / usePostFile.ts
@Taehui Taehui on 13 Mar 1 KB v1.0.0
import { useMutation } from "@tanstack/react-query";
import { wwwAXIOS } from "src/Www";
import { getMillis } from "taehui-ts/date";

import { useAvatarStore } from "src/Stores";

export default function usePostFile() {
  const { totem } = useAvatarStore();

  return useMutation({
    mutationFn: async ({
      file,
      textView,
    }: {
      file: File;
      textView: HTMLTextAreaElement;
    }) => {
      const form = new FormData();
      form.append("data", file);
      const {
        status,
        data: { fileName },
      } = await wwwAXIOS.post("/file", form, {
        headers: {
          millis: getMillis(),
          totem,
        },
      });
      if (status === 201) {
        const { selectionStart, value } = textView;
        const textBefore = value.substring(0, selectionStart);
        const textLater = value.substring(selectionStart, value.length);
        if (fileName.match(/^.*\.(bmp|gif|jpeg|jpg|png|webp)$/i)) {
          return `${textBefore}<img alt="" src="${fileName}">${textLater}`;
        } else if (
          fileName.match(
            /^.*\.(aif|aiff|asf|flac|m4a|mid|midi|mp2|mp3|ogg|opus|raw|wav|wma)$/i,
          )
        ) {
          return `${textBefore}<audio src="${fileName}" controls></audio>${textLater}`;
        } else if (
          fileName.match(/^.*\.(avi|flv|m1v|mkv|mov|mp4|mpeg|mpg|webm|wmv)$/i)
        ) {
          return `${textBefore}<video src="${fileName}" controls></video>${textLater}`;
        } else {
          return `${textBefore}<a href="${fileName}">${file.name}</a>${textLater}`;
        }
      }
    },
  });
}