2019-10-16 17:02:04 +02:00
|
|
|
import ipfsClient from 'ipfs-http-client'
|
2019-10-17 00:13:54 +02:00
|
|
|
import { ipfsNodeUri } from '../site.config'
|
2019-10-16 17:02:04 +02:00
|
|
|
|
2019-10-17 00:13:54 +02:00
|
|
|
export async function saveToIpfs(files: File[]) {
|
2019-10-16 17:02:04 +02:00
|
|
|
const { hostname, port, protocol } = new URL(ipfsNodeUri)
|
|
|
|
|
|
|
|
const ipfsConfig = {
|
|
|
|
protocol: protocol.replace(':', ''),
|
|
|
|
host: hostname,
|
|
|
|
port: port || '443'
|
|
|
|
}
|
|
|
|
|
|
|
|
const ipfs = ipfsClient(ipfsConfig)
|
|
|
|
|
|
|
|
const file = [...files][0]
|
|
|
|
let ipfsId
|
|
|
|
const fileDetails = {
|
|
|
|
path: file.name,
|
|
|
|
content: file
|
|
|
|
}
|
|
|
|
const options = {
|
|
|
|
wrapWithDirectory: true,
|
2019-10-17 00:13:54 +02:00
|
|
|
progress: (prog: number) => console.log(`received: ${prog}`)
|
2019-10-16 17:02:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const response = await ipfs.add(fileDetails, options)
|
|
|
|
|
|
|
|
// CID of wrapping directory is returned last
|
|
|
|
ipfsId = `${response[response.length - 1].hash}/${fileDetails.path}`
|
|
|
|
return ipfsId
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error.message)
|
|
|
|
}
|
|
|
|
}
|