This repository has been 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
/
get.js
107 lines (99 loc) · 2.52 KB
/
get.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict'
const { withTimeoutOption } = require('../../utils')
const first = require('it-first')
const last = require('it-last')
const toCidAndPath = require('ipfs-core-utils/src/to-cid-and-path')
/**
* @param {Object} config
* @param {import('..').IPLD} config.ipld
* @param {import('..').Preload} config.preload
*/
module.exports = ({ ipld, preload }) => {
/**
* Retrieve an IPLD format node
*
* @param {CID} ipfsPath - A DAG node that follows one of the supported IPLD formats
* @param {GetOptions & AbortOptions} [options] - An optional configration
* @returns {Promise<DagEntry>}
* @example
* ```js
* ```JavaScript
* // example obj
* const obj = {
* a: 1,
* b: [1, 2, 3],
* c: {
* ca: [5, 6, 7],
* cb: 'foo'
* }
* }
*
* const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' })
* console.log(cid.toString())
* // zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5
*
* async function getAndLog(cid, path) {
* const result = await ipfs.dag.get(cid, { path })
* console.log(result.value)
* }
*
* await getAndLog(cid, '/a')
* // Logs:
* // 1
*
* await getAndLog(cid, '/b')
* // Logs:
* // [1, 2, 3]
*
* await getAndLog(cid, '/c')
* // Logs:
* // {
* // ca: [5, 6, 7],
* // cb: 'foo'
* // }
*
* await getAndLog(cid, '/c/ca/1')
* // Logs:
* // 6
* ```
*/
const get = async function get (ipfsPath, options = {}) {
const {
cid,
path
} = toCidAndPath(ipfsPath)
if (path) {
options.path = path
}
if (options.preload !== false) {
preload(cid)
}
if (options.path) {
const result = options.localResolve
/** @type {DagEntry} - first will return undefined if empty */
? (await first(ipld.resolve(cid, options.path)))
/** @type {DagEntry} - last will return undefined if empty */
: (await last(ipld.resolve(cid, options.path)))
return result
}
return {
value: await ipld.get(cid, options),
remainderPath: ''
}
}
return withTimeoutOption(get)
}
/**
* @typedef {Object} GetOptions
* @property {boolean} [localResolve=false]
* @property {number} [timeout]
* @property {boolean} [preload=false]
* @property {string} [path] - An optional path within the DAG to resolve
*
* @typedef {Object} DagEntry
* @property {Object} value
* @property {string} remainderPath
*
* @typedef {import('..').CID} CID
* @typedef {import('../../utils').AbortOptions} AbortOptions
*/