-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathipfs.ts
59 lines (50 loc) · 1.42 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
54
55
56
57
58
59
import PinataSDK, { PinataClient, PinataPinResponse } from '@pinata/sdk';
import { PINATA_API_KEY, PINATA_SECRET_API_KEY } from './config';
import * as fs from 'fs';
import { MetaData } from './type';
class IPFS {
pinata: PinataClient;
constructor() {
this.pinata = PinataSDK(PINATA_API_KEY, PINATA_SECRET_API_KEY);
}
async uploadFile(filepath: string): Promise<PinataPinResponse> {
const data = fs.readFileSync(filepath);
// should be larger than 2MB
if (data.buffer.byteLength > 2 * 1024 * 1024) {
throw new Error('Image size should be lower than 2MB')
}
const streamForFile = fs.createReadStream(filepath);
const result = await this.pinata.pinFileToIPFS(streamForFile, {
pinataOptions: {
cidVersion: 1
}
})
fs.unlinkSync(filepath);
return result;
}
async uploadMetadata(metadata: MetaData): Promise<PinataPinResponse> {
return this.pinata.pinJSONToIPFS({
...metadata,
}, {
pinataOptions: {
cidVersion: 1
}
});
}
}
async function run() {
const ipfs = new IPFS();
const filepath = '';
const ipfsResp = await ipfs.uploadFile(filepath);
const hash = `ipfs://${ipfsResp.IpfsHash}`;
// metadata sample
const metaData: MetaData = {
name: '',
description: '',
image: hash
}
const resp = await ipfs.uploadMetadata(metaData);
const uri = `ipfs://${resp.IpfsHash}`;
console.log('Final URI:', uri);
}
run();