From d88cc3b4f8af30745cf0ca068db41ee138f31319 Mon Sep 17 00:00:00 2001 From: temi0x Date: Sat, 22 Jun 2024 23:44:32 +0100 Subject: [PATCH] feat:pinata helper --- packages/nextjs/utils/pinata.ts | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 packages/nextjs/utils/pinata.ts diff --git a/packages/nextjs/utils/pinata.ts b/packages/nextjs/utils/pinata.ts new file mode 100644 index 0000000..117f0dd --- /dev/null +++ b/packages/nextjs/utils/pinata.ts @@ -0,0 +1,47 @@ +import axios from "axios"; +import FormData from "form-data"; +import fs from "fs"; + +interface PinFileProps { + filePath: string; + fileName: string; +} + +export const pinFileToIPFS = async ({ filePath, fileName }: PinFileProps): Promise => { + const JWT = process.env.PINATA_JWT; + if (!JWT) { + throw new Error("PINATA_JWT is not defined in environment variables."); + } + + const formData = new FormData(); + const fileStream = fs.createReadStream(filePath); + formData.append("file", fileStream); + + const pinataMetadata = JSON.stringify({ + name: fileName, + }); + formData.append("pinataMetadata", pinataMetadata); + + const pinataOptions = JSON.stringify({ + cidVersion: 0, + }); + formData.append("pinataOptions", pinataOptions); + + try { + const response = await axios.post( + "https://api.pinata.cloud/pinning/pinFileToIPFS", + formData, + { + maxBodyLength: Infinity, // This is needed to prevent Axios from throwing a "Max body length exceeded" error + headers: { + "Content-Type": `multipart/form-data; boundary=${formData.getBoundary()}`, + Authorization: `Bearer ${JWT}`, + }, + } + ); + return response.data; + } catch (error) { + console.error(error); + throw error; + } +}; \ No newline at end of file