/
ipfs.ts
53 lines (49 loc) · 1.48 KB
/
ipfs.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
/* eslint-disable no-console */
import { create, IPFSHTTPClient } from 'ipfs-http-client';
export const postToIPFS = async (data: any): Promise<string> => {
let ipfs: IPFSHTTPClient | undefined;
let cid = '';
try {
const authorization =
'Basic ' +
btoa(process.env.NEXT_PUBLIC_INFURA_ID + ':' + process.env.NEXT_PUBLIC_INFURA_SECRET);
ipfs = create({
url: 'https://infura-ipfs.io:5001/api/v0',
headers: {
authorization,
},
});
const result = await (ipfs as IPFSHTTPClient).add(data);
cid = `${result.path}`;
} catch (error) {
console.error('IPFS error ', error);
}
return cid;
};
export const IpfsIsSynced = async (cid: string): Promise<boolean> => {
return new Promise<boolean>((resolve, reject) => {
const interval = setInterval(async () => {
const response = await fetch(cid);
if (response.status === 200) {
clearInterval(interval);
resolve(true);
}
}, 5000);
});
};
export const readFromIpfs = async (cid: string): Promise<any> => {
try {
const response = await fetch(process.env.NEXT_PUBLIC_IPFS_BASE_URL + cid);
return await response.json();
} catch (error) {
console.error('IPFS error ', error);
}
};
export const readFileFromIpfs = async (cid: string): Promise<any> => {
try {
const response = await fetch(process.env.NEXT_PUBLIC_IPFS_BASE_URL + cid);
return await response.arrayBuffer();
} catch (error) {
console.error('IPFS error ', error);
}
};