Skip to content

Commit

Permalink
feat:pinata helper
Browse files Browse the repository at this point in the history
  • Loading branch information
temi0x committed Jun 22, 2024
1 parent f51f95d commit d88cc3b
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions packages/nextjs/utils/pinata.ts
Original file line number Diff line number Diff line change
@@ -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<any> => {
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;
}
};

0 comments on commit d88cc3b

Please sign in to comment.