This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathwith-mfs-root.js
63 lines (49 loc) · 1.52 KB
/
with-mfs-root.js
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
'use strict'
const { CID } = require('multiformats/cid')
const { UnixFS } = require('ipfs-unixfs')
const dagPb = require('@ipld/dag-pb')
const { sha256 } = require('multiformats/hashes/sha2')
const log = require('debug')('ipfs:mfs:utils:with-mfs-root')
const errCode = require('err-code')
const {
MFS_ROOT_KEY
} = require('../../../utils')
/**
* @typedef {import('../').MfsContext} MfsContext
*/
/**
* @param {MfsContext} context
* @param {import('ipfs-core-types/src/utils').AbortOptions} [options]
*/
const loadMfsRoot = async (context, options) => {
if (options && options.signal && options.signal.aborted) {
throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })
}
// Open the repo if it's been closed
await context.repo.root.open()
// Load the MFS root CID
let cid
try {
const buf = await context.repo.root.get(MFS_ROOT_KEY)
cid = CID.decode(buf)
} catch (err) {
if (err.code !== 'ERR_NOT_FOUND') {
throw err
}
log('Creating new MFS root')
const buf = dagPb.encode({
Data: new UnixFS({ type: 'directory' }).marshal(),
Links: []
})
const hash = await sha256.digest(buf)
cid = CID.createV0(hash)
await context.repo.blocks.put(cid, buf)
if (options && options.signal && options.signal.aborted) {
throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })
}
await context.repo.root.put(MFS_ROOT_KEY, cid.bytes)
}
log(`Loaded MFS root /ipfs/${cid}`)
return cid
}
module.exports = loadMfsRoot