-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpinata.ts
97 lines (84 loc) · 2.35 KB
/
pinata.ts
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
89
90
91
92
93
94
95
96
97
import * as dotenv from "dotenv";
import axios from "axios";
import FormData from "form-data";
dotenv.config();
const key: string | undefined = process.env.PINATA_KEY;
const secret: string | undefined = process.env.PINATA_SECRET;
if (!key || !secret) {
throw new Error("Pinata API key or secret is missing. Please check your .env file.");
}
interface IPFSResponse {
success: boolean;
pinataURL?: string;
message?: string;
}
export const uploadJSONToIPFS = async (JSONBody: Record<string, any>): Promise<IPFSResponse> => {
const url = `https://api.pinata.cloud/pinning/pinJSONToIPFS`;
try {
const response = await axios.post(url, JSONBody, {
headers: {
pinata_api_key: key,
pinata_secret_api_key: secret,
},
});
return {
success: true,
pinataURL: `https://gateway.pinata.cloud/ipfs/${response.data.IpfsHash}`,
};
} catch (error: any) {
console.error("Error uploading JSON to IPFS:", error.message);
return {
success: false,
message: error.message,
};
}
};
export const uploadFileToIPFS = async (file: Buffer | Blob): Promise<IPFSResponse> => {
const url = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
const data = new FormData();
data.append("file", file);
const metadata = JSON.stringify({
name: "testname",
keyvalues: {
exampleKey: "exampleValue",
},
});
data.append("pinataMetadata", metadata);
const pinataOptions = JSON.stringify({
cidVersion: 0,
customPinPolicy: {
regions: [
{
id: "FRA1",
desiredReplicationCount: 1,
},
{
id: "NYC1",
desiredReplicationCount: 2,
},
],
},
});
data.append("pinataOptions", pinataOptions);
try {
const response = await axios.post(url, data, {
maxBodyLength: Infinity,
headers: {
"Content-Type": `multipart/form-data; boundary=${(data as any)._boundary}`,
pinata_api_key: key,
pinata_secret_api_key: secret,
},
});
console.log("Image uploaded:", response.data.IpfsHash);
return {
success: true,
pinataURL: `https://gateway.pinata.cloud/ipfs/${response.data.IpfsHash}`,
};
} catch (error: any) {
console.error("Error uploading file to IPFS:", error.message);
return {
success: false,
message: error.message,
};
}
};