Skip to content

Instantly share code, notes, and snippets.

@sonipranjal
Created June 8, 2024 20:45
Show Gist options
  • Save sonipranjal/3c0543095f48a4f015718570341e1153 to your computer and use it in GitHub Desktop.
Save sonipranjal/3c0543095f48a4f015718570341e1153 to your computer and use it in GitHub Desktop.
use upload stuff hook -- s3
import { useState } from "react";
import axios from "axios";
import { toast } from "sonner";
import { api } from "@/utils/api";
const useUploadStuff = () => {
const [isUploadLoading, setIsUploadLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const getUploadSignedUrl = api.storageRouter.getUploadSignedUrl.useMutation();
const uploadStuff = async ({
stuffFile,
saveUrlIntoDBFun,
}: {
stuffFile: File | undefined;
saveUrlIntoDBFun: (url: string) => Promise<void>;
}) => {
if (!stuffFile) return;
try {
setIsUploadLoading(true);
const { assetUrl, signedUrl } = await getUploadSignedUrl.mutateAsync({
fileMimetype: stuffFile.type,
fileName: stuffFile.name,
});
await axios
.put(signedUrl, stuffFile, {
headers: {
"Content-Type": stuffFile.type,
},
onUploadProgress(progressEvent) {
if (progressEvent.progress) {
setUploadProgress(Math.floor(progressEvent.progress * 100));
}
},
})
.catch((err) => {
console.error(err);
toast.error("upload failed!");
setIsUploadLoading(false);
});
await saveUrlIntoDBFun(assetUrl);
setIsUploadLoading(false);
} catch (error) {
toast.error("uploading failed due to some reason");
setIsUploadLoading(false);
}
};
return {
isUploadLoading,
uploadStuff,
uploadProgress,
};
};
export { useUploadStuff };
@sonipranjal
Copy link
Author

sonipranjal commented Jun 8, 2024

getUploadSignedUrl: protectedProcedure
    .input(
      z.object({
        fileName: z.string(),
        fileMimetype: z.string(),
      })
    )
    .mutation(async ({ input: { fileName, fileMimetype } }) => {
      const fileExtensionArr = /[.]/.exec(fileName)
        ? /[^.]+$/.exec(fileName)
        : undefined;
      const fileExtension = fileExtensionArr ? fileExtensionArr[0] : undefined;

      if (!fileExtension) {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message: "wrong type of file!",
        });
      }

      const randomKey = `lesson-thumbnails/${nanoid()}.${fileExtension}`;
      const assetUrl = `${env.NEXT_PUBLIC_R2_URL}/${randomKey}`;

      const signedUrl = await getSignedUrl(
        s3,
        new PutObjectCommand({
          Bucket: env.CLOUDFLARE_R2_BUCKET_NAME,
          Key: randomKey,
          ContentType: fileMimetype,
        }),
        {
          expiresIn: 60 * 2,
        }
      );

      return { signedUrl, assetUrl };
    }),
    ```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment