2019-09-06 12:39:48 +02:00
|
|
|
/* eslint-disable no-console */
|
|
|
|
|
2019-09-05 16:02:47 +02:00
|
|
|
import { useEffect, useState } from 'react'
|
|
|
|
import ipfsClient from 'ipfs-http-client'
|
|
|
|
|
|
|
|
let ipfs: any = null
|
|
|
|
let ipfsMessage = ''
|
|
|
|
let ipfsVersion = ''
|
|
|
|
|
2019-09-18 18:38:02 +02:00
|
|
|
export interface IpfsConfig {
|
2019-10-07 13:06:24 +02:00
|
|
|
protocol: string
|
2019-09-05 16:02:47 +02:00
|
|
|
host: string
|
|
|
|
port: string
|
2019-09-09 13:53:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export default function useIpfsApi(config: IpfsConfig) {
|
2019-09-05 16:02:47 +02:00
|
|
|
const [isIpfsReady, setIpfsReady] = useState(Boolean(ipfs))
|
2019-09-20 13:51:24 +02:00
|
|
|
const [ipfsError, setIpfsError] = useState('')
|
2019-09-05 16:02:47 +02:00
|
|
|
|
|
|
|
useEffect(() => {
|
2019-09-06 14:48:49 +02:00
|
|
|
async function initIpfs() {
|
2019-09-09 13:53:06 +02:00
|
|
|
if (ipfs !== null) return
|
2019-09-06 14:48:49 +02:00
|
|
|
|
2019-09-09 13:53:06 +02:00
|
|
|
ipfsMessage = 'Checking IPFS gateway...'
|
2019-09-06 14:48:49 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
ipfs = await ipfsClient(config)
|
|
|
|
const version = await ipfs.version()
|
|
|
|
ipfsVersion = version.version
|
2019-10-09 17:32:40 +02:00
|
|
|
ipfsMessage = `Connected to ${config.host}`
|
2019-09-06 14:48:49 +02:00
|
|
|
} catch (error) {
|
2019-10-09 17:32:40 +02:00
|
|
|
setIpfsError(`IPFS connection error: ${error.message}`)
|
2019-09-06 14:48:49 +02:00
|
|
|
}
|
2020-03-17 11:54:46 +01:00
|
|
|
setIpfsReady(Boolean(await (ipfs && ipfs.id())))
|
2019-09-06 14:48:49 +02:00
|
|
|
}
|
2019-09-09 13:53:06 +02:00
|
|
|
|
2019-09-05 16:02:47 +02:00
|
|
|
initIpfs()
|
2019-09-09 13:53:06 +02:00
|
|
|
}, [config])
|
2019-09-05 16:02:47 +02:00
|
|
|
|
2019-09-09 13:53:06 +02:00
|
|
|
useEffect(() => {
|
2019-09-05 16:02:47 +02:00
|
|
|
return function cleanup() {
|
|
|
|
if (ipfs) {
|
|
|
|
setIpfsReady(false)
|
|
|
|
ipfs = null
|
|
|
|
ipfsMessage = ''
|
|
|
|
ipfsVersion = ''
|
2019-09-20 13:51:24 +02:00
|
|
|
setIpfsError('')
|
2019-09-05 16:02:47 +02:00
|
|
|
}
|
|
|
|
}
|
2019-09-09 13:53:06 +02:00
|
|
|
}, [])
|
2019-09-05 16:02:47 +02:00
|
|
|
|
|
|
|
return { ipfs, ipfsVersion, isIpfsReady, ipfsError, ipfsMessage }
|
|
|
|
}
|