orbit-db/API.md

451 lines
13 KiB
Markdown
Raw Normal View History

2018-07-12 15:07:30 -04:00
# OrbitDB API Documentation
Read the **[GETTING STARTED](https://github.com/orbitdb/orbit-db/blob/master/GUIDE.md)** guide for a more in-depth tutorial and to understand how OrbitDB works.
2018-07-12 15:07:30 -04:00
### constructor(ipfs, [directory], [options])
```javascript
const orbitdb = new OrbitDB(ipfs)
```
2018-07-12 15:07:30 -04:00
Creates and returns an instance of OrbitDB. Use the optional `directory` argument to specify a path to be used for the database files (Default: `'./orbitdb'`). In addition, you can use the optional `options` argument for further configuration. It is an object with any of these properties:
2018-07-12 15:07:30 -04:00
- `peerId` (string): By default it uses the base58 string of the ipfs peer id.
2018-07-12 15:07:30 -04:00
- `keystore` (Keystore Instance) : By default creates an instance of [Keystore](https://github.com/orbitdb/orbit-db-keystore). A custom keystore instance can be used, see [this](https://github.com/orbitdb/orbit-db/blob/master/test/utils/custom-test-keystore.js) for an example.
2017-03-30 18:43:47 +02:00
After creating an `OrbitDB` instance , you can access the different data stores. Creating a database instance, eg. with `orbitdb.keyvalue(...)`, returns a *Promise* that resolves to a [database instance](#store). See the [Store](#store) section for details of common methods and properties.
2017-03-30 18:43:47 +02:00
```javascript
const db = await orbitdb.keyvalue('profile')
```
2017-03-30 18:43:47 +02:00
2018-07-12 15:07:30 -04:00
- **Public OrbitDB Instance Methods**
2018-07-12 15:33:28 -04:00
- [orbitdb.keyvalue(name|address)](#orbitdbkeyvaluenameaddress)
2018-07-12 15:07:30 -04:00
- [kv.put(key, value)](#putkey-value)
- [kv.set(key, value)](#setkey-value)
- [kv.get(key)](#getkey)
2018-07-12 15:33:28 -04:00
- [orbitdb.log(name|address)](#orbitdblognameaddress)
2018-07-12 15:07:30 -04:00
- [log.add(event)](#addevent)
- [log.get(hash)](#gethash)
- [log.iterator([options])](#iteratoroptions)
2018-07-12 15:33:28 -04:00
- [orbitdb.feed(name|address)](#orbitdbfeednameaddress)
2018-07-12 15:07:30 -04:00
- [feed.add(data)](#adddata)
- [feed.get(hash)](#gethash-1)
- [feed.remove(hash)](#removehash)
2018-07-12 15:33:28 -04:00
- [feed.iterator([options])](#iteratoroptions-1)
- [orbitdb.docs(name|address, options)](#orbitdbdocsnameaddress-options)
2018-07-12 15:07:30 -04:00
- [docs.put(doc)](#putdoc)
- [docs.get(hash)](#getkey-1)
- [docs.query(mapper)](#querymapper)
- [del(key)](#delkey)
2018-07-12 15:33:28 -04:00
- [orbitdb.counter(name|address)](#orbitdbcounternameaddress)
2018-07-12 15:07:30 -04:00
- [counter.value](#value)
- [counter.inc([value])](#incvalue)
- [orbitdb.create(name|address, type, [options])]()
- [orbitdb.open(name|address, [options])]()
2018-07-12 15:33:28 -04:00
- [orbitdb.stop()](#orbitdbstop)
- [orbitdb.disconnect()](orbitdbdisconnect)
2018-07-12 15:07:30 -04:00
- **Static Properties**
- [OrbitDB.databaseTypes](#databasetypes)
- **Static Methods**
- [OrbitDB.isValidType(type)](#isvalidtypetype)
- [OrbitDB.addDatabaseType(type, store)](#adddatabasetypetype-store)
- [OrbitDB.getDatabaseTypes()](#getdatabasetypes)
- [OrbitDB.isValidAddress(address)](#isvalidaddressaddress)
- [OrbitDB.parseAddress(address)](#parseaddressaddress)
- [Store API](#store)
- [store.load()](#load)
- [store.close()](#close)
- [store.drop()](#drop)
- [store.events](#events)
- [store.key](#key)
- [store.type](#type)
## Public Instance Methods
### orbitdb.keyvalue(name|address)
Module: [orbit-db-kvstore](https://github.com/orbitdb/orbit-db-kvstore)
```javascript
const db = await orbitdb.keyvalue('application.settings')
// Or:
const db = await orbitdb.keyvalue(anotherkvdb.address)
```
**See the [Store](#store) section for details of common methods and properties.**
#### put(key, value)
```javascript
await db.put('hello', { name: 'World' })
```
#### set(key, value)
```javascript
await db.set('hello', { name: 'Friend' })
```
2017-12-02 06:33:30 +01:00
*set() is an alias of put(). They both work the same.*
#### get(key)
```javascript
const value = db.get('hello')
// { name: 'Friend' }
```
2018-07-12 15:07:30 -04:00
### orbitdb.log(name|address)
Module: [orbit-db-eventstore](https://github.com/orbitdb/orbit-db-eventstore)
```javascript
const db = await orbitdb.eventlog('site.visitors')
// Or:
const db = await orbitdb.eventlog(anotherlogdb.address)
```
**See the [Store](#store) section for details of common methods and properties.**
#### add(event)
```javascript
const hash = await db.add({ name: 'User1' })
```
#### get(hash)
```javascript
const event = db.get(hash)
.map((e) => e.payload.value)
// { name: 'User1' }
```
#### iterator([options])
**options** : It is an object which supports the following properties
`gt - (string)` Greater than, takes an item's `hash`.
`gte - (string)` Greater than or equal to, takes an item's `hash`.
`lt - (string)` Less than, takes an item's `hash`.
`lte - (string)` Less than or equal to, takes an item's `hash` value.
2017-03-30 18:43:47 +02:00
`limit - (integer)` Limiting the entries of result, defaults to `1`, and `-1` means all items (no limit).
2017-03-30 18:43:47 +02:00
`reverse - (boolean)` If set to true will result in reversing the result.
2017-03-30 18:43:47 +02:00
If `hash` not found when passing `gt`, `gte`, `lt`, or `lte`, the iterator will return all items (respecting `limit` and `reverse`).
```javascript
const all = db.iterator({ limit: -1 })
.collect()
.map((e) => e.payload.value)
// [{ name: 'User1' }]
```
2018-07-12 15:07:30 -04:00
### orbitdb.feed(name|address)
Module: [orbit-db-feedstore](https://github.com/orbitdb/orbit-db-feedstore)
```javascript
const db = await orbitdb.feed('orbit-db.issues')
// Or:
const db = await orbitdb.feed(anotherfeeddb.address)
```
See the [Store](#store) section for details of common methods and properties.
#### add(data)
```javascript
const hash = await db.add({ name: 'User1' })
```
#### get(hash)
```javascript
const event = db.get(hash)
.map((e) => e.payload.value)
// { name: 'User1' }
```
#### remove(hash)
```javascript
const hash = await db.remove(hash)
```
#### iterator([options])
**options** : It is an object which supports the following properties
`gt - (string)` Greater than, takes an item's `hash`.
`gte - (string)` Greater than or equal to, takes an item's `hash`.
`lt - (string)` Less than, takes an item's `hash`.
`lte - (string)` Less than or equal to, takes an item's `hash`.
`limit - (integer)` Limiting the entries of result, defaults to `1`, and `-1` means all items (no limit).
`reverse - (boolean)` If set to true will result in reversing the result.
If `hash` not found when passing `gt`, `gte`, `lt`, or `lte`, the iterator will return all items (respecting `limit` and `reverse`).
```javascript
const all = db.iterator({ limit: -1 })
.collect()
.map((e) => e.payload.value)
// [{ name: 'User1' }]
```
2017-03-30 18:43:47 +02:00
2018-07-12 15:07:30 -04:00
### orbitdb.docs(name|address, options)
2017-03-30 18:43:47 +02:00
Module: [orbit-db-docstore](https://github.com/orbitdb/orbit-db-docstore)
2017-03-30 18:43:47 +02:00
```javascript
const db = await orbitdb.docs('orbit.users.shamb0t.profile')
// Or:
const db = await orbitdb.docs(anotherdocdb.address)
```
By default, documents are indexed by field `_id`. You can also specify the field to index by:
```javascript
const db = await orbitdb.docs('orbit.users.shamb0t.profile', { indexBy: 'name' })
```
**See the [Store](#store) section for details of common methods and properties.**
#### put(doc)
```javascript
const hash = await db.put({ _id: 'QmAwesomeIpfsHash', name: 'shamb0t', followers: 500 })
```
#### get(key)
```javascript
const profile = db.get('shamb0t')
.map((e) => e.payload.value)
// [{ _id: 'shamb0t', name: 'shamb0t', followers: 500 }]
```
#### query(mapper)
```javascript
const all = db.query((doc) => doc.followers >= 500)
// [{ _id: 'shamb0t', name: 'shamb0t', followers: 500 }]
```
#### del(key)
```javascript
const hash = await db.del('shamb0t')
```
2018-07-12 15:07:30 -04:00
### orbitdb.counter(name|address)
Module: [orbit-db-counterstore](https://github.com/orbitdb/orbit-db-counterstore)
```javascript
const counter = await orbitdb.counter('song_123.play_count')
// Or:
const counter = await orbitdb.counter(anothercounterdb.address)
```
**See the [Store](#store) section for details of common methods and properties.**
#### value
```javascript
counter.value // 0
```
#### inc([value])
```javascript
await counter.inc()
counter.value // 1
await counter.inc(7)
counter.value // 8
await counter.inc(-2)
counter.value // 8
```
2018-07-12 15:33:28 -04:00
### orbitdb.create(name|address, type, [options])
### orbitdb.open(name|address, [options])
2018-07-12 15:07:30 -04:00
### orbitdb.stop()
2017-03-30 18:43:47 +02:00
Stop OrbitDB, close databases and disconnect the databases from the network.
2017-03-30 18:43:47 +02:00
```javascript
orbitdb.stop()
```
2018-07-12 15:33:28 -04:00
### orbitdb.disconnect()
2018-07-12 15:07:30 -04:00
## Static Properties
### OrbitDB.databaseTypes
Returns supported database types (i.e. store types) as an Array of strings
```js
OrbitDB.databaseTypes
// [ 'counter', 'eventlog', 'feed', 'docstore', 'keyvalue']
```
2018-07-12 15:07:30 -04:00
## Static Methods
2018-07-12 15:07:30 -04:00
### OrbitDB.isValidType(type)
Returns `true` if the provided string is a supported database type
```js
OrbitDB.isValidType('docstore')
// true
```
2018-07-12 15:07:30 -04:00
### OrbitDB.addDatabaseType(type, store)
Adds a custom database type & store to OrbitDB
```js
const CustomStore = require('./CustomStore')
OrbitDB.addDatabaseType(CustomStore.type, CustomStore)
```
2018-07-12 15:07:30 -04:00
### OrbitDB.getDatabaseTypes()
Returns an object mapping database types to Store Classes
```js
OrbitDB.getDatabaseTypes()
// { counter: [Function: CounterStore],
// eventlog: [Function: EventStore],
// feed: [Function: FeedStore],
// docstore: [Function: DocumentStore],
// keyvalue: [Function: KeyValueStore] }
```
2018-07-12 15:07:30 -04:00
### OrbitDB.isValidAddress(address)
Returns `true` if the provided string is a valid orbitdb address
```js
OrbitDB.isValidAddress('/orbitdb/Qmdgwt7w4uBsw8LXduzCd18zfGXeTmBsiR8edQ1hSfzcJC/first-database')
// true
```
2018-07-12 15:07:30 -04:00
### OrbitDB.parseAddress(address)
Returns an instance of OrbitDBAddress if the provided string is a valid orbitdb address
```js
OrbitDB.parseAddress('/orbitdb/Qmdgwt7w4uBsw8LXduzCd18zfGXeTmBsiR8edQ1hSfzcJC/first-database')
// OrbitDBAddress {
// root: 'Qmdgwt7w4uBsw8LXduzCd18zfGXeTmBsiR8edQ1hSfzcJC',
// path: 'first-database' }
```
2017-03-30 18:43:47 +02:00
## Store
Every database (store) has the following methods available in addition to their specific methods.
#### load()
Load the locally persisted database state to memory.
With events:
```javascript
db.events.on('ready', () => {
/* database is now ready to be queried */
})
db.load()
```
Async:
```javascript
await db.load()
/* database is now ready to be queried */
```
#### close()
2017-03-30 18:43:47 +02:00
Close the database.
2017-03-30 18:43:47 +02:00
Async:
```javascript
await db.close()
```
2017-03-30 18:43:47 +02:00
#### drop()
Remove the database locally. This does not delete any data from peers.
```javascript
await db.drop()
```
#### key
2017-11-29 21:23:08 +01:00
The [keypair](https://github.com/orbitdb/orbit-db/blob/master/GUIDE.md#keys) used to access the database.
```
const key = db.key
console.log(key)
// <Key priv: db8ef129f3d26ac5d7c17b402027488a8f4b2e7fa855c27d680b714cf9c1f87e
// pub: <EC Point x: f0e33d60f9824ce10b2c8983d3da0311933e82cf5ec9374cd82c0af699cbde5b
2017-11-29 21:23:08 +01:00
// y: ce206bfccf889465c6g6f9a7fdf452f9c3e1204a6f1b4582ec427ec12b116de9> >
```
The key contains the keypair used to sign the database entries. The public key can be retrieved with:
```
console.log(db.key.getPublic('hex'))
// 04d009bd530f2fa0cda29202e1b15e97247893cb1e88601968abfe787f7ea03828fdb7624a618fd67c4c437ad7f48e670cc5a6ea2340b896e42b0c8a3e4d54aebe
```
The key can also be accessed from the [OrbitDB](#orbitdb) instance: `orbitdb.key.getPublic('hex')`.
#### type
The type of the database as a string.
#### events
Each database in `orbit-db` contains an `events` ([EventEmitter](https://nodejs.org/api/events.html)) object that emits events that describe what's happening in the database. Events can be listened to with:
```javascript
db.events.on(name, callback)
```
2017-03-30 18:43:47 +02:00
- **`replicated`** - (address)
Emitted when a the database was synced with another peer. This is usually a good place to re-query the database for updated results, eg. if a value of a key was changed or if there are new events in an event log.
```javascript
db.events.on('replicated', (address) => ... )
```
- **`replicate`** - (address)
Emitted before replicating a part of the database with a peer.
```javascript
db.events.on('replicate', (address) => ... )
```
- **`replicate.progress`** - (address, hash, entry, progress, have)
Emitted while replicating a database. *address* is id of the database that emitted the event. *hash* is the multihash of the entry that was just loaded. *entry* is the database operation entry. *progress* is the current progress. *have* is a map of database pieces we have.
```javascript
db.events.on('replicate.progress', (address, hash, entry, progress, have) => ... )
```
- **`load`** - (dbname)
Emitted before loading the database.
```javascript
db.events.on('load', (dbname) => ... )
```
- **`load.progress`** - (address, hash, entry, progress, total)
Emitted while loading the local database, once for each entry. *dbname* is the name of the database that emitted the event. *hash* is the multihash of the entry that was just loaded. *entry* is the database operation entry. *progress* is a sequential number starting from 0 upon calling `load()`.
```javascript
db.events.on('load.progress', (address, hash, entry, progress, total) => ... )
```
2017-03-30 18:43:47 +02:00
- **`ready`** - (dbname)
2017-03-30 18:43:47 +02:00
Emitted after fully loading the local database.
2017-03-30 18:43:47 +02:00
```javascript
db.events.on('ready', (dbname) => ... )
```
- **`write`** - (dbname, hash, entry)
Emitted after an entry was added locally to the database. *hash* is the IPFS hash of the latest state of the database. *entry* is the added database op.
```javascript
db.events.on('write', (dbname, hash, entry) => ... )
```