From 3ed1e1bc519d53cbcde024ecdfae44bb1d053e8d Mon Sep 17 00:00:00 2001 From: Pedro Santos Date: Thu, 10 Oct 2019 18:38:19 +0100 Subject: [PATCH 1/2] chore: update examples in docs to async/await --- README.md | 17 +- SPEC/BITSWAP.md | 47 +++-- SPEC/BLOCK.md | 113 +++++------ SPEC/BOOTSTRAP.md | 84 +++++++- SPEC/CONFIG.md | 89 ++++----- SPEC/DAG.md | 78 ++++---- SPEC/DHT.md | 80 +++++--- SPEC/FILES.md | 438 ++++++++++++++++++++++++------------------ SPEC/KEY.md | 90 ++++++--- SPEC/MISCELLANEOUS.md | 159 ++++++++------- SPEC/NAME.md | 108 +++++++---- SPEC/OBJECT.md | 204 ++++++++++---------- SPEC/PIN.md | 52 ++--- SPEC/PUBSUB.md | 108 +++++------ SPEC/REFS.md | 86 ++++++--- SPEC/REPO.md | 46 +++-- SPEC/STATS.md | 40 +++- SPEC/SWARM.md | 107 ++++++----- 18 files changed, 1107 insertions(+), 839 deletions(-) diff --git a/README.md b/README.md index 151070b9b..a65ffdd44 100644 --- a/README.md +++ b/README.md @@ -71,20 +71,21 @@ Install `interface-ipfs-core` as one of the dependencies of your project and as ```js const tests = require('interface-ipfs-core') +const nodes = [] // Create common setup and teardown const createCommon = () => ({ // Do some setup common to all tests - setup (cb) { - // Must call back with an "IPFS factory", an object with a `spawnNode` method - cb(null, { - // Use ipfsd-ctl or other to spawn an IPFS node for testing - spawnNode (cb) { /* ... */ } - }) + setup: async () => { + // Use ipfsd-ctl or other to spawn an IPFS node for testing + const node = await spawnNode() + nodes.push(node) + + return node.api }, // Dispose of nodes created by the IPFS factory and any other teardown - teardown (cb) { - cb() + teardown: () => { + return Promise.all(nodes.map(n => n.stop())) } }) diff --git a/SPEC/BITSWAP.md b/SPEC/BITSWAP.md index 9afe4a5ec..6262e7df6 100644 --- a/SPEC/BITSWAP.md +++ b/SPEC/BITSWAP.md @@ -7,36 +7,48 @@ > Returns the wantlist, optionally filtered by peer ID -#### `ipfs.bitswap.wantlist([peerId], [callback])` +#### `ipfs.bitswap.wantlist([peerId])` -`callback` must follow `function (err, list) {}` signature, where `err` is an error if the operation was not successful. `list` is an Object containing the following keys: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object representing the wantlist | + +the returned object contains the following keys: - `Keys` An array of objects containing the following keys: - `/` A string multihash -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.bitswap.wantlist((err, list) => console.log(list)) - +const list = await ipfs.bitswap.wantlist() +console.log(list) // { Keys: [{ '/': 'QmHash' }] } -ipfs.bitswap.wantlist(peerId, (err, list) => console.log(list)) - +const list2 = await ipfs.bitswap.wantlist(peerId) +console.log(list2) // { Keys: [{ '/': 'QmHash' }] } ``` +A great source of [examples][] can be found in the tests for this API. + #### `bitswap.stat` > Show diagnostic information on the bitswap agent. -##### `ipfs.bitswap.stat([callback])` +##### `ipfs.bitswap.stat()` Note: `bitswap.stat` and `stats.bitswap` can be used interchangeably. -`callback` must follow `function (err, stats) {}` signature, where `err` is an error if the operation was not successful. `stats` is an Object containing the following keys: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains information about the bitswap agent | + +the returned object contains the following keys: - `provideBufLen` is an integer. - `wantlist` (array of CIDs) @@ -48,14 +60,13 @@ Note: `bitswap.stat` and `stats.bitswap` can be used interchangeably. - `dupBlksReceived` is a [BigNumber Int][1] - `dupDataReceived` is a [BigNumber Int][1] -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.bitswap.stat((err, stats) => console.log(stats)) - -// { provideBufLen: 0, +const stats = await ipfs.bitswap.stat() +console.log(stats) +// { +// provideBufLen: 0, // wantlist: [ { '/': 'QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM' } ], // peers: // [ 'QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM', @@ -66,7 +77,11 @@ ipfs.bitswap.stat((err, stats) => console.log(stats)) // blocksSent: 0, // dataSent: 0, // dupBlksReceived: 0, -// dupDataReceived: 0 } +// dupDataReceived: 0 +// } ``` +A great source of [examples][] can be found in the tests for this API. + [1]: https://github.com/MikeMcl/bignumber.js/ +[examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/bitswap diff --git a/SPEC/BLOCK.md b/SPEC/BLOCK.md index 3319cd299..d3eeb6304 100644 --- a/SPEC/BLOCK.md +++ b/SPEC/BLOCK.md @@ -9,7 +9,7 @@ > Get a raw IPFS block. -##### `ipfs.block.get(cid, [options], [callback])` +##### `ipfs.block.get(cid, [options])` `cid` is a [cid][cid] which can be passed as: @@ -17,24 +17,17 @@ - CID, a CID instance - String, the base58 encoded version of the multihash -`callback` must follow `function (err, block) {}` signature, where `err` is an error if the operation was not successful and `block` is a [Block][block] type object, containing both the data and the hash of the block. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A [Block][block] type object, containing both the data and the hash of the block | **Example:** ```JavaScript -ipfs.block.get(cid, function (err, block) { - if (err) { - throw err - } - block.key((err, key) => { - if (err) { - throw err - } - console.log(key, block.data) - }) -}) +const block = await ipfs.block.get(cid) +console.log(block.data) ``` A great source of [examples][] can be found in the tests for this API. @@ -43,7 +36,7 @@ A great source of [examples][] can be found in the tests for this API. > Stores input as an IPFS block. -##### `ipfs.block.put(block, [options], [callback])` +##### `ipfs.block.put(block, [options])` Where `block` can be: @@ -65,9 +58,11 @@ if no options are passed, it defaults to `{ format: 'dag-pb', mhtype: 'sha2-256' **Note:** If you pass a [`Block`][block] instance as the block parameter, you don't need to pass options, as the block instance will carry the CID value as a property. -`callback` has the signature `function (err, block) {}`, where `err` is an error if the operation was not successful and `block` is a [Block][block] type object, containing both the data and the hash of the block. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A [Block][block] type object, containing both the data and the hash of the block | **Example:** @@ -75,34 +70,28 @@ If no `callback` is passed, a promise is returned. // Defaults const buf = new Buffer('a serialized object') -ipfs.block.put(buf, (err, block) => { - if (err) { throw err } - // Block has been stored +const block = await ipfs.block.put(buf) - console.log(block.data.toString()) - // Logs: - // a serialized object - console.log(block.cid.toBaseEncodedString()) - // Logs: - // the CID of the object -}) +console.log(block.data.toString()) +// Logs: +// a serialized object +console.log(block.cid.toBaseEncodedString()) +// Logs: +// the CID of the object // With custom format and hashtype through CID const CID = require('cids') const buf = new Buffer('another serialized object') const cid = new CID(1, 'dag-pb', multihash) -ipfs.block.put(blob, cid, (err, block) => { - if (err) { throw err } - // Block has been stored - - console.log(block.data.toString()) - // Logs: - // a serialized object - console.log(block.cid.toBaseEncodedString()) - // Logs: - // the CID of the object -}) +const block = await ipfs.block.put(blob, cid) + +console.log(block.data.toString()) +// Logs: +// a serialized object +console.log(block.cid.toBaseEncodedString()) +// Logs: +// the CID of the object ``` A great source of [examples][] can be found in the tests for this API. @@ -111,7 +100,7 @@ A great source of [examples][] can be found in the tests for this API. > Remove one or more IPFS block(s). -##### `ipfs.block.rm(cid, [options], [callback])` +##### `ipfs.block.rm(cid, [options])` `cid` is a [cid][cid] which can be passed as: @@ -125,21 +114,19 @@ A great source of [examples][] can be found in the tests for this API. - force (boolean): Ignores nonexistent blocks. - quiet (boolean): write minimal output -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful and `result` is a list of objects, containing hash and (potentially) error strings. +**Returns** -If an error string is present for a given object in `result`, the block with that hash was not removed and the string will contain the reason why, for example if the block was pinned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects containing hash and (potentially) error strings | -If no `callback` is passed, a promise is returned. +Note: If an error string is present for a given object in the returned array, the block with that hash was not removed and the string will contain the reason why, for example if the block was pinned. **Example:** ```JavaScript -ipfs.block.rm(cid, function (err, result) { - if (err) { - throw err - } - console.log(result[0].hash) -}) +const result = await ipfs.block.rm(cid) +console.log(result[0].hash) ``` A great source of [examples][] can be found in the tests for this API. @@ -148,7 +135,7 @@ A great source of [examples][] can be found in the tests for this API. > Print information of a raw IPFS block. -##### `ipfs.block.stat(cid, [callback])` +##### `ipfs.block.stat(cid)` `cid` is a [cid][cid] which can be passed as: @@ -156,7 +143,13 @@ A great source of [examples][] can be found in the tests for this API. - `String`, the toString version of the multihash (or of an encoded version) - CID, a CID instance -`callback` must follow the signature `function (err, stats) {}`, where `err` is an error if the operation was not successful and `stats` is an object with the format:` +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object containing the block's info | + +the returned object has the following keys: ```JavaScript { @@ -165,25 +158,19 @@ A great source of [examples][] can be found in the tests for this API. } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript const multihashStr = 'QmQULBtTjNcMwMr4VMNknnVv3RpytrLSdgpvMcTnfNhrBJ' const cid = new CID(multihashStr) -ipfs.block.stat(cid, (err, stats) => { - if (err) { - throw err - } - console.log(stats) - // Logs: - // { - // key: QmQULBtTjNcMwMr4VMNknnVv3RpytrLSdgpvMcTnfNhrBJ, - / size: 3739 - // } -}) +const stats = await ipfs.block.stat(cid) +console.log(stats) +// Logs: +// { +// key: QmQULBtTjNcMwMr4VMNknnVv3RpytrLSdgpvMcTnfNhrBJ, +// size: 3739 +// } ``` A great source of [examples][] can be found in the tests for this API. diff --git a/SPEC/BOOTSTRAP.md b/SPEC/BOOTSTRAP.md index 82ba53011..b9566c950 100644 --- a/SPEC/BOOTSTRAP.md +++ b/SPEC/BOOTSTRAP.md @@ -14,27 +14,99 @@ > Add a peer address to the bootstrap list -##### `ipfs.bootstrap.add(addr, [options], [callback])` +##### `ipfs.bootstrap.add(addr, [options])` - `addr` is a [multiaddr](https://github.com/multiformats/js-multiaddr) to a peer node - `options.default` if true, add the default peers to the list -- `callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res.Peers` is an array of added addresses. + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains an array with all the added addresses | + +example of the returned object: + +```JavaScript +{ + Peers: [address1, address2, ...] +} +``` + +**Example:** + +```JavaScript +const validIp4 = '/ip4/104....9z' + +const res = await ipfs.bootstrap.add(validIp4) +console.log(res.Peers) +// Logs: +// ['/ip4/104....9z'] +``` + +A great source of [examples][] can be found in the tests for this API. #### `bootstrap.list` > List all peer addresses in the bootstrap list -##### `ipfs.bootstrap.list([callback])`` +##### `ipfs.bootstrap.list()` + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains an array with all the bootstrap addresses | -- `callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res.Peers` is an array of addresses. +example of the returned object: +```JavaScript +{ + Peers: [address1, address2, ...] +} +``` + +**Example:** + +```JavaScript +const res = await ipfs.bootstrap.list() +console.log(res.Peers) +// Logs: +// [address1, address2, ...] +``` + +A great source of [examples][] can be found in the tests for this API. #### `bootstrap.rm` > Remove a peer address from the bootstrap list -##### `ipfs.bootstrap.rm(peer, [options], [callback])` +##### `ipfs.bootstrap.rm(peer, [options])` - `addr` is a [multiaddr](https://github.com/multiformats/js-multiaddr) to a peer node - `options.all` if true, remove all peers from the list -- `callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res.Peers` is an array of removed addresses. + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains an array with all the removed addresses | + +```JavaScript +{ + Peers: [address1, address2, ...] +} +``` + +**Example:** + +```JavaScript +const res = await ipfs.bootstrap.rm(null, { all: true }) +console.log(res.Peers) +// Logs: +// [address1, address2, ...] +``` + +A great source of [examples][] can be found in the tests for this API. + +[examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/bootstrap diff --git a/SPEC/CONFIG.md b/SPEC/CONFIG.md index 68caee4e1..725a59d47 100644 --- a/SPEC/CONFIG.md +++ b/SPEC/CONFIG.md @@ -10,23 +10,21 @@ > Returns the currently being used config. If the daemon is off, it returns the stored config. -##### `ipfs.config.get([key], [callback])` +##### `ipfs.config.get([key])` `key` is the key of the value that should be fetched from the config file. If no key is passed, then the whole config should be returned. `key` should be of type String. -`callback` must follow `function (err, config) {}` signature, where `err` is an error if the operation was not successful and `config` is a JSON object containing the configuration of the IPFS node. +**Returns** -If no callback is passed, a [promise][] is returned +| Type | Description | +| -------- | -------- | +| `Promise` | An object containing the configuration of the IPFS node | **Example:** ```JavaScript -ipfs.config.get((err, config) => { - if (err) { - throw err - } - console.log(config) -}) +const config = await ipfs.config.get() +console.log(config) ``` A great source of [examples][] can be found in the tests for this API. @@ -35,27 +33,25 @@ A great source of [examples][] can be found in the tests for this API. > Adds or replaces a config value. -##### `ipfs.config.set(key, value, [callback])` +##### `ipfs.config.set(key, value)` `key` is the key value that will be added or replaced (in case of the value already). `key` should be of type String. `value` value to be set. -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no callback is passed, a [promise][] is returned +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | Note that this operation will **not** spark the restart of any service, i.e: if a config.replace changes the multiaddrs of the Swarm, Swarm will have to be restarted manually for the changes to take difference. **Example:** ```JavaScript -ipfs.config.set('Discovery.MDNS.Enabled', false, (err) => { - if (err) { - throw err - } - // MDNS Discovery was set to false -}) +await ipfs.config.set('Discovery.MDNS.Enabled', false) +// MDNS Discovery was set to false ``` A great source of [examples][] can be found in the tests for this API. @@ -64,25 +60,23 @@ A great source of [examples][] can be found in the tests for this API. > Adds or replaces a config file. -##### `ipfs.config.replace(config, [callback])` +##### `ipfs.config.replace(config)` `config` is a JSON object that contains the new config. -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no callback is passed, a [promise][] is returned +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | Note that this operation will **not** spark the restart of any service, i.e: if a config.replace changes the multiaddrs of the Swarm, Swarm will have to be restarted manually for the changes to take difference. **Example:** ```JavaScript -ipfs.config.replace(newConfig, (err) => { - if (err) { - throw err - } - // config has been replaced -}) +await ipfs.config.replace(newConfig) +// config has been replaced ``` A great source of [examples][] can be found in the tests for this API. @@ -91,24 +85,22 @@ A great source of [examples][] can be found in the tests for this API. > List available config profiles -##### `ipfs.config.profiles.list([options], [callback])` +##### `ipfs.config.profiles.list([options])` `options` is a object. -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful. -If no callback is passed, a [promise][] is returned +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array with all the available config profiles | **Example:** ```JavaScript -ipfs.config.profiles.list((err, profiles) => { - if (err) { - throw err - } - - profiles.forEach(profile => { - console.info(profile.name, profile.description) - }) +const profiles = await ipfs.config.profiles.list() +profiles.forEach(profile => { + console.info(profile.name, profile.description) }) ``` @@ -118,31 +110,28 @@ A great source of [examples][] can be found in the tests for this API. > Apply a config profile -##### `ipfs.config.profiles.apply(name, [options], [callback])` +##### `ipfs.config.profiles.apply(name, [options])` `name` is a string. Call `config.profiles.list()` for a list of valid profile names. `options` an object that might contain the following values: - `dryRun` is a boolean which if true does not apply the profile -`callback` must follow the `function (err, result) {}` signature, where `err` is an error if the operation was not successful. -If no callback is passed, a [promise][] is returned +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object containing both the `original` and `updated` config | **Example:** ```JavaScript -ipfs.config.profiles.apply('lowpower', (err, diff) => { - if (err) { - throw err - } - - console.info(diff.original) - console.info(diff.updated) -}) +const diff = await ipfs.config.profiles.apply('lowpower') +console.info(diff.original) +console.info(diff.updated) ``` Note that you will need to restart your node for config changes to take effect. A great source of [examples][] can be found in the tests for this API. -[promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise [examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/config diff --git a/SPEC/DAG.md b/SPEC/DAG.md index d93c4a9b2..662020a02 100644 --- a/SPEC/DAG.md +++ b/SPEC/DAG.md @@ -14,7 +14,7 @@ _Explore the DAG API through interactive coding challenges in our ProtoSchool tu > Store an IPLD format node -##### `ipfs.dag.put(dagNode, [options], [callback])` +##### `ipfs.dag.put(dagNode, [options])` - `dagNode` - a DAG node that follows one of the supported IPLD formats. - `options` - a object that might contain the following values: @@ -27,19 +27,21 @@ _Explore the DAG API through interactive coding challenges in our ProtoSchool tu - `format: 'dag-cbor'` - `hashAlg: 'sha2-256'` - **Note** - You should only pass the CID or the format + hashAlg pair and not both -- `callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and CID is the CID generated through the process or the one that was passed -If no `callback` is passed, a [promise][] is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [CID](https://github.com/ipfs/js-cid) instance. The CID generated through the process or the one that was passed | **Example:** ```JavaScript const obj = { simple: 'object' } +const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha3-512' }) -ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha3-512' }, (err, cid) => { - console.log(cid.toBaseEncodedString()) - // zBwWX9ecx5F4X54WAjmFLErnBT6ByfNxStr5ovowTL7AhaUR98RWvXPS1V3HqV1qs3r5Ec5ocv7eCdbqYQREXNUfYNuKG -}) +console.log(cid.toBaseEncodedString()) +// zBwWX9ecx5F4X54WAjmFLErnBT6ByfNxStr5ovowTL7AhaUR98RWvXPS1V3HqV1qs3r5Ec5ocv7eCdbqYQREXNUfYNuKG ``` A great source of [examples][] can be found in the tests for this API. @@ -48,7 +50,7 @@ A great source of [examples][] can be found in the tests for this API. > Retrieve an IPLD format node -##### `ipfs.dag.get(cid, [path], [options], [callback])` +##### `ipfs.dag.get(cid, [path], [options])` - `cid` - can be one of the following: - a [CID](https://github.com/ipfs/js-cid) instance. @@ -58,13 +60,17 @@ A great source of [examples][] can be found in the tests for this API. - `options` - a object that might contain the following values: - `localResolve` - bool - if set to true, it will avoid resolving through different objects. -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful and `result` is an object containing: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object representing an IPLD format node | + +the returned object contains: - `value` - the value or node that was fetched during the get operation. - `remainderPath` - The remainder of the Path that the node was unable to resolve or what was left in a localResolve scenario. -If no `callback` is passed, a [promise][] is returned. - **Example:** ```JavaScript @@ -78,35 +84,31 @@ const obj = { } } -ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' }, (err, cid) => { - console.log(cid.toBaseEncodedString()) - // zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5 -}) +const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' }) +console.log(cid.toBaseEncodedString()) +// zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5 -function errOrLog(err, result) { - if (err) { - console.error('error: ' + err) - } else { - console.log(result.value) - } +async function getAndLog(cid) { + const result = await ipfs.dag.get(cid) + console.log(result.value) } -ipfs.dag.get('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/a', errOrLog) +await getAndLog('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/a') // Logs: // 1 -ipfs.dag.get('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/b', errOrLog) +await getAndLog('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/b') // Logs: // [1, 2, 3] -ipfs.dag.get('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/c', errOrLog) +await getAndLog('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/c') // Logs: // { // ca: [5, 6, 7], // cb: 'foo' // } -ipfs.dag.get('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/c/ca/1', errOrLog) +await getAndLog('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5/c/ca/1') // Logs: // 6 ``` @@ -117,7 +119,7 @@ A great source of [examples][] can be found in the tests for this API. > Enumerate all the entries in a graph -##### `ipfs.dag.tree(cid, [path], [options], [callback])` +##### `ipfs.dag.tree(cid, [path], [options])` - `cid` - can be one of the following: - a [CID](https://github.com/ipfs/js-cid) instance. @@ -127,9 +129,11 @@ A great source of [examples][] can be found in the tests for this API. - `options` - a object that might contain the following values: - `recursive` - bool - if set to true, it will follow the links and continuously run tree on them, returning all the paths in the graph. -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful and `result` is an Array with the paths passed. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array with the paths passed | **Example:** @@ -144,20 +148,12 @@ const obj = { } } -ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' }, (err, cid) => { - console.log(cid.toBaseEncodedString()) - // zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5 -}) - -function errOrLog(err, result) { - if (err) { - console.error('error: ' + err) - } else { - console.log(result) - } -} +const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' }) +console.log(cid.toBaseEncodedString()) +// zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5 -ipfs.dag.tree('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5', errOrLog) +const result = await ipfs.dag.tree('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5') +console.log(result) // Logs: // a // b diff --git a/SPEC/DHT.md b/SPEC/DHT.md index 8d449e08a..05191d547 100644 --- a/SPEC/DHT.md +++ b/SPEC/DHT.md @@ -11,24 +11,25 @@ > Retrieve the Peer Info of a reachable node in the network. -##### `ipfs.dht.findPeer(peerId, [callback])` +##### `ipfs.dht.findPeer(peerId)` Where `peerId` is a IPFS/libp2p Id from [PeerId](https://github.com/libp2p/js-peer-id) type. -`callback` must follow `function (err, peerInfo) {}` signature, where `err` is an error if the operation was not successful. `peerInfo` is an object of type `PeerInfo`. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An object type [`PeerInfo`](https://github.com/libp2p/js-peer-info) | **Example:** ```JavaScript var id = PeerId.create() -ipfs.dht.findPeer(id, function (err, peerInfo) { - // peerInfo will contain the multiaddrs of that peer - const id = peerInfo.id - const addrs = peerInfo.multiaddrs -}) +const peerInfo = await ipfs.dht.findPeer(id) +// peerInfo will contain the multiaddrs of that peer +const id = peerInfo.id +const addrs = peerInfo.multiaddrs ``` A great source of [examples][] can be found in the tests for this API. @@ -37,7 +38,7 @@ A great source of [examples][] can be found in the tests for this API. > Retrieve the providers for content that is addressed by an hash. -##### `ipfs.dht.findProvs(hash, [options], [callback])` +##### `ipfs.dht.findProvs(hash, [options])` Where `hash` is a multihash. @@ -45,16 +46,26 @@ Where `hash` is a multihash. - `timeout` - a maximum timeout in milliseconds - `maxNumProviders` - a maximum number of providers to find -`callback` must follow `function (err, peerInfos) {}` signature, where `err` is an error if the operation was not successful. `peerInfos` is an array of type `[PeerInfo]`. Each entry of this array is composed by the peerId, as well as an array with its adresses. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of type [`PeerInfo`](https://github.com/libp2p/js-peer-info) | -If no `callback` is passed, a promise is returned. +each entry of the returned array is composed by the peerId, as well as an array with its adresses. **Example:** ```JavaScript -ipfs.dht.findProvs(multihash, function (err, res) {}) +const provs = await ipfs.dht.findProvs(multihash) +provs.forEach(prov => { + console.log(prov.id.toB58String()) +}) -ipfs.dht.findProvs(multihash, { timeout: 4000 }, function (err, res) {}) +const provs2 = await ipfs.dht.findProvs(multihash, { timeout: 4000 }) +provs2.forEach(prov => { + console.log(prov.id.toB58String()) +}) ``` A great source of [examples][] can be found in the tests for this API. @@ -63,18 +74,20 @@ A great source of [examples][] can be found in the tests for this API. > Retrieve a value from DHT -##### `ipfs.dht.get(key, [callback])` +##### `ipfs.dht.get(key)` Where `key` is a Buffer. -`callback` must follow `function (err, value) {}` signature, where `err` is an error if the operation was not successful. `value` is the value that was stored under that key. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | The value that was stored under that key | **Example:** ```JavaScript -ipfs.dht.get(key, function (err, value) {}) +const value = await ipfs.dht.get(key) ``` A great source of [examples][] can be found in the tests for this API. @@ -83,18 +96,20 @@ A great source of [examples][] can be found in the tests for this API. > Announce to the network that you are providing given values. -##### `ipfs.dht.provide(cid, [callback])` +##### `ipfs.dht.provide(cid)` Where `cid` is a CID or array of CIDs. -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.dht.provide(cid, function (err) {}) +await ipfs.dht.provide(cid) ``` A great source of [examples][] can be found in the tests for this API. @@ -103,18 +118,20 @@ A great source of [examples][] can be found in the tests for this API. > Store a value on the DHT -##### `ipfs.dht.put(key, value, [callback])` +##### `ipfs.dht.put(key, value)` Where `key` is a Buffer and `value` is a Buffer. -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.dht.put(key, value, function (err) {}) +await ipfs.dht.put(key, value) ``` A great source of [examples][] can be found in the tests for this API. @@ -123,20 +140,25 @@ A great source of [examples][] can be found in the tests for this API. > Queries the network for the 'closest peers' to a given key. 'closest' is defined by the rules of the underlying Peer Routing mechanism. -##### `ipfs.dht.query(peerId, [callback])` +##### `ipfs.dht.query(peerId)` Where `peerId` is a IPFS/libp2p Id of type [PeerId](https://github.com/libp2p/js-peer-id). -`callback` must follow `function (err, peerInfos) {}` signature, where `err` is an error if the operation was not successful. `peerInfos` is an array of objects of type [PeerInfo](https://github.com/libp2p/js-peer-info) +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects of type [PeerInfo](https://github.com/libp2p/js-peer-info) | **Example:** ```JavaScript const id = PeerId.create() -ipfs.dht.query(id, function (err, peerInfos) { +const peerInfos = await ipfs.dht.query(id) + +peerInfos.forEach(p => { + console.log(p.id.toB58String()) }) ``` diff --git a/SPEC/FILES.md b/SPEC/FILES.md index 1f0cd6c47..e5cfda957 100644 --- a/SPEC/FILES.md +++ b/SPEC/FILES.md @@ -42,7 +42,7 @@ _Explore the Mutable File System through interactive coding challenges in our [P > Add files and data to IPFS. -##### `ipfs.add(data, [options], [callback])` +##### `ipfs.add(data, [options])` Where `data` may be: @@ -53,8 +53,8 @@ Where `data` may be: - an array of objects, each of the form: ```JavaScript { - path: '/tmp/myfile.txt', // The file path - content: // A Buffer, Readable Stream, Pull Stream or File with the contents of the file + path: '/tmp/myfile.txt', // The file path + content: // A Buffer, Readable Stream, Pull Stream or File with the contents of the file } ``` If no `content` is passed, then the path is treated as an empty directory @@ -83,7 +83,13 @@ If no `content` is passed, then the path is treated as an empty directory [Trickle definition from go-ipfs documentation](https://godoc.org/github.com/ipsn/go-ipfs/gxlibs/github.com/ipfs/go-unixfs/importer/trickle). - wrapWithDirectory (boolean, default false): adds a wrapping node around the content. -`callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res` will be an array of: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects describing the added data | + +an array of objects is returned, each of the form: ```JavaScript { @@ -93,8 +99,6 @@ If no `content` is passed, then the path is treated as an empty directory } ``` -If no `callback` is passed, a promise is returned. - **Example:** In the browser, assuming `ipfs = new Ipfs(...)`: @@ -236,7 +240,7 @@ pull( > Add files or entire directories from the FileSystem to IPFS -##### `ipfs.addFromFs(path, [options], [callback])` +##### `ipfs.addFromFs(path, [options])` Reads a file or folder from `path` on the filesystem and adds it to IPFS. @@ -245,63 +249,88 @@ Options: - **ignore**: To exclude file globs from the directory, use option `{ ignore: ['ignore/this/folder/**', 'and/this/file'] }`. - **hidden**: hidden/dot files (files or folders starting with a `.`, for example, `.git/`) are not included by default. To add them, use the option `{ hidden: true }`. -```JavaScript -ipfs.addFromFs('path/to/a/folder', { recursive: true , ignore: ['subfolder/to/ignore/**']}, (err, result) => { - if (err) { throw err } - console.log(result) -}) -``` +**Returns** -`result` is an array of objects describing the files that were added, such as: +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects describing the files that were added | + +an array of objects is returned, each of the form: ```js -[ - { - path: 'test-folder', - hash: 'QmRNjDeKStKGTQXnJ2NFqeQ9oW23WcpbmvCVrpDHgDg3T6', - size: 2278 - }, - // ... -] +{ + path: 'test-folder', + hash: 'QmRNjDeKStKGTQXnJ2NFqeQ9oW23WcpbmvCVrpDHgDg3T6', + size: 123 +} +``` + +**Example** + +```JavaScript +const results = await ipfs.addFromFs('path/to/a/folder', { recursive: true , ignore: ['subfolder/to/ignore/**']}) +console.log(results) ``` #### `addFromURL` > Add a file from a URL to IPFS -##### `ipfs.addFromURL(url, [callback])` +##### `ipfs.addFromURL(url, [options])` + +`options` is an optional object that argument that might include the same keys of [`ipfs.add(data, [options])`](#add) + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object describing the added file | + +**Example** ```JavaScript -ipfs.addFromURL('http://example.com/', (err, result) => { - if (err) { - throw err - } - console.log(result) -}) +const result = await ipfs.addFromURL('http://example.com/') +console.log('result') ``` #### `addFromStream` > Add a file from a stream to IPFS -##### `ipfs.addFromStream(stream, [callback])` +##### `ipfs.addFromStream(stream, [options])` This is very similar to `ipfs.add({ path:'', content: stream })`. It is like the reverse of cat. +`options` is an optional object that argument that might include the same keys of [`ipfs.add(data, [options])`](#add) + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects describing the added data | + +an array of objects is returned, each of the form: + ```JavaScript -ipfs.addFromStream(, (err, result) => { - if (err) { - throw err - } - console.log(result) -}) +{ + path: '/tmp/myfile.txt', + hash: 'QmHash', // base58 encoded multihash + size: 123 +} +``` + +**Example** + +```JavaScript +const result = await ipfs.addFromStream() +console.log(result) ``` #### `cat` > Returns a file addressed by a valid IPFS Path. -##### `ipfs.cat(ipfsPath, [options], [callback])` +##### `ipfs.cat(ipfsPath, [options])` `ipfsPath` can be of type: @@ -318,20 +347,17 @@ ipfs.addFromStream(, (err, result) => { - `offset` is an optional byte offset to start the stream at - `length` is an optional number of bytes to read from the stream -`callback` must follow `function (err, file) {}` signature, where `err` is an error if the operation was not successful and `file` is a [Buffer][b] +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A [`Buffer`][b] with the contents of `path` | **Example:** ```JavaScript -ipfs.cat(ipfsPath, function (err, file) { - if (err) { - throw err - } - - console.log(file.toString('utf8')) -}) +const file = await ipfs.cat(ipfsPath) { +console.log(file.toString('utf8')) ``` A great source of [examples][] can be found in the tests for this API. @@ -357,8 +383,13 @@ A great source of [examples][] can be found in the tests for this API. - `offset` is an optional byte offset to start the stream at - `length` is an optional number of bytes to read from the stream -Returns a [Readable Stream][rs] with the contents of the file. +**Returns** + +| Type | Description | +| -------- | -------- | +| `ReadableStream` | A [Readable Stream][rs] with the contents of the file | +**Example** ```JavaScript const stream = ipfs.catReadableStream(ipfsPath) @@ -387,7 +418,13 @@ A great source of [examples][] can be found in the tests for this API. - `offset` is an optional byte offset to start the stream at - `length` is an optional number of bytes to read from the stream -Returns a [Pull Stream][ps] with the contents of the file. +**Returns** + +| Type | Description | +| -------- | -------- | +| `PullStream` | A [Pull Stream][ps] with the contents of the file | + +**Example** ```JavaScript const stream = ipfs.catPullStream(ipfsPath) @@ -401,7 +438,7 @@ A great source of [examples][] can be found in the tests for this API. > Fetch a file or an entire directory tree from IPFS that is addressed by a valid IPFS Path. -##### `ipfs.get(ipfsPath, [callback])` +##### `ipfs.get(ipfsPath)` ipfsPath can be of type: @@ -413,7 +450,13 @@ ipfsPath can be of type: - '/ipfs/QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' - 'QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' -`callback` must follow `function (err, files) {}` signature, where `err` is an error if the operation was not successful. `files` is an array containing objects of the following form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects representing the files | + +an array of objects is returned, each of the form: ```js { @@ -424,18 +467,15 @@ ipfsPath can be of type: Here, each `path` corresponds to the name of a file, and `content` is a regular Readable stream with the raw contents of that file. -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript const validCID = 'QmQ2r6iMNpky5f1m4cnm3Yqw8VSvjuKpTcK1X7dBR1LkJF' -ipfs.get(validCID, function (err, files) { - files.forEach((file) => { - console.log(file.path) - console.log(file.content.toString('utf8')) - }) +const files = await ipfs.get(validCID) +files.forEach((file) => { + console.log(file.path) + console.log(file.content.toString('utf8')) }) ``` @@ -457,7 +497,13 @@ ipfsPath can be of type: - '/ipfs/QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' - 'QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' -It returns a [Readable Stream][rs] in [Object mode](https://nodejs.org/api/stream.html#stream_object_mode) that will yield objects of the form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `ReadableStream` | A [Readable Stream][rs] in [Object mode](https://nodejs.org/api/stream.html#stream_object_mode) that will yield objects | + +the yielded objects are of the form: ```js { @@ -503,7 +549,13 @@ ipfsPath can be of type: - '/ipfs/QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' - 'QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' -It returns a [Pull Stream][os] that will yield objects of the form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `PullStream` | A [Pull Stream][ps] that will yield objects | + +the yielded objects are of the form: ```js { @@ -540,7 +592,7 @@ A great source of [examples][] can be found in the tests for this API. > Lists a directory from IPFS that is addressed by a valid IPFS Path. -##### `ipfs.ls(ipfsPath, [callback])` +##### `ipfs.ls(ipfsPath)` > **Note:** ipfs.files.ls is currently only for MFS directories. The goal is to converge both functionalities. @@ -554,7 +606,13 @@ ipfsPath can be of type: - '/ipfs/QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' - 'QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' -`callback` must follow `function (err, files) {}` signature, where `err` is an error if the operation was not successful. `files` is an array containing objects of the following form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects representing the files | + +an array of objects is returned, each of the form: ```js { @@ -567,17 +625,14 @@ ipfsPath can be of type: } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript const validCID = 'QmQ2r6iMNpky5f1m4cnm3Yqw8VSvjuKpTcK1X7dBR1LkJF' -ipfs.ls(validCID, function (err, files) { - files.forEach((file) => { - console.log(file.path) - }) +const files = await ipfs.ls(validCID) +files.forEach((file) => { + console.log(file.path) }) ``` @@ -601,7 +656,13 @@ ipfsPath can be of type: - '/ipfs/QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' - 'QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' -It returns a [Readable Stream][rs] in [Object mode](https://nodejs.org/api/stream.html#stream_object_mode) that will yield objects of the form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `ReadableStream` | A [Readable Stream][rs] in [Object mode](https://nodejs.org/api/stream.html#stream_object_mode) that will yield objects | + +the yielded objects are of the form: ```js { @@ -648,7 +709,13 @@ ipfsPath can be of type: - '/ipfs/QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' - 'QmXEmhrMpbVvTh61FNAxP9nU7ygVtyvZA8HZDUaqQCAb66/a.txt' -It returns a [Pull Stream][os] that will yield objects of the form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `PullStream` | A [Pull Stream][ps] that will yield objects | + +the yielded objects are of the form: ```js { @@ -693,7 +760,7 @@ The Mutable File System (MFS) is a virtual file system on top of IPFS that expos > Copy files. -##### `ipfs.files.cp(...from, to, [options], [callback])` +##### `ipfs.files.cp(...from, to, [options])` Where: @@ -707,7 +774,6 @@ Where: - `format` is what type of nodes to write any newly created directories as (default: `dag-pb`) - `hashAlg` is which algorithm to use when creating CIDs for newly created directories. (default: `sha2-256`) [The list of all possible values]( https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343) - `flush` is a Boolean value to decide whether or not to immediately flush MFS changes to disk (default: true) -- `callback` is an optional function with the signature `function (error) {}`, where `error` may be an Error that occurs if the operation is not successful If `from` has multiple values then `to` must be a directory. @@ -717,38 +783,30 @@ If `from` has a single value and `to` exists and is a file, `from` must be a fil If `from` is an IPFS path, and an MFS path exists with the same name, the IPFS path will be chosen. -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript // To copy a file -ipfs.files.cp('/src-file', '/dst-file', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.cp('/src-file', '/dst-file') // To copy a directory -ipfs.files.cp('/src-dir', '/dst-dir', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.cp('/src-dir', '/dst-dir') // To copy multiple files to a directory -ipfs.files.cp('/src-file1', '/src-file2', '/dst-dir', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.cp('/src-file1', '/src-file2', '/dst-dir') ``` #### `files.mkdir` > Make a directory. -##### `ipfs.files.mkdir(path, [options], [callback])` +##### `ipfs.files.mkdir(path, [options])` Where: @@ -758,25 +816,24 @@ Where: - `format` is what type of nodes to write any newly created directories as (default: `dag-pb`) - `hashAlg` is which algorithm to use when creating CIDs for newly created directories (default: `sha2-256`) [The list of all possible values]( https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343) - `flush` is a Boolean value to decide whether or not to immediately flush MFS changes to disk (default: true) -- `callback` is an optional function with the signature `function (error) {}`, where `error` may be an Error that occurs if the operation is not successful -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.files.mkdir('/my/beautiful/directory', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.mkdir('/my/beautiful/directory') ``` #### `files.stat` > Get file or directory status. -##### `ipfs.files.stat(path, [options], [callback])` +##### `ipfs.files.stat(path, [options])` Where: @@ -789,25 +846,29 @@ Where: - `size` is a Boolean value to return only the size (default: false) - `withLocal` is a Boolean value to compute the amount of the dag that is local, and if possible the total size (default: false) - `cidBase` is which number base to use to format hashes - e.g. `base32`, `base64` etc (default: `base58btc`) -- `callback` is an optional function with the signature `function (error, stats) {}`, where `error` may be an Error that occurs if the operation is not successful and `stats` is an Object with the following keys: - - `hash` is a string with the hash - - `size` is an integer with the file size in Bytes - - `cumulativeSize` is an integer with the size of the DAGNodes making up the file in Bytes - - `type` is a string that can be either `directory` or `file` - - `blocks` if `type` is `directory`, this is the number of files in the directory. If it is `file` it is the number of blocks that make up the file - - `withLocality` is a boolean to indicate if locality information is present - - `local` is a boolean to indicate if the queried dag is fully present locally - - `sizeLocal` is an integer indicating the cumulative size of the data present locally +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object containing the file/directory status | -If no `callback` is passed, a promise is returned. +the returned object has the following keys: + +- `hash` is a string with the hash +- `size` is an integer with the file size in Bytes +- `cumulativeSize` is an integer with the size of the DAGNodes making up the file in Bytes +- `type` is a string that can be either `directory` or `file` +- `blocks` if `type` is `directory`, this is the number of files in the directory. If it is `file` it is the number of blocks that make up the file +- `withLocality` is a boolean to indicate if locality information is present +- `local` is a boolean to indicate if the queried dag is fully present locally +- `sizeLocal` is an integer indicating the cumulative size of the data present locally **Example:** ```JavaScript -ipfs.files.stat('/file.txt', (err, stats) => { - console.log(stats) -}) +const stats = await ipfs.files.stat('/file.txt') +console.log(stats) // { // hash: 'QmXmJBmnYqXVuicUfn9uDCC8kxCEEzQpsAbeq1iJvLAmVs', @@ -822,47 +883,38 @@ ipfs.files.stat('/file.txt', (err, stats) => { > Remove a file or directory. -##### `ipfs.files.rm(...paths, [options], [callback])` +##### `ipfs.files.rm(...paths, [options])` Where: - `paths` are one or more paths to remove - `options` is an optional Object that might contain the following keys: - `recursive` is a Boolean value to decide whether or not to remove directories recursively (default: false) -- `callback` is an optional function with the signature `function (error) {}`, where `error` may be an Error that occurs if the operation is not successful -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript // To remove a file -ipfs.files.rm('/my/beautiful/file.txt', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.rm('/my/beautiful/file.txt') // To remove multiple files -ipfs.files.rm('/my/beautiful/file.txt', '/my/other/file.txt', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.rm('/my/beautiful/file.txt', '/my/other/file.txt') // To remove a directory -ipfs.files.rm('/my/beautiful/directory', { recursive: true }, (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.rm('/my/beautiful/directory', { recursive: true }) ``` #### `files.read` > Read a file into a [`Buffer`][b]. -##### `ipfs.files.read(path, [options], [callback])` +##### `ipfs.files.read(path, [options])` Where: @@ -873,18 +925,20 @@ Where: - `options` is an optional Object that might contain the following keys: - `offset` is an Integer with the byte offset to begin reading from (default: 0) - `length` is an Integer with the maximum number of bytes to read (default: Read to the end of stream) -- `callback` is an optional function with the signature `function (error, buffer) {}`, where `error` may be an Error that occurs if the operation is not successful and `buffer` is a [`Buffer`][b] with the contents of `path` -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [`Buffer`][b] with the contents of `path` | N.b. this method is likely to result in high memory usage, you should use [files.readReadableStream](#filesreadreadablestream) or [files.readPullStream](#filesreadpullstream) instead where possible. **Example:** ```JavaScript -ipfs.files.read('/hello-world', (error, buf) => { - console.log(buf.toString('utf8')) -}) +const buf = await ipfs.files.read('/hello-world') +console.log(buf.toString('utf8')) // Hello, World! ``` @@ -905,7 +959,11 @@ Where: - `offset` is an Integer with the byte offset to begin reading from (default: 0) - `length` is an Integer with the maximum number of bytes to read (default: Read to the end of stream) -Returns a [`ReadableStream`][rs] with the contents of `path`. +**Returns** + +| Type | Description | +| -------- | -------- | +| `ReadableStream` | A [Readable Stream][rs] with the contents of `path` | **Example:** @@ -932,7 +990,11 @@ Where: - `offset` is an Integer with the byte offset to begin reading from (default: 0) - `length` is an Integer with the maximum number of bytes to read (default: Read to the end of stream) -Returns a [`PullStream`][ps] with the contents of `path`. +**Returns** + +| Type | Description | +| -------- | -------- | +| `PullStream` | A [`PullStream`][ps] with the contents of `path` | **Example:** @@ -950,7 +1012,7 @@ pull( > Write to a file. -##### `ipfs.files.write(path, content, [options], [callback])` +##### `ipfs.files.write(path, content, [options])` Where: @@ -969,23 +1031,24 @@ Where: - `length` is an Integer with the maximum number of bytes to read (default: Read all bytes from `content`) - `rawLeaves`: if true, DAG leaves will contain raw file data and not be wrapped in a protobuf (boolean, default false) - `cidVersion`: the CID version to use when storing the data (storage keys are based on the CID, including its version) (integer, default 0) -- `callback` is an optional function with the signature `function (error) {}`, where `error` may be an Error that occurs if the operation is not successful -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.files.write('/hello-world', Buffer.from('Hello, world!'), (err) => { - console.log(err) -}) +await ipfs.files.write('/hello-world', Buffer.from('Hello, world!')) ``` #### `files.mv` > Move files. -##### `ipfs.files.mv(...from, to, [options], [callback])` +##### `ipfs.files.mv(...from, to, [options])` Where: @@ -996,7 +1059,6 @@ Where: - `format` is what type of nodes to write any newly created directories as (default: `dag-pb`) - `hashAlg` is which algorithm to use when creating CIDs for newly created directories (default: `sha2-256`) [The list of all possible values]( https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343) - `flush` is a Boolean value to decide whether or not to immediately flush MFS changes to disk (default: true) -- `callback` is an optional function with the signature `function (error) {}`, where `error` may be an Error that occurs if the operation is not successful If `from` has multiple values then `to` must be a directory. @@ -1008,58 +1070,49 @@ If `from` is an IPFS path, and an MFS path exists with the same name, the IPFS p All values of `from` will be removed after the operation is complete unless they are an IPFS path. -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.files.mv('/src-file', '/dst-file', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.mv('/src-file', '/dst-file') -ipfs.files.mv('/src-dir', '/dst-dir', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.mv('/src-dir', '/dst-dir') -ipfs.files.mv('/src-file1', '/src-file2', '/dst-dir', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.mv('/src-file1', '/src-file2', '/dst-dir') ``` #### `files.flush` > Flush a given path's data to the disk -##### `ipfs.files.flush([...paths], [callback])` +##### `ipfs.files.flush([...paths])` Where: - `paths` are optional string paths to flush (default: `/`) -- `callback` is an optional function with the signature `function (error) {}`, where `error` may be an Error that occurs if the operation is not successful -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If successfully copied. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.files.flush('/', (err) => { - if (err) { - console.error(err) - } -}) +await ipfs.files.flush('/') ``` #### `files.ls` > List directories in the local mutable namespace. -##### `ipfs.files.ls([path], [options], [callback])` +##### `ipfs.files.ls([path], [options])` Where: @@ -1071,22 +1124,27 @@ Where: - `long` is a Boolean value to decide whether or not to populate `type`, `size` and `hash` (default: false) - `cidBase` is which number base to use to format hashes - e.g. `base32`, `base64` etc (default: `base58btc`) - `sort` is a Boolean value. If true entries will be sorted by filename (default: false) -- `callback` is an optional function with the signature `function (error, files) {}`, where `error` may be an Error that occurs if the operation is not successful and `files` is an array containing Objects that contain the following keys: - - `name` which is the file's name - - `type` which is the object's type (`directory` or `file`) - - `size` the size of the file in bytes - - `hash` the hash of the file +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects representing the files | -If no `callback` is passed, a promise is returned. +each object contains the following keys: + +- `name` which is the file's name +- `type` which is the object's type (`directory` or `file`) +- `size` the size of the file in bytes +- `hash` the hash of the file **Example:** ```JavaScript -ipfs.files.ls('/screenshots', function (err, files) { - files.forEach((file) => { - console.log(file.name) - }) +const files = await ipfs.files.ls('/screenshots') + +files.forEach((file) => { + console.log(file.name) }) // 2018-01-22T18:08:46.775Z.png @@ -1111,12 +1169,18 @@ Where: - `long` is a Boolean value to decide whether or not to populate `type`, `size` and `hash` (default: false) - `cidBase` is which number base to use to format hashes - e.g. `base32`, `base64` etc (default: `base58btc`) -It returns a [Readable Stream][rs] in [Object mode](https://nodejs.org/api/stream.html#stream_object_mode) that will yield objects containing the following keys: +**Returns** - - `name` which is the file's name - - `type` which is the object's type (`directory` or `file`) - - `size` the size of the file in bytes - - `hash` the hash of the file +| Type | Description | +| -------- | -------- | +| `ReadableStream` | A [Readable Stream][rs] in [Object mode](https://nodejs.org/api/stream.html#stream_object_mode) that will yield objects | + +the yielded objects contain the following keys: + +- `name` which is the file's name +- `type` which is the object's type (`directory` or `file`) +- `size` the size of the file in bytes +- `hash` the hash of the file **Example:** @@ -1147,7 +1211,13 @@ Where: - `long` is a Boolean value to decide whether or not to populate `type`, `size` and `hash` (default: false) - `cidBase` is which number base to use to format hashes - e.g. `base32`, `base64` etc (default: `base58btc`) -It returns a [Pull Stream][os] that will yield objects containing the following keys: +**Returns** + +| Type | Description | +| -------- | -------- | +| `PullStream` | A [Pull Stream][os] that will yield objects | + +the yielded objects contain the following keys: - `name` which is the file's name - `type` which is the object's type (`directory` or `file`) diff --git a/SPEC/KEY.md b/SPEC/KEY.md index b65e606f1..dceddb1c6 100644 --- a/SPEC/KEY.md +++ b/SPEC/KEY.md @@ -11,7 +11,7 @@ > Generate a new key -##### `ipfs.key.gen(name, options, [callback])` +##### `ipfs.key.gen(name, options)` Where: @@ -20,29 +20,40 @@ Where: - 'type' - the key type, one of 'rsa' - 'size' - the key size in bits -`callback` must follow `function (err, key) {}` signature, where `err` is an Error if the operation was not successful. `key` is an object that describes the key; `name` and `id`. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An object that describes the key; `name` and `id` | **Example:** ```JavaScript -ipfs.key.gen('my-key', { +const key = await ipfs.key.gen('my-key', { type: 'rsa', size: 2048 -}, (err, key) => console.log(key)) +}) +console.log(key) // { id: 'QmYWqAFvLWb2G5A69JGXui2JJXzaHXiUEmQkQgor6kNNcJ', // name: 'my-key' } ``` +A great source of [examples][] can be found in the tests for this API. + #### `key.list` > List all the keys -##### `ipfs.key.list([callback])` +##### `ipfs.key.list()` + +**Returns** -`callback` must follow `function (err, keys) {}` signature, where `err` is an Error if the operation was not successful. `keys` is an array of: +| Type | Description | +| -------- | -------- | +| `Promise` | An array representing all the keys | + +example of the returned array: ```js { @@ -51,13 +62,12 @@ ipfs.key.gen('my-key', { } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.key.list((err, keys) => console.log(keys)) +const keys = await ipfs.key.list() +console.log(keys) // [ // { id: 'QmTe4tuceM2sAmuZiFsJ9tmAopA8au71NabBDdpPYDjxAb', // name: 'self' }, @@ -66,16 +76,24 @@ ipfs.key.list((err, keys) => console.log(keys)) // ] ``` +A great source of [examples][] can be found in the tests for this API. + #### `key.rm` > Remove a key -##### `ipfs.key.rm(name, [callback])` +##### `ipfs.key.rm(name)` Where: - `name` is the local name for the key -`callback` must follow `function (err, key) {}` signature, where `err` is an Error if the operation was not successful. `key` is an object that describes the removed key: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that describes the removed key | + +example of the returned object: ```js { @@ -84,63 +102,72 @@ Where: } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.key.rm('my-key', (err, key) => console.log(key)) +const key = await ipfs.key.rm('my-key') +console.log(key) // { id: 'QmWETF5QvzGnP7jKq5sPDiRjSM2fzwzNsna4wSBEzRzK6W', // name: 'my-key' } ``` +A great source of [examples][] can be found in the tests for this API. + #### `key.rename` > Rename a key -##### `ipfs.key.rename(oldName, newName, [callback])` +##### `ipfs.key.rename(oldName, newName)` Where: - `oldName` is the local name for the key - `newName` a new name for key -`callback` must follow `function (err, key) {}` signature, where `err` is an Error if the operation was not successful. `key` is an object that describes the renamed key. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An object that describes the renamed key | **Example:** ```JavaScript -ipfs.key.rename('my-key', 'my-new-key', (err, key) => console.log(key)) +const key = await ipfs.key.rename('my-key', 'my-new-key') +console.log(key) // { id: 'Qmd4xC46Um6s24MradViGLFtMitvrR4SVexKUgPgFjMNzg', // was: 'my-key', // now: 'my-new-key', // overwrite: false } ``` +A great source of [examples][] can be found in the tests for this API. + #### `key.export` > Export a key in a PEM encoded password protected PKCS #8 ##### Go **NYI** -##### `ipfs.key.export(name, password, [callback])` +##### `ipfs.key.export(name, password)` Where: - `name` is the local name for the key - `password` is the password to protect the key -`callback` must follow `function (err, pem) {}` signature, where `err` is an Error if the operation was not successful. `pem` is the string representation of the key. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | The string representation of the key | **Example:** ```JavaScript -ipfs.key.export('self', 'password', (err, pem) => console.log(pem)) +const pem = await ipfs.key.export('self', 'password') +console.log(pem) // -----BEGIN ENCRYPTED PRIVATE KEY----- // MIIFDTA/BgkqhkiG9w0BBQ0wMjAaBgkqhkiG9w0BBQwwDQQIpdO40RVyBwACAWQw // ... @@ -148,28 +175,37 @@ ipfs.key.export('self', 'password', (err, pem) => console.log(pem)) // -----END ENCRYPTED PRIVATE KEY----- ``` +A great source of [examples][] can be found in the tests for this API. + #### `key.import` > Import a PEM encoded password protected PKCS #8 key ##### Go **NYI** -##### `ipfs.key.import(name, pem, password, [callback])` +##### `ipfs.key.import(name, pem, password)` Where: - `name` is a local name for the key - `pem` is the PEM encoded key - `password` is the password that protects the PEM key -`callback` must follow `function (err, key) {}` signature, where `err` is an Error if the operation was not successful. `key` is an object that describes the new key. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An object that describes the new key | **Example:** ```JavaScript -ipfs.key.import('clone', 'password', (err, key) => console.log(key)) +const key = await ipfs.key.import('clone', 'password') +console.log(key) // { id: 'QmQRiays958UM7norGRQUG3tmrLq8pJdmJarwYSk2eLthQ', // name: 'clone' } ``` + +A great source of [examples][] can be found in the tests for this API. + +[examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/key diff --git a/SPEC/MISCELLANEOUS.md b/SPEC/MISCELLANEOUS.md index 8fcccec50..230272410 100644 --- a/SPEC/MISCELLANEOUS.md +++ b/SPEC/MISCELLANEOUS.md @@ -13,21 +13,19 @@ > Returns the identity of the Peer -##### `ipfs.id([callback])` +##### `ipfs.id()` -`callback` must follow `function (err, identity) {}` signature, where `err` is an error if the operation was not successful. `identity` is an object with the Peer identity. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An object with the Peer identity | **Example:** ```JavaScript -ipfs.id(function (err, identity) { - if (err) { - throw err - } - console.log(identity) -}) +const identity = await ipfs.id() +console.log(identity) ``` A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/master/src/miscellaneous/id.js) can be found in the tests for this API. @@ -36,21 +34,19 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/ma > Returns the implementation version -##### `ipfs.version([callback])` +##### `ipfs.version()` -`callback` must follow `function (err, version) {}` signature, where `err` is an error if the operation was not successful. `version` is an object with the version of the implementation, the commit and the Repo. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An object with the version of the implementation, the commit and the Repo | **Example:** ```JavaScript -ipfs.version((err, version) => { - if (err) { - throw err - } - console.log(version) -}) +const version = await ipfs.version() +console.log(version) ``` A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/master/src/miscellaneous/version.js) can be found in the tests for this API. @@ -59,26 +55,24 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/ma > Resolve DNS links -##### `ipfs.dns(domain, [options], [callback])` +##### `ipfs.dns(domain, [options])` Where: - `options` is an optional object argument that might include the following properties: - `recursive` (boolean, default true): resolve until result is not a domain name -- `callback` must follow `function (err, path) {}` signature, where `err` is an error if the operation was not successful. `path` is the IPFS path for that domain. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A string representing the IPFS path for that domain | **Example:** ```JavaScript -ipfs.dns('ipfs.io', (err, path) => { - if (err) { - throw err - } - console.log(path) -}) +const path = await ipfs.dns('ipfs.io') +console.log(path) ``` A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/master/src/miscellaneous/dns.js) can be found in the tests for this API. @@ -87,19 +81,18 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/ma > Stops the IPFS node and in case of talking with an IPFS Daemon, it stops the process. -##### `ipfs.stop([callback])` +##### `ipfs.stop()` -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.stop((err) => { - if (err) { - throw err - } -}) +await ipfs.stop() ``` A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/master/src/miscellaneous/stop.js) can be found in the tests for this API. @@ -108,42 +101,42 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/ma > Send echo request packets to IPFS hosts -##### `ipfs.ping(peerId, [options], [callback])` +##### `ipfs.ping(peerId, [options])` Where: - `peerId` (string) ID of the peer to be pinged. - `options` is an optional object argument that might include the following properties: - `count` (integer, default 10): the number of ping messages to send -- `callback` must follow `function (err, responses) {}` signature, where `err` is an error if the operation was not successful. `responses` is an Array of ping response objects of the form: - ```js - { - success: true, - time: 1234, - text: '' - } - ``` +**Returns** - Note that not all ping response objects are "pongs". A "pong" message can be identified by a truthy `success` property and an empty `text` property. Other ping responses are failures or status updates. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of ping response objects | - If no `callback` is passed, a promise is returned. +an array of objects is returned, each of the form: + +```js +{ + success: true, + time: 1234, + text: '' +} +``` + +Note that not all ping response objects are "pongs". A "pong" message can be identified by a truthy `success` property and an empty `text` property. Other ping responses are failures or status updates. **Example:** ```JavaScript -ipfs.ping('Qmhash', function (err, responses) { - if (err) { - throw err +const responses = await ipfs.ping('Qmhash') +responses.forEach((res) => { + if (res.time) { + console.log(`Pong received: time=${res.time} ms`) + } else { + console.log(res.text) } - - responses.forEach((res) => { - if (res.time) { - console.log(`Pong received: time=${res.time} ms`) - } else { - console.log(res.text) - } - }) }) ``` @@ -153,7 +146,7 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/tree/ma > Stream echo request packets to IPFS hosts -##### `ipfs.pingPullStream(peerId, [options], [callback])` +##### `ipfs.pingPullStream(peerId, [options])` Where: @@ -161,7 +154,13 @@ Where: - `options` is an optional object argument that might include the following properties: - `count` (integer, default 10): the number of ping messages to send -Returns a [`PullStream`][ps] of ping response objects of the form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [`PullStream`][ps] of ping response objects | + +example of the returned objects: ```js { @@ -196,7 +195,7 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/tree/ma > Stream echo request packets to IPFS hosts -##### `ipfs.pingReadableStream(peerId, [options], [callback])` +##### `ipfs.pingReadableStream(peerId, [options])` Where: @@ -204,7 +203,13 @@ Where: - `options` is an optional object argument that might include the following properties: - `count` (integer, default 10): the number of ping messages to send -Returns a [`ReadableStream`][rs] of ping response objects of the form: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [`ReadableStream`][rs] of ping response objects | + +example of the returned objects: ```js { @@ -238,7 +243,7 @@ A great source of [examples](https://github.com/ipfs/interface-ipfs-core/tree/ma There are a number of mutable name protocols that can link among themselves and into IPNS. For example IPNS references can (currently) point at an IPFS object, and DNS links can point at other DNS links, IPNS entries, or IPFS objects. This command accepts any of these identifiers and resolves them to the referenced item. -##### `ipfs.resolve(name, [options], [callback])` +##### `ipfs.resolve(name, [options])` Where: @@ -247,9 +252,11 @@ Where: - `recursive` (boolean, default false): Resolve until the result is an IPFS name - `cidBase` (string): Multibase codec name the CID in the resolved path will be encoded with -`callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res` is a string, the resolved name. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A string representing the resolved name | **Examples:** @@ -258,12 +265,8 @@ Resolve the value of your identity: ```JavaScript const name = '/ipns/QmatmE9msSfkKxoffpHwNLNKgwZG8eT9Bud6YoPab52vpy' -ipfs.resolve(name, (err, res) => { - if (err) { - throw err - } - console.log(res) // /ipfs/Qmcqtw8FfrVSBaRmbWwHxt3AuySBhJLcvmFYi3Lbc4xnwj -}) +const res = await ipfs.resolve(name) +console.log(res) // /ipfs/Qmcqtw8FfrVSBaRmbWwHxt3AuySBhJLcvmFYi3Lbc4xnwj ``` Resolve the value of another name recursively: @@ -278,12 +281,8 @@ const name = '/ipns/QmbCMUZw6JFeZ7Wp9jkzbye3Fzp2GGcPgC3nmeUjfVF87n' // ...which in turn resolves to: // /ipfs/Qmcqtw8FfrVSBaRmbWwHxt3AuySBhJLcvmFYi3Lbc4xnwj -ipfs.resolve(name, { recursive: true }, (err, res) => { - if (err) { - throw err - } - console.log(res) // /ipfs/Qmcqtw8FfrVSBaRmbWwHxt3AuySBhJLcvmFYi3Lbc4xnwj -}) +const res = await ipfs.resolve(name, { recursive: true }) +console.log(res) // /ipfs/Qmcqtw8FfrVSBaRmbWwHxt3AuySBhJLcvmFYi3Lbc4xnwj ``` Resolve the value of an IPFS path: @@ -291,12 +290,8 @@ Resolve the value of an IPFS path: ```JavaScript const name = '/ipfs/QmeZy1fGbwgVSrqbfh9fKQrAWgeyRnj7h8fsHS1oy3k99x/beep/boop' -ipfs.resolve(name, (err, res) => { - if (err) { - throw err - } - console.log(res) // /ipfs/QmYRMjyvAiHKN9UTi8Bzt1HUspmSRD8T8DwxfSMzLgBon1 -}) +const res = await ipfs.resolve(name) +console.log(res) // /ipfs/QmYRMjyvAiHKN9UTi8Bzt1HUspmSRD8T8DwxfSMzLgBon1 ``` A great source of [examples](https://github.com/ipfs/interface-ipfs-core/blob/master/src/miscellaneous/resolve.js) can be found in the tests for this API. diff --git a/SPEC/NAME.md b/SPEC/NAME.md index e9a13eee6..f62847803 100644 --- a/SPEC/NAME.md +++ b/SPEC/NAME.md @@ -10,7 +10,7 @@ > Publish an IPNS name with a given value. -##### `ipfs.name.publish(value, [options], [callback])` +##### `ipfs.name.publish(value, [options])` `value` is a base58 encoded IPFS multihash, such as: `/ipfs/QmbezGequPwcsWo8UL4wDF6a8hYwM1hmbzYv2mnKkEWaUp`. @@ -25,7 +25,13 @@ } ``` -`callback` must follow `function (err, name) {}` signature, where `err` is an error if the operation was not successful. `name` is an object that contains the IPNS hash and the IPFS hash, such as: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains the IPNS hash and the IPFS hash | + +example of the returned object: ```JavaScript { @@ -34,8 +40,6 @@ } ``` -If no `callback` is passed, a promise is returned. - **Example:** Imagine you want to publish your website under IPFS. You can use the [Files API](./FILES.md) to publish your static website and then you'll get a multihash you can link to. But when you need to make a change, a problem arises: you get a new multihash because you now have a different content. And it is not possible for you to be always giving others the new address. @@ -46,25 +50,32 @@ Here's where the Name API comes in handy. With it, you can use one static multih // The address of your files. const addr = '/ipfs/QmbezGequPwcsWo8UL4wDF6a8hYwM1hmbzYv2mnKkEWaUp' -ipfs.name.publish(addr, function (err, res) { - // You now receive a res which contains two fields: - // - name: the name under which the content was published. - // - value: the "real" address to which Name points. - console.log(`https://gateway.ipfs.io/ipns/${res.name}`) -}) +const res = await ipfs.name.publish(addr) +// You now have a res which contains two fields: +// - name: the name under which the content was published. +// - value: the "real" address to which Name points. +console.log(`https://gateway.ipfs.io/ipns/${res.name}`) ``` This way, you can republish a new version of your website under the same address. By default, `ipfs.name.publish` will use the Peer ID. If you want to have multiple websites (for example) under the same IPFS module, you can always check the [key API](./KEY.md). +A great source of [examples][] can be found in the tests for this API. + #### `name.pubsub.cancel` > Cancel a name subscription. -##### `ipfs.name.pubsub.cancel(arg, [callback])` +##### `ipfs.name.pubsub.cancel(arg)` `arg` is the name of the subscription to cancel. -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful. `result` is an object that contains the result of the operation, such as: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains the result of the operation | + +example of the returned object: ```JavaScript { @@ -72,26 +83,31 @@ This way, you can republish a new version of your website under the same address } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript const name = 'QmQrX8hka2BtNHa8N8arAq16TCVx5qHcb46c5yPewRycLm' -ipfs.name.pubsub.cancel(name, function (err, result) { - console.log(result.canceled) - // true -}) +const result = await ipfs.name.pubsub.cancel(name) +console.log(result.canceled) +// true ``` +A great source of [examples][examples-pubsub] can be found in the tests for this API. + #### `name.pubsub.state` > Query the state of IPNS pubsub. -##### `ipfs.name.pubsub.state([callback])` +##### `ipfs.name.pubsub.state()` + +**Returns** -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful. `result` is an object that contains the result of the operation, such as: +| Type | Description | +| -------- | -------- | +| `Promise` | An object that contains the result of the operation | + +example of the returned object: ```JavaScript { @@ -99,45 +115,49 @@ ipfs.name.pubsub.cancel(name, function (err, result) { } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.name.pubsub.state(function (err, result) { - console.log(result.enabled) - // true -}) +const result = await ipfs.name.pubsub.state() +console.log(result.enabled) +// true ``` +A great source of [examples][examples-pubsub] can be found in the tests for this API. + #### `name.pubsub.subs` > Show current name subscriptions. -##### `ipfs.name.pubsub.subs([callback])` +##### `ipfs.name.pubsub.subs()` + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of subscriptions | -`callback` must follow `function (err, result) {}` signature, where `err` is an error if the operation was not successful. `result` is an array of subscriptions, such as: +example of the returned array: ```JavaScript ['/ipns/QmQrX8hka2BtNHa8N8arAq16TCVx5qHcb46c5yPewRycLm'] ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.name.pubsub.subs(function (err, result) { - console.log(result) - // ['/ipns/QmQrX8hka2BtNHa8N8arAq16TCVx5qHcb46c5yPewRycLm'] -}) +const result = await ipfs.name.pubsub.subs() +console.log(result) +// ['/ipns/QmQrX8hka2BtNHa8N8arAq16TCVx5qHcb46c5yPewRycLm'] ``` +A great source of [examples][examples-pubsub] can be found in the tests for this API. + #### `name.resolve` > Resolve an IPNS name. -##### `ipfs.name.resolve(value, [options], [callback])` +##### `ipfs.name.resolve(value, [options])` `value` is a IPNS address, such as: `/ipns/ipfs.io`. @@ -150,9 +170,11 @@ ipfs.name.pubsub.subs(function (err, result) { } ``` -`callback` must follow `function (err, name) {}` signature, where `err` is an error if the operation was not successful. `name` is a string that contains the IPFS hash. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A string that contains the IPFS hash | **Example:** @@ -160,8 +182,12 @@ If no `callback` is passed, a promise is returned. // The IPNS address you want to resolve. const addr = '/ipns/ipfs.io' -ipfs.name.resolve(addr, function (err, name) { - console.log(name) - // /ipfs/QmQrX8hka2BtNHa8N8arAq16TCVx5qHcb46c5yPewRycLm -}) +const name = await ipfs.name.resolve(addr) +console.log(name) +// /ipfs/QmQrX8hka2BtNHa8N8arAq16TCVx5qHcb46c5yPewRycLm ``` + +A great source of [examples][] can be found in the tests for this API. + +[examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/name +[examples-pubsub]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/name-pubsub diff --git a/SPEC/OBJECT.md b/SPEC/OBJECT.md index d1d3690a1..83c03e35e 100644 --- a/SPEC/OBJECT.md +++ b/SPEC/OBJECT.md @@ -15,25 +15,23 @@ > Create a new MerkleDAG node, using a specific layout. Caveat: So far, only UnixFS object layouts are supported. -##### `ipfs.object.new([template], [callback])` +##### `ipfs.object.new([template])` `template` if defined, must be a string `unixfs-dir` and if that is passed, the created node will be an empty unixfs style directory. -`callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and `cid` is an instance of [CID][]. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A [CID](https://github.com/ipfs/js-cid) instance | **Example:** ```JavaScript -ipfs.object.new('unixfs-dir', (err, cid) => { - if (err) { - throw err - } - console.log(cid.toString()) - // Logs: - // QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn -}) +const cid = await ipfs.object.new('unixfs-dir') +console.log(cid.toString()) +// Logs: +// QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn ``` A great source of [examples][] can be found in the tests for this API. @@ -42,7 +40,7 @@ A great source of [examples][] can be found in the tests for this API. > Store an MerkleDAG node. -##### `ipfs.object.put(obj, [options], [callback])` +##### `ipfs.object.put(obj, [options])` `obj` is the MerkleDAG Node to be stored. Can of type: @@ -54,9 +52,11 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of the Buffer (json, yml, etc), if passed a Buffer. -`callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and `cid` is an instance of [CID][]. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A [CID](https://github.com/ipfs/js-cid) instance | **Example:** @@ -66,14 +66,10 @@ const obj = { Links: [] } -ipfs.object.put(obj, (err, cid) => { - if (err) { - throw err - } - console.log(cid.toString()) - // Logs: - // QmPb5f92FxKPYdT3QNBd1GKiL4tZUXUrzF4Hkpdr3Gf1gK -}) +const cid = await ipfs.object.pu(obj) +console.log(cid.toString()) +// Logs: +// QmPb5f92FxKPYdT3QNBd1GKiL4tZUXUrzF4Hkpdr3Gf1gK ``` A great source of [examples][] can be found in the tests for this API. @@ -82,7 +78,7 @@ A great source of [examples][] can be found in the tests for this API. > Fetch a MerkleDAG node -##### `ipfs.object.get(multihash, [options], [callback])` +##### `ipfs.object.get(multihash, [options])` `multihash` is a [multihash][] which can be passed as: @@ -93,23 +89,21 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, node) {}` signature, where `err` is an error if the operation was not successful and `node` is a MerkleDAG node of the type [DAGNode][] +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A MerkleDAG node of the type [DAGNode][] | **Example:** ```JavaScript const multihash = 'QmPb5f92FxKPYdT3QNBd1GKiL4tZUXUrzF4Hkpdr3Gf1gK' -ipfs.object.get(multihash, (err, node) => { - if (err) { - throw err - } - console.log(node.data) - // Logs: - // some data -}) +const node = await ipfs.object.get(multihash) +console.log(node.data) +// Logs: +// some data ``` A great source of [examples][] can be found in the tests for this API. @@ -118,7 +112,7 @@ A great source of [examples][] can be found in the tests for this API. > Returns the Data field of an object -##### `ipfs.object.data(multihash, [options], [callback])` +##### `ipfs.object.data(multihash, [options])` `multihash` is a [multihash][] which can be passed as: - Buffer, the raw Buffer of the multihash (or of and encoded version) @@ -128,23 +122,21 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, data) {}` signature, where `err` is an error if the operation was not successful and `data` is a Buffer with the data that the MerkleDAG node contained. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A Buffer with the data that the MerkleDAG node contained | **Example:** ```JavaScript const multihash = 'QmPb5f92FxKPYdT3QNBd1GKiL4tZUXUrzF4Hkpdr3Gf1gK' -ipfs.object.data(multihash, (err, data) => { - if (err) { - throw err - } - console.log(data.toString()) - // Logs: - // some data -}) +const data = await ipfs.object.data(multihash) +console.log(data.toString()) +// Logs: +// some data ``` A great source of [examples][] can be found in the tests for this API. @@ -153,7 +145,7 @@ A great source of [examples][] can be found in the tests for this API. > Returns the Links field of an object -##### `ipfs.object.links(multihash, [options], [callback])` +##### `ipfs.object.links(multihash, [options])` `multihash` is a [multihash][] which can be passed as: @@ -164,23 +156,21 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, links) {}` signature, where `err` is an error if the operation was not successful and `links` is an Array of [DAGLink](https://github.com/vijayee/js-ipfs-merkle-dag/blob/master/src/dag-node.js#L199-L203) objects. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An Array of [DAGLink](https://github.com/vijayee/js-ipfs-merkle-dag/blob/master/src/dag-node.js#L199-L203) objects | **Example:** ```JavaScript const multihash = 'QmPb5f92FxKPYdT3QNBd1GKiL4tZUXUrzF4Hkpdr3Gf1gK' -ipfs.object.links(multihash, (err, links) => { - if (err) { - throw err - } - console.log(links) - // Logs: - // [] -}) +const links = await ipfs.object.links(multihash) +console.log(links) +// Logs: +// [] ``` A great source of [examples][] can be found in the tests for this API. @@ -189,7 +179,7 @@ A great source of [examples][] can be found in the tests for this API. > Returns stats about an Object -##### `ipfs.object.stat(multihash, [options], [callback])` +##### `ipfs.object.stat(multihash, [options])` `multihash` is a [multihash][] which can be passed as: @@ -200,7 +190,13 @@ A great source of [examples][] can be found in the tests for this API. - `timeout`, A timeout to pass to the IPFS daemon so the request expires after a certain amount of time without any response. NOTE: not yet supported in JS IPFS. -`callback` must follow `function (err, stats) {}` signature, where `err` is an error if the operation was not successful and `stats` is an Object with following format: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object representing the stats of the Object | + +the returned object has the following format: ```JavaScript { @@ -213,28 +209,22 @@ A great source of [examples][] can be found in the tests for this API. } ``` -If no `callback` is passed, a [promise][] is returned. - **Example:** ```JavaScript const multihash = 'QmPTkMuuL6PD8L2SwTwbcs1NPg14U8mRzerB1ZrrBrkSDD' -ipfs.object.stat(multihash, {timeout: '10s'}, (err, stats) => { - if (err) { - throw err - } - console.log(stats) - // Logs: - // { - // Hash: 'QmPTkMuuL6PD8L2SwTwbcs1NPg14U8mRzerB1ZrrBrkSDD', - // NumLinks: 0, - // BlockSize: 10, - // LinksSize: 2, - // DataSize: 8, - // CumulativeSize: 10 - // } -}) +const stats = await ipfs.object.stat(multihash, {timeout: '10s'}) +console.log(stats) +// Logs: +// { +// Hash: 'QmPTkMuuL6PD8L2SwTwbcs1NPg14U8mRzerB1ZrrBrkSDD', +// NumLinks: 0, +// BlockSize: 10, +// LinksSize: 2, +// DataSize: 8, +// CumulativeSize: 10 +// } ``` A great source of [examples][] can be found in the tests for this API. @@ -247,7 +237,7 @@ A great source of [examples][] can be found in the tests for this API. > Add a Link to an existing MerkleDAG Object -###### `ipfs.object.patch.addLink(multihash, link, [options], [callback])` +###### `ipfs.object.patch.addLink(multihash, link, [options])` `multihash` is a [multihash][] which can be passed as: @@ -276,22 +266,21 @@ const link = new DAGLink(name, size, multihash) - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and `cid` is an instance of [CID][] - the CID of the new DAG node that was created due to the operation. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An instance of [CID][] representing the new DAG node that was created due to the operation | -If no `callback` is passed, a [promise][] is returned. **Example:** ```JavaScript -ipfs.object.patch.addLink(node, { +// cid is CID of the DAG node created by adding a link +const cid = await ipfs.object.patch.addLink(node, { name: 'some-link' size: 10 cid: new CID('QmPTkMuuL6PD8L2SwTwbcs1NPg14U8mRzerB1ZrrBrkSDD') -}, (err, cid) => { - if (err) { - throw err - } - // cid is CID of the DAG node created by adding a link }) ``` @@ -301,7 +290,7 @@ A great source of [examples][] can be found in the tests for this API. > Remove a Link from an existing MerkleDAG Object -###### `ipfs.object.patch.rmLink(multihash, link, [options], [callback])` +###### `ipfs.object.patch.rmLink(multihash, link, [options])` `multihash` is a [multihash][] which can be passed as: @@ -312,9 +301,9 @@ A great source of [examples][] can be found in the tests for this API. - `DAGLink` - ```js - const link = new DAGLink(name, size, multihash) - ``` + ```js + const link = new DAGLink(name, size, multihash) + ``` - Object containing a `name` property @@ -328,13 +317,21 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and `cid` is an instance of [CID][] - the CID of the new DAG node that was created due to the operation. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An instance of [CID][] representing the new DAG node that was created due to the operation | **Example:** ```JavaScript +// cid is CID of the DAG node created by removing a link +const cid = await ipfs.object.patch.rmLink(node, { + name: 'some-link' + size: 10 + cid: new CID('QmPTkMuuL6PD8L2SwTwbcs1NPg14U8mRzerB1ZrrBrkSDD') +}) ``` A great source of [examples][] can be found in the tests for this API. @@ -343,7 +340,7 @@ A great source of [examples][] can be found in the tests for this API. > Append Data to the Data field of an existing node. -###### `ipfs.object.patch.appendData(multihash, data, [options], [callback])` +###### `ipfs.object.patch.appendData(multihash, data, [options])` `multihash` is a [multihash][] which can be passed as: @@ -356,18 +353,16 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and `cid` is an instance of [CID][] - the CID of the new DAG node that was created due to the operation. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An instance of [CID][] representing the new DAG node that was created due to the operation | **Example:** ```JavaScript -ipfs.object.patch.appendData(multihash, new Buffer('more data'), (err, node) => { - if (err) { - throw err - } -}) +const cid = await ipfs.object.patch.appendData(multihash, new Buffer('more data')) ``` A great source of [examples][] can be found in the tests for this API. @@ -376,7 +371,7 @@ A great source of [examples][] can be found in the tests for this API. > Reset the Data field of a MerkleDAG Node to new Data -###### `ipfs.object.patch.setData(multihash, data, [options], [callback])` +###### `ipfs.object.patch.setData(multihash, data, [options])` `multihash` is a [multihash][] which can be passed as: @@ -389,18 +384,16 @@ A great source of [examples][] can be found in the tests for this API. - `enc`, the encoding of multihash (base58, base64, etc), if any. -`callback` must follow `function (err, cid) {}` signature, where `err` is an error if the operation was not successful and `cid` is an instance of [CID][] - the CID of the new DAG node that was created due to the operation. +**Returns** -If no `callback` is passed, a [promise][] is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An instance of [CID][] representing the new DAG node that was created due to the operation | **Example:** ```JavaScript -ipfs.object.patch.setData(multihash, new Buffer('more data'), (err, cid) => { - if (err) { - throw err - } -}) +const cid = await ipfs.object.patch.setData(multihash, new Buffer('more data')) ``` A great source of [examples][] can be found in the tests for this API. @@ -408,5 +401,4 @@ A great source of [examples][] can be found in the tests for this API. [CID]: https://github.com/multiformats/js-cid [DAGNode]: https://github.com/ipld/js-ipld-dag-pb [multihash]: http://github.com/multiformats/multihash -[promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise [examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/object diff --git a/SPEC/PIN.md b/SPEC/PIN.md index c3a7831bf..f3b36e6b8 100644 --- a/SPEC/PIN.md +++ b/SPEC/PIN.md @@ -8,7 +8,7 @@ > Adds an IPFS object to the pinset and also stores it to the IPFS repo. pinset is the set of hashes currently pinned (not gc'able). -##### `ipfs.pin.add(hash, [options], [callback])` +##### `ipfs.pin.add(hash, [options])` Where: @@ -16,7 +16,13 @@ Where: - `options` is an object that can contain the following keys - 'recursive' - Recursively pin the object linked. Type: bool. Default: `true` -`callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res` is an array of objects that represent the files that were pinned. Example: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects that represent the files that were pinned | + +an array of objects is returned, each of the form: ```JavaScript { @@ -24,19 +30,20 @@ Where: } ``` -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.pin.add(hash, function (err) {}) +const pinset = await ipfs.pin.add(hash) +console.log(pinset) ``` +A great source of [examples][] can be found in the tests for this API. + #### `pin.ls` > List all the objects pinned to local storage or under a specific hash. -##### `ipfs.pin.ls([hash], [options], [callback])` +##### `ipfs.pin.ls([hash], [options])` Where: @@ -44,19 +51,19 @@ Where: - `options` is an object that can contain the following keys: - 'type' - Return also the type of pin (direct, indirect or recursive) -`callback` must follow `function (err, pinset) {}` signature, where `err` is an error if the operation was not successful. `pinset` is an array of objects with keys `hash` and `type`. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of current pinned objects | -If no `callback` is passed, a promise is returned. +an array of objects with keys `hash` and `type` is returned. **Example:** ```JavaScript -ipfs.pin.ls(function (err, pinset) { - if (err) { - throw err - } - console.log(pinset) -}) +const pinset = await ipfs.pin.ls() +console.log(pinset) ``` A great source of [examples][] can be found in the tests for this API. @@ -65,26 +72,25 @@ A great source of [examples][] can be found in the tests for this API. > Remove a hash from the pinset -##### `ipfs.pin.rm(hash, [options], [callback])` +##### `ipfs.pin.rm(hash, [options])` Where: - `hash` is a multihash. - `options` is an object that can contain the following keys - 'recursive' - Recursively unpin the object linked. Type: bool. Default: `true` -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of unpinned objects | **Example:** ```JavaScript -ipfs.pin.rm(hash, function (err, pinset) { - if (err) { - throw err - } - console.log(pinset) prints the hashes that were unpinned -}) +const pinset = await ipfs.pin.rm(hash) +console.log(pinset) +// prints the hashes that were unpinned ``` A great source of [examples][] can be found in the tests for this API. diff --git a/SPEC/PUBSUB.md b/SPEC/PUBSUB.md index ecc6d96bb..3009589c2 100644 --- a/SPEC/PUBSUB.md +++ b/SPEC/PUBSUB.md @@ -10,30 +10,29 @@ > Subscribe to a pubsub topic. -##### `ipfs.pubsub.subscribe(topic, handler, [options], [callback])` +##### `ipfs.pubsub.subscribe(topic, handler, [options])` - `topic: String` - `handler: (msg) => {}` - Event handler which will be called with a message object everytime one is received. The `msg` has the format `{from: String, seqno: Buffer, data: Buffer, topicIDs: Array}`. - `options: Object` - (Optional) Object containing the following properties: - `discover: Boolean` - (Default: `false`) Will use the DHT to find other peers. -- `callback: (Error) => {}` - (Optional) Called once the subscription is established. - -If no `callback` is passed, a [promise][] is returned. > _In the future, topic can also be type of TopicDescriptor (https://github.com/libp2p/pubsub-notes/blob/master/flooding/flooding.proto#L23). However, for now, only strings are supported._ +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | + **Example:** ```JavaScript const topic = 'fruit-of-the-day' const receiveMsg = (msg) => console.log(msg.data.toString()) -ipfs.pubsub.subscribe(topic, receiveMsg, (err) => { - if (err) { - return console.error(`failed to subscribe to ${topic}`, err) - } - console.log(`subscribed to ${topic}`) -}) +await ipfs.pubsub.subscribe(topic, receiveMsg) +console.log(`subscribed to ${topic}`) ``` A great source of [examples][] can be found in the tests for this API. @@ -42,51 +41,41 @@ A great source of [examples][] can be found in the tests for this API. > Unsubscribes from a pubsub topic. -##### `ipfs.pubsub.unsubscribe(topic, handler, [callback])` +##### `ipfs.pubsub.unsubscribe(topic, handler)` - `topic: String` - The topic to unsubscribe from - `handler: (msg) => {}` - The handler to remove. -- `callback: (Error) => {}` (Optional) Called once the unsubscribe is done. - -If no `callback` is passed, a [promise][] is returned. If the `topic` and `handler` are provided, the `handler` will no longer receive updates for the `topic`. This behaves like [EventEmitter.removeListener](https://nodejs.org/dist/latest/docs/api/events.html#events_emitter_removelistener_eventname_listener). If the `handler` is not equivalent to the `handler` provided on `subscribe`, no action will be taken. If **only** the `topic` param is provided, unsubscribe will remove **all** handlers for the `topic`. This behaves like [EventEmitter.removeAllListeners](https://nodejs.org/dist/latest/docs/api/events.html#events_emitter_removealllisteners_eventname). Use this if you would like to no longer receive any updates for the `topic`. -**WARNING:** Unsubscribe is an async operation, but removing **all** handlers for a topic can only be done using the Promises API (due to the difficulty in distinguishing between a "handler" and a "callback" - they are both functions). If you _need_ to know when unsubscribe has completed you must use `await` or `.then` on the return value from +**WARNING:** Unsubscribe is an async operation, but removing **all** handlers for a topic can only be done using the Promises API (due to the difficulty in distinguishing between a "handler" and a "callback" - they are both functions). If you _need_ to know when unsubscribe has completed you must use `await` or `.then` on the return value from ```JavaScript ipfs.pubsub.unsubscribe('topic') ``` +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | + **Example:** ```JavaScript const topic = 'fruit-of-the-day' const receiveMsg = (msg) => console.log(msg.toString()) -ipfs.pubsub.subscribe(topic, receiveMsg, (err) => { - if (err) { - return console.error(`failed to subscribe to ${topic}`, err) - } +await ipfs.pubsub.subscribe(topic, receiveMsg) +console.log(`subscribed to ${topic}`) - console.log(`subscribed to ${topic}`) - - // unsubscribe a second later - setTimeout(() => { - ipfs.pubsub.unsubscribe(topic, receiveMsg, (err) => { - if (err) { - return console.error(`failed to unsubscribe from ${topic}`, err) - } - - console.log(`unsubscribed from ${topic}`) - }) - }, 1000) -}) +await ipfs.pubsub.unsubscribe(topic, receiveMsg) +console.log(`unsubscribed from ${topic}`) ``` -Or removing all listeners: +Or removing all listeners: ```JavaScript const topic = 'fruit-of-the-day' const receiveMsg = (msg) => console.log(msg.toString()) @@ -103,13 +92,16 @@ A great source of [examples][] can be found in the tests for this API. > Publish a data message to a pubsub topic. -##### `ipfs.pubsub.publish(topic, data, [callback])` +##### `ipfs.pubsub.publish(topic, data)` - `topic: String` - `data: Buffer|String` - The message to send -- `callback: (Error) => {}` - (Optional) Calls back with an error or nothing if the publish was successful. -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** @@ -117,13 +109,10 @@ If no `callback` is passed, a promise is returned. const topic = 'fruit-of-the-day' const msg = Buffer.from('banana') -ipfs.pubsub.publish(topic, msg, (err) => { - if (err) { - return console.error(`failed to publish to ${topic}`, err) - } - // msg was broadcasted - console.log(`published to ${topic}`) -}) +await ipfs.pubsub.publish(topic, msg) + +// msg was broadcasted +console.log(`published to ${topic}`) ``` A great source of [examples][] can be found in the tests for this API. @@ -132,21 +121,19 @@ A great source of [examples][] can be found in the tests for this API. > Returns the list of subscriptions the peer is subscribed to. -##### `ipfs.pubsub.ls([callback])` +##### `ipfs.pubsub.ls()` -- `callback: (Error, Array) => {}` - (Optional) Calls back with an error or a list of topicIDs that this peer is subscribed to. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of topicIDs that the peer is subscribed to | **Example:** ```JavaScript -ipfs.pubsub.ls((err, topics) => { - if (err) { - return console.error('failed to get list of subscription topics', err) - } - console.log(topics) -}) +const topics = await ipfs.pubsub.ls() +console.log(topics) ``` A great source of [examples][] can be found in the tests for this API. @@ -155,24 +142,23 @@ A great source of [examples][] can be found in the tests for this API. > Returns the peers that are subscribed to one topic. -##### `ipfs.pubsub.peers(topic, [callback])` +##### `ipfs.pubsub.peers(topic)` - `topic: String` -- `callback: (Error, Array) => {}` - (Optional) Calls back with an error or a list of peer IDs subscribed to the `topic`. -If no `callback` is passed, a promise is returned. +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array of peer IDs subscribed to the `topic` | **Example:** ```JavaScript const topic = 'fruit-of-the-day' -ipfs.pubsub.peers(topic, (err, peerIds) => { - if (err) { - return console.error(`failed to get peers subscribed to ${topic}`, err) - } - console.log(peerIds) -}) +const peerIds = ipfs.pubsub.peers(topic) +console.log(peerIds) ``` A great source of [examples][] can be found in the tests for this API. diff --git a/SPEC/REFS.md b/SPEC/REFS.md index e86fea704..491c51339 100644 --- a/SPEC/REFS.md +++ b/SPEC/REFS.md @@ -11,7 +11,7 @@ > Get links (references) from an object. -##### `ipfs.refs(ipfsPath, [options], [callback])` +##### `ipfs.refs(ipfsPath, [options])` `ipfsPath` can be of type: @@ -31,37 +31,49 @@ - `edges (false)`: output references in edge format: `" -> "` - `maxDepth (1)`: only for recursive refs, limits fetch and listing to the given depth -`callback` must follow `function (err, refs) {}` signature, where `err` is an error if the operation was not successful and `refs` is an array of `{ ref: "myref", err: "error msg" }` +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array representing the links (references) | + +example of the returned array: +```js +{ + ref: "myref", + err: "error msg" +} +``` **Example:** ```JavaScript -ipfs.refs(ipfsPath, { recursive: true }, function (err, refs) { - if (err) { - throw err - } - - for (const ref of refs) { - if (ref.err) { - console.error(ref.err) - } else { - console.log(ref.ref) - // output: "QmHash" - } +const refs = await ipfs.refs(ipfsPath, { recursive: true }) + +for (const ref of refs) { + if (ref.err) { + console.error(ref.err) + } else { + console.log(ref.ref) + // output: "QmHash" } -}) +} ``` #### `refsReadableStream` > Output references using a [Readable Stream][rs] -##### `ipfs.refsReadableStream(ipfsPath, [options])` -> [Readable Stream][rs] +##### `ipfs.refsReadableStream(ipfsPath, [options])` `options` is an optional object argument identical to the options for [ipfs.refs](#refs) +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [Readable Stream][rs] representing the references | + **Example:** ```JavaScript @@ -79,10 +91,16 @@ stream.on('data', function (ref) { > Output references using a [Pull Stream][ps]. -##### `ipfs.refsReadableStream(ipfsPath, [options])` -> [Pull Stream][ps] +##### `ipfs.refsReadableStream(ipfsPath, [options])` `options` is an optional object argument identical to the options for [ipfs.refs](#refs) +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [Pull Stream][ps] representing the references | + **Example:** ```JavaScript @@ -104,11 +122,21 @@ pull( > Output all local references (CIDs of all blocks in the blockstore) -##### `ipfs.refs.local([callback])` +##### `ipfs.refs.local()` -`callback` must follow `function (err, refs) {}` signature, where `err` is an error if the operation was not successful and `refs` is an array of `{ ref: "myref", err: "error msg" }` +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array representing all the local references | + +example of the returned array: +```js +{ + ref: "myref", + err: "error msg" +} +``` **Example:** @@ -133,7 +161,13 @@ ipfs.refs.local(function (err, refs) { > Output all local references using a [Readable Stream][rs] -##### `ipfs.localReadableStream()` -> [Readable Stream][rs] +##### `ipfs.localReadableStream()` + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [Readable Stream][rs] representing all the local references | **Example:** @@ -152,7 +186,13 @@ stream.on('data', function (ref) { > Output all local references using a [Pull Stream][ps]. -##### `ipfs.refs.localReadableStream()` -> [Pull Stream][ps] +##### `ipfs.refs.localReadableStream()` + +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [Pull Stream][ps] representing all the local references | **Example:** diff --git a/SPEC/REPO.md b/SPEC/REPO.md index c0abc44f0..d59765a47 100644 --- a/SPEC/REPO.md +++ b/SPEC/REPO.md @@ -8,7 +8,7 @@ > Perform a garbage collection sweep on the repo. -##### `ipfs.repo.gc([options], [callback])` +##### `ipfs.repo.gc([options])` Where: @@ -16,25 +16,29 @@ Where: - `quiet` writes a minimal output. - `stream-errors` stream errors. -`callback` must follow `function (err, res) {}` signature, where -- `err` is an Error if the whole GC operation was not successful. -- `res` is an array of objects that contains the following properties - - `err` is an Error if it was not possible to GC a particular block. - - `cid` is the [CID][cid] of the block that was Garbage Collected. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of objects | + +each object contains the following properties: + +- `err` is an Error if it was not possible to GC a particular block. +- `cid` is the [CID][cid] of the block that was Garbage Collected. **Example:** ```JavaScript -ipfs.repo.gc((err, res) => console.log(res)) +const res = await ipfs.repo.gc() +console.log(res) ``` #### `repo.stat` > Get stats for the currently used repo. -##### `ipfs.repo.stat([options], [callback])` +##### `ipfs.repo.stat([options])` `stats.repo` and `repo.stat` can be used interchangeably. @@ -43,7 +47,13 @@ Where: - `options` is an object that contains following properties - `human` a Boolean value to output `repoSize` in MiB. -`callback` must follow `function (err, stats) {}` signature, where `err` is an Error if the operation was not successful and `stats` is an object containing the following keys: +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An object containing the repo's info | + +the returned object has the following keys: - `numObjects` is a [BigNumber Int][1]. - `repoSize` is a [BigNumber Int][1], in bytes. @@ -51,12 +61,11 @@ Where: - `version` is a string. - `storageMax` is a [BigNumber Int][1]. -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.repo.stat((err, stats) => console.log(stats)) +const stats = await ipfs.repo.stat() +console.log(stats) // { numObjects: 15, // repoSize: 64190, @@ -69,16 +78,19 @@ ipfs.repo.stat((err, stats) => console.log(stats)) > Show the repo version. -##### `ipfs.repo.version([callback])` +##### `ipfs.repo.version()` -`callback` must follow `function (err, version) {}` signature, where `err` is an Error if the operation was not successful and `version` is a String containing the version. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | A String containing the repo's version | **Example:** ```JavaScript -ipfs.repo.version((err, version) => console.log(version)) +const version = await ipfs.repo.version() +console.log(version) // "6" ``` diff --git a/SPEC/STATS.md b/SPEC/STATS.md index 16dd636fd..4686592e2 100644 --- a/SPEC/STATS.md +++ b/SPEC/STATS.md @@ -22,7 +22,7 @@ Note: `stats.repo` and `repo.stat` can be used interchangeably. See [`repo.stat` > Get IPFS bandwidth information as an object. -##### `ipfs.stats.bw([options], [callback])` +##### `ipfs.stats.bw([options])` Where: @@ -32,36 +32,47 @@ Where: - `poll` is used to print bandwidth at an interval. - `interval` is the time interval to wait between updating output, if `poll` is true. -`callback` must follow `function (err, stat) {}` signature, where `err` is an Error if the operation was not successful. +**Returns** -`stat` is, in both cases, an Object containing the following keys: +| Type | Description | +| -------- | -------- | +| `Promise` | An object representing IPFS bandwidth information | + +the returned object contains the following keys: - `totalIn` - is a [BigNumber Int][bigNumber], in bytes. - `totalOut` - is a [BigNumber Int][bigNumber], in bytes. - `rateIn` - is a [BigNumber Int][bigNumber], in bytes. - `rateOut` - is a [BigNumber Int][bigNumber], in bytes. -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.stats.bw((err, stats) => console.log(stats)) +const stats = await ipfs.stats.bw() +console.log(stats) // { totalIn: BigNumber {...}, // totalOut: BigNumber {...}, // rateIn: BigNumber {...}, // rateOut: BigNumber {...} } ``` +A great source of [examples][] can be found in the tests for this API. + #### `stats.bwPullStream` > Get IPFS bandwidth information as a [Pull Stream][ps]. -##### `ipfs.stats.bwPullStream([options])` -> [Pull Stream][ps] +##### `ipfs.stats.bwPullStream([options])` Options are described on [`ipfs.stats.bw`](#bw). +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [Pull Stream][ps] representing IPFS bandwidth information | + **Example:** ```JavaScript @@ -83,15 +94,23 @@ pull( // Ad infinitum ``` +A great source of [examples][] can be found in the tests for this API. + #### `stats.bwReadableStream` > Get IPFS bandwidth information as a [Readable Stream][rs]. -##### `ipfs.stats.bwReadableStream([options])` -> [Readable Stream][rs] +##### `ipfs.stats.bwReadableStream([options])` Options are described on [`ipfs.stats.bw`](#bw). -**Examples:** +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | A [Readable Stream][rs] representing IPFS bandwidth information | + +**Example:** ```JavaScript const stream = ipfs.stats.bwReadableStream({ poll: true }) @@ -108,6 +127,9 @@ stream.on('data', (data) => { // Ad infinitum ``` +A great source of [examples][] can be found in the tests for this API. + [bigNumber]: https://github.com/MikeMcl/bignumber.js/ [rs]: https://www.npmjs.com/package/readable-stream [ps]: https://www.npmjs.com/package/pull-stream +[examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/stats diff --git a/SPEC/SWARM.md b/SPEC/SWARM.md index 5cb5199d5..7f9d8252f 100644 --- a/SPEC/SWARM.md +++ b/SPEC/SWARM.md @@ -12,21 +12,19 @@ > List of known addresses of each peer connected. -##### `ipfs.swarm.addrs([callback])` +##### `ipfs.swarm.addrs()` -`callback` must follow `function (err, peerInfos) {}` signature, where `err` is an error if the operation was not successful. `peerInfos` will be an array of [`PeerInfo`](https://github.com/libp2p/js-peer-info)s. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of of [`PeerInfo`](https://github.com/libp2p/js-peer-info)s | **Example:** ```JavaScript -ipfs.swarm.addrs(function (err, peerInfos) { - if (err) { - throw err - } - console.log(peerInfos) -}) +const peerInfos = await ipfs.swarm.addrs() +console.log(peerInfos) ``` A great source of [examples][] can be found in the tests for this API. @@ -35,23 +33,20 @@ A great source of [examples][] can be found in the tests for this API. > Open a connection to a given address. -##### `ipfs.swarm.connect(addr, [callback])` +##### `ipfs.swarm.connect(addr)` Where `addr` is of type [multiaddr](https://github.com/multiformats/js-multiaddr) -`callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.swarm.connect(addr, function (err) { - if (err) { - throw err - } - // if no err is present, connection is now open -}) +await ipfs.swarm.connect(addr) ``` A great source of [examples][] can be found in the tests for this API. @@ -60,18 +55,20 @@ A great source of [examples][] can be found in the tests for this API. > Close a connection on a given address. -##### `ipfs.swarm.disconnect(addr, [callback])` +##### `ipfs.swarm.disconnect(addr)` Where `addr` is of type [multiaddr](https://github.com/multiformats/js-multiaddr) -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | **Example:** ```JavaScript -ipfs.swarm.disconnect(addr, function (err) {}) +await ipfs.swarm.disconnect(addr) ``` A great source of [examples][] can be found in the tests for this API. @@ -80,21 +77,19 @@ A great source of [examples][] can be found in the tests for this API. > Local addresses this node is listening on. -##### `ipfs.swarm.localAddrs([callback])` +##### `ipfs.swarm.localAddrs()` -`callback` must follow `function (err, multiAddrs) {}` signature, where `err` is an error if the operation was not successful. `multiAddrs` will be an array of [`MultiAddr`](https://github.com/multiformats/js-multiaddr). +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of [`MultiAddr`](https://github.com/multiformats/js-multiaddr) representing the local addresses the node is listening | **Example:** ```JavaScript -ipfs.swarm.localAddrs(function (err, multiAddrs) { - if (err) { - throw err - } - console.log(multiAddrs) -}) +const multiAddrs = await ipfs.swarm.localAddrs() +console.log(multiAddrs) ``` A great source of [examples][] can be found in the tests for this API. @@ -103,11 +98,17 @@ A great source of [examples][] can be found in the tests for this API. > List out the peers that we have connections with. -##### `ipfs.swarm.peers([options], [callback])` +##### `ipfs.swarm.peers([options])` If `options.verbose` is set to `true` additional information, such as `latency` is provided. -`callback` must follow `function (err, peerInfos) {}` signature, where `err` is an error if the operation was not successful. `peerInfos` will be an array of the form +**Returns** + +| Type | Description | +| -------- | -------- | +| `Promise` | An array with the list of peers that the node have connections with | + +the returned array has the following form: - `addr: Multiaddr` - `peer: PeerId` @@ -125,17 +126,11 @@ If an error occurs trying to create an individual `peerInfo` object, it will hav and all other properties may be undefined. -If no `callback` is passed, a promise is returned. - **Example:** ```JavaScript -ipfs.swarm.peers(function (err, peerInfos) { - if (err) { - throw err - } - console.log(peerInfos) -}) +const peerInfos = await ipfs.swarm.peers() +console.log(peerInfos) ``` A great source of [examples][] can be found in the tests for this API. @@ -148,52 +143,58 @@ A great source of [examples][] can be found in the tests for this API. > Display current multiaddr filters. Filters are a way to set up rules for the network connections established. -##### `ipfs.swarm.filters([callback])` +##### `ipfs.swarm.filters()` -`callback` must follow `function (err, filters) {}` signature, where `err` is an error if the operation was not successful. `filters` is an array of multiaddrs that represent the filters being applied. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | An array of multiaddrs that represent the filters being applied | Example: ```JavaScript -ipfs.swarm.filters(function (err, filters) {}) +const filters = await ipfs.swarm.filters() ``` #### `swarm.filters.add` > Add another filter. -##### `ipfs.swarm.filters.add(filter, [callback])` +##### `ipfs.swarm.filters.add(filter)` Where `filter` is of type [multiaddr]() -`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | Example: ```JavaScript -ipfs.swarm.filters.add(filter, function (err) {}) +await ipfs.swarm.filters.add(filter) ``` #### `swarm.filters.rm` > Remove a filter -##### `ipfs.swarm.filters.rm(filter, [callback])` +##### `ipfs.swarm.filters.rm(filter)` Where `filter` is of type [multiaddr]() -`callback` must follow `function (err, res) {}` signature, where `err` is an error if the operation was not successful. `res` will be an array of: +**Returns** -If no `callback` is passed, a promise is returned. +| Type | Description | +| -------- | -------- | +| `Promise` | If action is successfully completed. Otherwise an error will be thrown | Example: ```JavaScript -ipfs.swarm.filters.rm(filter, function (err) {}) +await ipfs.swarm.filters.rm(filter) ``` [examples]: https://github.com/ipfs/interface-ipfs-core/blob/master/src/swarm From 838bac54af87c5b2efe3601e26cc7b18488e7094 Mon Sep 17 00:00:00 2001 From: Pedro Santos Date: Fri, 25 Oct 2019 17:14:57 +0100 Subject: [PATCH 2/2] chore: code review changes --- SPEC/BITSWAP.md | 3 +++ SPEC/BLOCK.md | 7 +++++-- SPEC/BOOTSTRAP.md | 3 +++ SPEC/CONFIG.md | 3 +++ SPEC/DAG.md | 13 ++++++++----- SPEC/DHT.md | 3 +++ SPEC/FILES.md | 3 +++ SPEC/KEY.md | 7 +++---- SPEC/MISCELLANEOUS.md | 7 +++++-- SPEC/NAME.md | 3 +++ SPEC/OBJECT.md | 7 +++++-- SPEC/PIN.md | 13 ++++++++++++- SPEC/PUBSUB.md | 5 ++++- SPEC/REFS.md | 11 +++++++---- SPEC/REPO.md | 3 +++ SPEC/STATS.md | 7 +++++-- SPEC/SWARM.md | 3 +++ 17 files changed, 78 insertions(+), 23 deletions(-) diff --git a/SPEC/BITSWAP.md b/SPEC/BITSWAP.md index 6262e7df6..9b97dc625 100644 --- a/SPEC/BITSWAP.md +++ b/SPEC/BITSWAP.md @@ -3,6 +3,9 @@ * [bitswap.wantlist](#bitswapwantlist) * [bitswap.stat](#bitswapstat) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + ### `bitswap.wantlist` > Returns the wantlist, optionally filtered by peer ID diff --git a/SPEC/BLOCK.md b/SPEC/BLOCK.md index d3eeb6304..1c3037258 100644 --- a/SPEC/BLOCK.md +++ b/SPEC/BLOCK.md @@ -5,6 +5,9 @@ * [block.rm](#blockrm) * [block.stat](#blockstat) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `block.get` > Get a raw IPFS block. @@ -75,7 +78,7 @@ const block = await ipfs.block.put(buf) console.log(block.data.toString()) // Logs: // a serialized object -console.log(block.cid.toBaseEncodedString()) +console.log(block.cid.toString()) // Logs: // the CID of the object @@ -89,7 +92,7 @@ const block = await ipfs.block.put(blob, cid) console.log(block.data.toString()) // Logs: // a serialized object -console.log(block.cid.toBaseEncodedString()) +console.log(block.cid.toString()) // Logs: // the CID of the object ``` diff --git a/SPEC/BOOTSTRAP.md b/SPEC/BOOTSTRAP.md index b9566c950..923696a98 100644 --- a/SPEC/BOOTSTRAP.md +++ b/SPEC/BOOTSTRAP.md @@ -10,6 +10,9 @@ * [bootstrap.list](#bootstraplist) * [bootstrap.rm](#bootstraprm) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `bootstrap.add` > Add a peer address to the bootstrap list diff --git a/SPEC/CONFIG.md b/SPEC/CONFIG.md index 725a59d47..5dd377903 100644 --- a/SPEC/CONFIG.md +++ b/SPEC/CONFIG.md @@ -6,6 +6,9 @@ * [config.profiles.list](#configprofileslist) * [config.profiles.apply](#configprofilesapply) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `config.get` > Returns the currently being used config. If the daemon is off, it returns the stored config. diff --git a/SPEC/DAG.md b/SPEC/DAG.md index 662020a02..93fce539f 100644 --- a/SPEC/DAG.md +++ b/SPEC/DAG.md @@ -10,6 +10,9 @@ _Explore the DAG API through interactive coding challenges in our ProtoSchool tu - _[P2P data links with content addressing](https://proto.school/#/basics/) (beginner)_ - _[Blogging on the Decentralized Web](https://proto.school/#/blog/) (intermediate)_ +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `dag.put` > Store an IPLD format node @@ -40,7 +43,7 @@ _Explore the DAG API through interactive coding challenges in our ProtoSchool tu const obj = { simple: 'object' } const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha3-512' }) -console.log(cid.toBaseEncodedString()) +console.log(cid.toString()) // zBwWX9ecx5F4X54WAjmFLErnBT6ByfNxStr5ovowTL7AhaUR98RWvXPS1V3HqV1qs3r5Ec5ocv7eCdbqYQREXNUfYNuKG ``` @@ -85,11 +88,11 @@ const obj = { } const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' }) -console.log(cid.toBaseEncodedString()) +console.log(cid.toString()) // zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5 -async function getAndLog(cid) { - const result = await ipfs.dag.get(cid) +async function getAndLog(cidPath) { + const result = await ipfs.dag.get(cidPath) console.log(result.value) } @@ -149,7 +152,7 @@ const obj = { } const cid = await ipfs.dag.put(obj, { format: 'dag-cbor', hashAlg: 'sha2-256' }) -console.log(cid.toBaseEncodedString()) +console.log(cid.toString()) // zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5 const result = await ipfs.dag.tree('zdpuAmtur968yprkhG9N5Zxn6MFVoqAWBbhUAkNLJs2UtkTq5') diff --git a/SPEC/DHT.md b/SPEC/DHT.md index 05191d547..31c8a5d33 100644 --- a/SPEC/DHT.md +++ b/SPEC/DHT.md @@ -7,6 +7,9 @@ * [dht.put](#dhtput) * [dht.query](#dhtquery) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `dht.findPeer` > Retrieve the Peer Info of a reachable node in the network. diff --git a/SPEC/FILES.md b/SPEC/FILES.md index e5cfda957..342133b6e 100644 --- a/SPEC/FILES.md +++ b/SPEC/FILES.md @@ -38,6 +38,9 @@ _Explore the Mutable File System through interactive coding challenges in our [P - [files.stat](#filesstat) - [files.write](#fileswrite) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `add` > Add files and data to IPFS. diff --git a/SPEC/KEY.md b/SPEC/KEY.md index dceddb1c6..ac588d1ba 100644 --- a/SPEC/KEY.md +++ b/SPEC/KEY.md @@ -7,6 +7,9 @@ * [key.export](#keyexport) * [key.import](#keyimport) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `key.gen` > Generate a new key @@ -148,8 +151,6 @@ A great source of [examples][] can be found in the tests for this API. > Export a key in a PEM encoded password protected PKCS #8 -##### Go **NYI** - ##### `ipfs.key.export(name, password)` Where: @@ -181,8 +182,6 @@ A great source of [examples][] can be found in the tests for this API. > Import a PEM encoded password protected PKCS #8 key -##### Go **NYI** - ##### `ipfs.key.import(name, pem, password)` Where: diff --git a/SPEC/MISCELLANEOUS.md b/SPEC/MISCELLANEOUS.md index 230272410..b09641a56 100644 --- a/SPEC/MISCELLANEOUS.md +++ b/SPEC/MISCELLANEOUS.md @@ -9,6 +9,9 @@ * [pingReadableStream](#pingreadablestream) * [resolve](#resolve) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `id` > Returns the identity of the Peer @@ -158,7 +161,7 @@ Where: | Type | Description | | -------- | -------- | -| `Promise` | A [`PullStream`][ps] of ping response objects | +| `PullStream` | A [`PullStream`][ps] of ping response objects | example of the returned objects: @@ -207,7 +210,7 @@ Where: | Type | Description | | -------- | -------- | -| `Promise` | A [`ReadableStream`][rs] of ping response objects | +| `ReadableStream` | A [`ReadableStream`][rs] of ping response objects | example of the returned objects: diff --git a/SPEC/NAME.md b/SPEC/NAME.md index f62847803..ecb7a0414 100644 --- a/SPEC/NAME.md +++ b/SPEC/NAME.md @@ -6,6 +6,9 @@ * [name.pubsub.subs](#namepubsubsubs) * [name.resolve](#nameresolve) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `name.publish` > Publish an IPNS name with a given value. diff --git a/SPEC/OBJECT.md b/SPEC/OBJECT.md index 83c03e35e..61aed4f7d 100644 --- a/SPEC/OBJECT.md +++ b/SPEC/OBJECT.md @@ -11,6 +11,9 @@ * [object.patch.appendData](#objectpatchappenddata) * [object.patch.setData](#objectpatchsetdata) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `object.new` > Create a new MerkleDAG node, using a specific layout. Caveat: So far, only UnixFS object layouts are supported. @@ -66,7 +69,7 @@ const obj = { Links: [] } -const cid = await ipfs.object.pu(obj) +const cid = await ipfs.object.put(obj) console.log(cid.toString()) // Logs: // QmPb5f92FxKPYdT3QNBd1GKiL4tZUXUrzF4Hkpdr3Gf1gK @@ -160,7 +163,7 @@ A great source of [examples][] can be found in the tests for this API. | Type | Description | | -------- | -------- | -| `Promise` | An Array of [DAGLink](https://github.com/vijayee/js-ipfs-merkle-dag/blob/master/src/dag-node.js#L199-L203) objects | +| `Promise` | An Array of [DAGLink](https://github.com/ipld/js-ipld-dag-pb/blob/master/src/dag-link/dagLink.js) objects | **Example:** diff --git a/SPEC/PIN.md b/SPEC/PIN.md index f3b36e6b8..b83fc4a82 100644 --- a/SPEC/PIN.md +++ b/SPEC/PIN.md @@ -4,6 +4,9 @@ * [pin.ls](#pinls) * [pin.rm](#pinrm) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `pin.add` > Adds an IPFS object to the pinset and also stores it to the IPFS repo. pinset is the set of hashes currently pinned (not gc'able). @@ -33,8 +36,10 @@ an array of objects is returned, each of the form: **Example:** ```JavaScript -const pinset = await ipfs.pin.add(hash) +const pinset = await ipfs.pin.add('QmWATWQ7fVPP2EFGu71UkfnqhYXDYH566qy47CnJDgvs8u') console.log(pinset) +// Logs: +// [ { hash: 'QmWATWQ7fVPP2EFGu71UkfnqhYXDYH566qy47CnJDgvs8u' } ] ``` A great source of [examples][] can be found in the tests for this API. @@ -64,6 +69,12 @@ an array of objects with keys `hash` and `type` is returned. ```JavaScript const pinset = await ipfs.pin.ls() console.log(pinset) +// Logs +// [ +// { hash: Qmc5XkteJdb337s7VwFBAGtiaoj2QCEzyxtNRy3iMudc3E, type: 'recursive' }, +// { hash: QmZbj5ruYneZb8FuR9wnLqJCpCXMQudhSdWhdhp5U1oPWJ, type: 'indirect' }, +// { hash: QmSo73bmN47gBxMNqbdV6rZ4KJiqaArqJ1nu5TvFhqqj1R, type: 'indirect' } +// ] ``` A great source of [examples][] can be found in the tests for this API. diff --git a/SPEC/PUBSUB.md b/SPEC/PUBSUB.md index 3009589c2..1f794a0dd 100644 --- a/SPEC/PUBSUB.md +++ b/SPEC/PUBSUB.md @@ -6,6 +6,9 @@ * [pubsub.ls](#pubsubls) * [pubsub.peers](#pubsubpeers) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `pubsub.subscribe` > Subscribe to a pubsub topic. @@ -15,7 +18,7 @@ - `topic: String` - `handler: (msg) => {}` - Event handler which will be called with a message object everytime one is received. The `msg` has the format `{from: String, seqno: Buffer, data: Buffer, topicIDs: Array}`. - `options: Object` - (Optional) Object containing the following properties: - - `discover: Boolean` - (Default: `false`) Will use the DHT to find other peers. + - `discover: Boolean` - (Default: `false`) Will use the DHT to find other peers. ***Note:** This option is currently unimplemented and, thus, you can't use it for now.* > _In the future, topic can also be type of TopicDescriptor (https://github.com/libp2p/pubsub-notes/blob/master/flooding/flooding.proto#L23). However, for now, only strings are supported._ diff --git a/SPEC/REFS.md b/SPEC/REFS.md index 491c51339..c2439a60e 100644 --- a/SPEC/REFS.md +++ b/SPEC/REFS.md @@ -7,6 +7,9 @@ * [refs.localReadableStream](#refslocalreadablestream) * [refs.localPullStream](#refslocalpullstream) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `refs` > Get links (references) from an object. @@ -72,7 +75,7 @@ for (const ref of refs) { | Type | Description | | -------- | -------- | -| `Promise` | A [Readable Stream][rs] representing the references | +| `ReadableStream` | A [Readable Stream][rs] representing the references | **Example:** @@ -99,7 +102,7 @@ stream.on('data', function (ref) { | Type | Description | | -------- | -------- | -| `Promise` | A [Pull Stream][ps] representing the references | +| `PullStream` | A [Pull Stream][ps] representing the references | **Example:** @@ -167,7 +170,7 @@ ipfs.refs.local(function (err, refs) { | Type | Description | | -------- | -------- | -| `Promise` | A [Readable Stream][rs] representing all the local references | +| `ReadableStream` | A [Readable Stream][rs] representing all the local references | **Example:** @@ -192,7 +195,7 @@ stream.on('data', function (ref) { | Type | Description | | -------- | -------- | -| `Promise` | A [Pull Stream][ps] representing all the local references | +| `PullStream` | A [Pull Stream][ps] representing all the local references | **Example:** diff --git a/SPEC/REPO.md b/SPEC/REPO.md index d59765a47..03789f5db 100644 --- a/SPEC/REPO.md +++ b/SPEC/REPO.md @@ -4,6 +4,9 @@ * [repo.stat](#repostat) * [repo.version](#repoversion) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `repo.gc` > Perform a garbage collection sweep on the repo. diff --git a/SPEC/STATS.md b/SPEC/STATS.md index 4686592e2..67cf01197 100644 --- a/SPEC/STATS.md +++ b/SPEC/STATS.md @@ -6,6 +6,9 @@ * [stats.bwPullStream](#statsbwpullstream) * [stats.bwReadableStream](#statsbwreadablestream) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `stats.bitswap` > Show diagnostic information on the bitswap agent. @@ -71,7 +74,7 @@ Options are described on [`ipfs.stats.bw`](#bw). | Type | Description | | -------- | -------- | -| `Promise` | A [Pull Stream][ps] representing IPFS bandwidth information | +| `PullStream` | A [Pull Stream][ps] representing IPFS bandwidth information | **Example:** @@ -108,7 +111,7 @@ Options are described on [`ipfs.stats.bw`](#bw). | Type | Description | | -------- | -------- | -| `Promise` | A [Readable Stream][rs] representing IPFS bandwidth information | +| `ReadableStream` | A [Readable Stream][rs] representing IPFS bandwidth information | **Example:** diff --git a/SPEC/SWARM.md b/SPEC/SWARM.md index 7f9d8252f..e61a8bf0c 100644 --- a/SPEC/SWARM.md +++ b/SPEC/SWARM.md @@ -8,6 +8,9 @@ * [swarm.filters.add](#swarmfiltersadd) (not implemented yet) * [swarm.filters.rm](#swarmfiltersrm) (not implemented yet) +### ⚠️ Note +Although not listed in the documentation, all the following APIs that actually return a **promise** can also accept a **final callback** parameter. + #### `swarm.addrs` > List of known addresses of each peer connected.