/ app / protocols / ipfs-protocol.js
ipfs-protocol.js
 1  import fetchToHandler from './fetch-to-handler.js'
 2  import path from 'node:path'
 3  import * as fs from 'node:fs/promises'
 4  
 5  export default async function createHandler (ipfsOptions, session) {
 6    return fetchToHandler(async () => {
 7      const { default: makeFetch } = await import('js-ipfs-fetch')
 8      const ipfsHttpModule = await import('ipfs-http-client')
 9  
10      const Ctl = await import('ipfsd-ctl')
11  
12      const { default: GoIPFS } = await import('go-ipfs')
13  
14      const ipfsBin = GoIPFS
15        .path()
16        .replace(`.asar${path.sep}`, `.asar.unpacked${path.sep}`)
17  
18      const ipfsdOpts = {
19  
20        ipfsOptions,
21        type: 'go',
22        disposable: false,
23        test: false,
24        remote: false,
25        ipfsHttpModule,
26        ipfsBin
27      }
28  
29      let ipfsd = await Ctl.createController(ipfsdOpts)
30  
31      await ipfsd.init({ ipfsOptions })
32      const version = await ipfsd.version()
33      console.log(`IPFS Version: ${version}\nIPFS bin path: ${ipfsBin}`)
34  
35      try {
36        await ipfsd.start()
37        await ipfsd.api.id()
38      } catch (e) {
39        console.log('IPFS Unable to boot daemon', e.message)
40        const { repo } = ipfsOptions
41        const lockFile = path.join(repo, 'repo.lock')
42        const apiFile = path.join(repo, 'api')
43        try {
44          await Promise.all([
45            fs.rm(lockFile),
46            fs.rm(apiFile)
47          ])
48          ipfsd = await Ctl.createController(ipfsdOpts)
49          await ipfsd.start()
50          await ipfsd.api.id()
51        } catch (cause) {
52          const message = `Unable to start daemon due to extra lockfile. Please clear your ipfs folder at ${repo} and try again.`
53          throw new Error(message, { cause })
54        }
55      }
56  
57      console.log('IPFS ID:', await ipfsd.api.id())
58  
59      const fetch = await makeFetch({
60        ipfs: ipfsd.api
61      })
62  
63      fetch.close = async () => {
64        return ipfsd.stop()
65      }
66  
67      return fetch
68    }, session)
69  }