This repository has been archived by the owner on Aug 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipfs.ts
67 lines (62 loc) · 1.71 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
60
61
62
63
64
65
66
67
import axios from 'axios'
import mime from 'mime-types'
import { INFTData } from 'interfaces/nft'
export const removeURLSlash = (url: string) => {
if (url.length === 0) return url
const lastChar = url.charAt(url.length - 1)
if (lastChar === '/') {
return url.slice(0, -1)
} else {
return url
}
}
export const IPFS_GATEWAY = process.env.NEXT_PUBLIC_IPFS_BASEURL ? removeURLSlash(process.env.NEXT_PUBLIC_IPFS_BASEURL) : ''
export const IPFS_UPLOAD_URL = IPFS_GATEWAY + '/api/v0'
export const uploadFiles = async (file: File) => {
try {
const formData = new FormData()
formData.append(`file`, file)
const response = await axios
.request({
method: 'post',
url: `${IPFS_UPLOAD_URL}/add`,
data: formData,
})
.catch((err) => {
throw new Error(err)
})
return formatIpfsResponse(response.data)
} catch (err) {
throw err
}
}
export const formatIpfsResponse = (res: any) => {
const type = mime.lookup(res.Name)
return {
name: res.Name,
hash: res.Hash,
size: res.Size,
type: type || '',
}
}
export const nftIpfsUpload = async (data: INFTData) => {
const { description, file, title } = data
if (file === null) throw new Error('File cannot be null on ipfs upload')
const { hash: fileHash } = await uploadFiles(file)
const nftMetadata = {
title,
description,
image: fileHash,
properties: {
media: {
hash: fileHash,
name: file?.name,
size: file?.size,
type: file?.type,
},
},
}
const finalBlob = new Blob([JSON.stringify(nftMetadata)], { type: 'application/json' })
const finalFile = new File([finalBlob], 'nft metadata')
return await uploadFiles(finalFile)
}