Add API documentation. Fix examples. Improve README.

This commit is contained in:
haad 2016-10-05 10:33:45 +02:00
parent 0f03d60291
commit 9ca1930abb
11 changed files with 397 additions and 446 deletions

274
API.md Normal file
View File

@ -0,0 +1,274 @@
## orbit-db API documentation
**WORK IN PROGRESS**
#### Table of Contents
- [Getting Started](#getting-started)
- [orbitdb](#orbitdb)
- [kvstore(name)](#kvstorename)
- [put(key, value)](#kvstorename)
- [set(key, value)](#kvstorename)
- [get(key)](#kvstorename)
- [events](#kvstorename)
- [eventlog(name)](#eventlogname)
- [add(event)](#eventlogname)
- [get(hash)](#eventlogname)
- [iterator([options])](#eventlogname)
- [events](#eventlogname)
- [feed(name)](#feedname)
- [add(data)](#feedname)
- [get(hash)](#feedname)
- [iterator([options])](#feedname)
- [remove(hash)](#feedname)
- [events](#feedname)
- [counter(name)](#countername)
- [value](#countername)
- [inc([amount])](#countername)
- [events](#countername)
- [disconnect()](#disconnect)
- [events](#events)
- [orbitdb](#events)
- [stores](#events)
#### Getting Started
Install `orbit-db` and [ipfs](https://www.npmjs.com/package/ipfs) from npm:
```
npm install orbit-db ipfs
```
Require it in your program:
```javascript
const IPFS = require('ipfs')
const OrbitDB = require('orbit-db')
const ipfs = new IPFS()
const orbitdb = new OrbitDB(ipfs)
```
This will tell `orbit-db` to use the [Javascript implementation](https://github.com/ipfs/js-ipfs) of IPFS. Choose this options if you're using `orbitd-db` to develop **Browser** applications.
Alternatively, you can use [ipfs-api](https://npmjs.org/package/ipfs-api) to use `orbit-db` with a locally running IPFS daemon:
```
npm install orbit-db ipfs-api
```
```javascript
const IpfsApi = require('ipfs-api')
const OrbitDB = require('orbit-db')
const ipfs = IpfsApi('localhost', '5001')
const orbitdb = new OrbitDB(ipfs)
```
Choose this options if you're using `orbitd-db` to develop **Desktop** (or "headless") applications, eg. with [Electron](https://electron.atom.io).
#### orbitdb
After creating an instance of `orbitd-db`, you can now access the different data stores.
##### kvstore(name)
```javascript
const db = orbitdb.kvstore('application.settings')
```
- **put(key, value)**
```javascript
db.put('hello', { name: 'World' }).then(() => ...)
```
- **set(key, value)**
```javascript
db.set('hello', { name: 'Friend' }).then(() => ...)
```
- **get(key)**
```javascript
const value = db.get('hello')
// { name: 'Friend' }
```
- **events**
```javascript
db.events.on('data', (dbname, event) => ... )
```
See [events](#stores) for full description.
##### eventlog(name)
```javascript
const db = orbitdb.eventlog('site.visitors')
```
- **add(event)**
```javascript
db.add({ name: 'User1' }).then((hash) => ...)
```
- **get(hash)**
```javascript
const event = db.get(hash)
.map((e) => e.payload.value)
// { name: 'User1' }
```
- **iterator([options])**
```javascript
// TODO: add all options - gt, gte, lt, lte, limit, reverse
const all = db.iterator({ limit: -1 })
.collect()
.map((e) => e.payload.value)
// [{ name: 'User1' }]
```
- **events**
```javascript
db.events.on('data', (dbname, event) => ... )
```
See [events](#stores) for full description.
##### feed(name)
```javascript
const db = orbitdb.feed('orbit-db.issues')
```
- **add(data)**
```javascript
db.add({ name: 'User1' }).then((hash) => ...)
```
- **get(hash)**
```javascript
const event = db.get(hash)
.map((e) => e.payload.value)
// { name: 'User1' }
```
- **iterator([options])**
```javascript
// TODO: add all options - gt, gte, lt, lte, limit, reverse
const all = db.iterator({ limit: -1 })
.collect()
.map((e) => e.payload.value)
// [{ name: 'User1' }]
```
- **remove(hash)**
```javascript
db.remove(hash).then((removed) => ...)
```
- **events**
```javascript
db.events.on('data', (dbname, event) => ... )
```
See [events](#stores) for full description.
##### counter(name)
```javascript
const counter = orbitdb.counter('song_123.play_count')
```
- **value**
```javascript
counter.value // 0
```
- **inc([value])**
```javascript
counter.inc()
counter.value // 1
counter.inc(7)
counter.value // 8
counter.inc(-2)
counter.value // 8
```
- **events**
```javascript
db.events.on('data', (dbname, event) => ... )
```
See [events](#stores) for full description.
##### disconnect()
```javascript
orbitdb.disconnect()
```
##### events
- **orbitdb**
- `data` - (dbname, event)
Emitted when an update happens in any of the open databases.
```javascript
orbitdb.events.on('data', (dbname, event) => ...)
```
- **stores**
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.
- `data` - (dbname, event)
Emitted after an entry was added to the database
```javascript
db.events.on('data', (dbname, event) => ... )
```
- `sync` - (dbname)
Emitted before starting a database sync with a peer.
```javascript
db.events.on('sync', (dbname) => ... )
```
- `load` - (dbname, hash)
Emitted before loading the database history. *hash* is the hash from which the history is loaded from.
```javascript
db.events.on('load', (dbname, hash) => ... )
```
- `history` - (dbname, entries)
Emitted after loading the database history. *entries* is an Array of entries that were loaded.
```javascript
db.events.on('history', (dbname, entries) => ... )
```
- `ready` - (dbname)
Emitted after fully loading the database history.
```javascript
db.events.on('ready', (dbname) => ... )
```
- `write` - (dbname, hash)
Emitted after an entry was added locally to the database. *hash* is the IPFS hash of the latest state of the database.
```javascript
db.events.on('write', (dbname, hash) => ... )
```

200
README.md
View File

@ -1,14 +1,8 @@
# OrbitDB
# orbit-db
> Distributed, peer-to-peer database on IPFS.
[![npm version](https://badge.fury.io/js/orbit-db.svg)](https://badge.fury.io/js/orbit-db)
[![CircleCI Status](https://circleci.com/gh/haadcode/orbit-db.svg?style=shield)](https://circleci.com/gh/haadcode/orbit-db)
[![Project Status](https://badge.waffle.io/haadcode/orbit.svg?label=In%20Progress&title=In%20Progress)](https://waffle.io/haadcode/orbit?source=haadcode%2Forbit-db,haadcode%2Forbit-db-counterstore,haadcode%2Forbit-db-eventstore,haadcode%2Forbit-db-feedstore,haadcode%2Forbit-db-kvstore,haadcode%2Forbit-db-store,haadcode%2Fipfs-log)
## Introduction
`orbit-db` is a serverless, distributed, peer-to-peer database. `orbit-db` uses [IPFS]() as its data storage and [IPFS Pubsub]() to automatically sync databases with peers.
`orbit-db` is a serverless, distributed, peer-to-peer database. `orbit-db` uses [IPFS](https://ipfs.io) as its data storage and [IPFS Pubsub](https://github.com/ipfs/go-ipfs/blob/master/core/commands/pubsub.go) to automatically sync databases with peers. It's an eventually consistent database that uses [CRDTs](https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) for conflict-free database merges making `orbit-db` and excellent choice for offline-first applications.
Data in `orbit-db` can be stored in a
@ -19,9 +13,13 @@ Data in `orbit-db` can be stored in a
This is the Javascript implementation and it works both in **Node.js** and **Browsers**.
[![npm version](https://badge.fury.io/js/orbit-db.svg)](https://badge.fury.io/js/orbit-db)
[![CircleCI Status](https://circleci.com/gh/haadcode/orbit-db.svg?style=shield)](https://circleci.com/gh/haadcode/orbit-db)
[![Project Status](https://badge.waffle.io/haadcode/orbit.svg?label=In%20Progress&title=In%20Progress)](https://waffle.io/haadcode/orbit?source=haadcode%2Forbit-db,haadcode%2Forbit-db-counterstore,haadcode%2Forbit-db-eventstore,haadcode%2Forbit-db-feedstore,haadcode%2Forbit-db-kvstore,haadcode%2Forbit-db-store,haadcode%2Fipfs-log)
## Usage
```
npm install orbit-db
npm install orbit-db ipfs-api
```
```javascript
@ -40,9 +38,22 @@ db.add("hello world")
})
```
### API
See [API documentation](https://github.com/haadcode/orbit-db/blob/master/API.md) for the full documentation.
- [Getting Started](https://github.com/haadcode/orbit-db/blob/master/API.md#getting-started)
- [orbitdb](https://github.com/haadcode/orbit-db/blob/master/API.md#orbitdb)
- [kvstore(name)](https://github.com/haadcode/orbit-db/blob/master/API.md#kvstorename)
- [eventlog(name)](https://github.com/haadcode/orbit-db/blob/master/API.md#eventlogname)
- [feed(name)](https://github.com/haadcode/orbit-db/blob/master/API.md#feedname)
- [counter(name)](https://github.com/haadcode/orbit-db/blob/master/API.md#countername)
- [disconnect()](https://github.com/haadcode/orbit-db/blob/master/API.md#disconnect)
- [events](https://github.com/haadcode/orbit-db/blob/master/API.md#events)
## Examples
### Clone
### Install dependencies
```
git clone https://github.com/haadcode/orbit-db.git
@ -57,8 +68,9 @@ npm run build:examples
npm run examples:browser
```
<img src="https://raw.githubusercontent.com/haadcode/orbit-db/feat/ipfs-pubsub/screenshots/orbit-db-demo1.gif" height="50%">
<img src="https://raw.githubusercontent.com/haadcode/orbit-db/feat/ipfs-pubsub/screenshots/orbit-db-demo1.gif" width="33%">
Check the code in [examples/browser/index.js](https://github.com/haadcode/orbit-db/blob/master/examples/browser/index.js).
### Node.js example
@ -66,147 +78,19 @@ npm run examples:browser
npm run examples:node
```
<img src="https://raw.githubusercontent.com/haadcode/orbit-db/feat/ipfs-pubsub/screenshots/orbit-db-demo3.gif" width="60%">
<img src="https://raw.githubusercontent.com/haadcode/orbit-db/feat/ipfs-pubsub/screenshots/orbit-db-demo3.gif" width="66%">
See details in [example](https://github.com/haadcode/orbit-db/blob/master/examples/eventlog.js) and run it with:
**Eventlog**
Check the code in [examples/eventlog.js](https://github.com/haadcode/orbit-db/blob/master/examples/eventlog.js) and run it with:
```
LOG=debug node examples/eventlog.js
```
## API
**WORK IN PROGRESS**
- [Getting Started](#getting-started)
- [orbitdb](#orbitdb-1)
- [kvstore(name)]()
- [eventlog(name)]()
- [feed(name)]()
- [counter(name)]()
- [disconnect()]()
- [events]()
#### Getting Started
```javascript
const ipfs = require('ipfs')
const OrbitDB = require('orbit-db')
const orbitdb = new OrbitDB(ipfs)
**Key-Value**
Check the code in [examples/keyvalue.js](https://github.com/haadcode/orbit-db/blob/master/examples/eventlog.js) and run it with:
```
LOG=debug node examples/keyvalue.js
```
#### orbitdb
- **[kvstore](https://github.com/haadcode/orbit-db-kvstore)(name)**
```javascript
const db = orbitdb.kvstore('application.settings')
```
- **put(key, value)**
```javascript
db.put('hello', { name: 'World' }).then(() => ...)
```
- **set(key, value)**
```javascript
db.set('hello', { name: 'Friend' }).then(() => ...)
```
- **get(key)**
```javascript
const value = db.get('hello')
// { name: 'Friend' }
```
- **[eventlog](https://github.com/haadcode/orbit-db-eventstore)(name)**
```javascript
const db = orbitdb.eventlog('site.visitors')
```
- **add(event)**
```javascript
db.add({ name: 'User1' }).then((hash) => ...)
```
- **get(hash)**
```javascript
const event = db.get(hash)
.map((e) => e.payload.value)
// { name: 'User1' }
```
- **iterator(options)**
```javascript
// TODO: add all options - gt, gte, lt, lte, limit, reverse
const all = db.iterator({ limit: -1 })
.collect()
.map((e) => e.payload.value)
// [{ name: 'User1' }]
```
- **[feed](https://github.com/haadcode/orbit-db-feedstore)(name)**
```javascript
const db = orbitdb.feed('orbit-db.issues')
```
- **add(value)**
```javascript
db.add({ name: 'User1' }).then((hash) => ...)
```
- **get(hash)**
```javascript
const event = db.get(hash)
.map((e) => e.payload.value)
// { name: 'User1' }
```
- **iterator(options)**
```javascript
// TODO: add all options - gt, gte, lt, lte, limit, reverse
const all = db.iterator({ limit: -1 })
.collect()
.map((e) => e.payload.value)
// [{ name: 'User1' }]
```
- **remove(hash)**
```javascript
db.remove(hash).then((removed) => ...)
```
- **[counter](https://github.com/haadcode/orbit-db-counterstore)(name)**
```javascript
const counter = orbitdb.counter('song_123.play_count')
```
- **value**
```javascript
counter.value // 0
```
- **inc([value])**
```javascript
counter.inc()
counter.value // 1
counter.inc(7)
counter.value // 8
counter.inc(-2)
counter.value // 8
```
- **events**
- `data` - (dbname, event)
```javascript
orbitdb.events.on('data', (dbname, event) => ...)
```
- **disconnect()**
```javascript
orbitdb.disconnect()
```
## Development
@ -220,24 +104,26 @@ npm test
npm run build
```
#### Benchmark
```
node examples/benchmark.js
```
## Background
Check out a visualization of the data flow at https://github.com/haadcode/proto2 or a live demo: http://celebdil.benet.ai:8080/ipfs/Qmezm7g8mBpWyuPk6D84CNcfLKJwU6mpXuEN5GJZNkX3XK/.
**TODO**
Check out a visualization of the data flow at https://github.com/haadcode/proto2
Live demo: http://celebdil.benet.ai:8080/ipfs/Qmezm7g8mBpWyuPk6D84CNcfLKJwU6mpXuEN5GJZNkX3XK/
![Screenshot](https://raw.githubusercontent.com/haadcode/proto2/master/screenshot.png)
**TODO: list of modules used, orbit-db-pubsub, etc.**
- list of modules used
- orbit-db-pubsub
- crdts
- ipfs-log
## Contributing
**TODO**
Issues and PRs welcome!
Issues, comments, feedback, feature requests and PRs highly welcome!
## License
MIT (c) 2016 Haadcode
MIT © 2016 Haadcode

View File

@ -1,88 +0,0 @@
'use strict';
const await = require('asyncawait/await');
const async = require('asyncawait/async');
const ipfsd = require('ipfsd-ctl');
const OrbitDB = require('../src/OrbitDB');
const Timer = require('./Timer');
// usage: benchmark.js <host> <username> <channel>;
// orbit-server
const network = 'QmaAHGFm78eupEaDFzBfhUL5xn32dbeqn8oU2XCZJTQGBj'; // 'localhost:3333'
const username = process.argv[2] ? process.argv[2] : 'testrunner';
const password = '';
const channelName = process.argv[3] ? process.argv[3] : 'c2';
const startIpfs = () => {
return new Promise((resolve, reject) => {
// ipfsd.disposableApi((err, ipfs) => {
// if(err) console.error(err);
// resolve(ipfs);
// });
ipfsd.local((err, node) => {
if(err) reject(err);
node.startDaemon((err, ipfs) => {
if(err) reject(err);
resolve(ipfs);
});
});
});
};
let run = (async(() => {
try {
// Connect
const ipfs = await(startIpfs());
const orbit = await(OrbitDB.connect(network, username, password, ipfs));
const db = await(orbit.kvstore(channelName));
// Metrics
let totalQueries = 0;
let seconds = 0;
let queriesPerSecond = 0;
let lastTenSeconds = 0;
// Metrics output
setInterval(() => {
seconds ++;
if(seconds % 10 === 0) {
console.log(`--> Average of ${lastTenSeconds/10} q/s in the last 10 seconds`)
if(lastTenSeconds === 0)
throw new Error("Problems!");
lastTenSeconds = 0
}
console.log(`${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds`)
queriesPerSecond = 0;
}, 1000);
const query = async(() => {
// let timer = new Timer();
// timer.start();
try {
await(db.put("keyA", username + totalQueries));
// console.log(`${timer.stop(true)} ms`);
totalQueries ++;
lastTenSeconds ++;
queriesPerSecond ++;
} catch(e) {
console.log(e);
}
process.nextTick(query);
});
query();
} catch(e) {
console.error("error:", e);
console.error(e.stack);
process.exit(1);
}
}))();
module.exports = run;

View File

@ -1,11 +1,8 @@
'use strict'
const IpfsApi = require('ipfs-api')
const IpfsDaemon = require('ipfs-daemon')
const OrbitDB = require('../src/OrbitDB')
const username = process.argv[2] ? process.argv[2] : 'testrunner'
const channelName = process.argv[3] ? process.argv[3] : 'c1'
// Metrics
let totalQueries = 0
let seconds = 0
@ -14,7 +11,7 @@ let lastTenSeconds = 0
// Main loop
const queryLoop = (db) => {
db.add(username + totalQueries).then(() => {
db.add(totalQueries).then(() => {
totalQueries ++
lastTenSeconds ++
queriesPerSecond ++
@ -22,28 +19,30 @@ const queryLoop = (db) => {
})
}
// Start
let run = (() => {
// Connect
console.log(`Connecting...`)
const ipfs = IpfsApi('localhost', '5001')
const orbit = new OrbitDB(ipfs, 'benchmark')
const db = orbit.eventlog(channelName)
IpfsDaemon()
.then((res) => {
const orbit = new OrbitDB(res.ipfs, 'benchmark')
const db = orbit.eventlog('orbit-db.benchmark')
// Metrics output
setInterval(() => {
seconds ++
if(seconds % 10 === 0) {
console.log(`--> Average of ${lastTenSeconds/10} q/s in the last 10 seconds`)
if(lastTenSeconds === 0)
throw new Error("Problems!")
lastTenSeconds = 0
}
console.log(`${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds`)
queriesPerSecond = 0
}, 1000)
// Metrics output
setInterval(() => {
seconds ++
if(seconds % 10 === 0) {
console.log(`--> Average of ${lastTenSeconds/10} q/s in the last 10 seconds`)
if(lastTenSeconds === 0)
throw new Error("Problems!")
lastTenSeconds = 0
}
console.log(`${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds`)
queriesPerSecond = 0
}, 1000)
// Start
queryLoop(db)
// Start the main loop
queryLoop(db)
})
.catch((e) => console.error(e))
})()
module.exports = run

View File

@ -1,47 +0,0 @@
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="result">Loading...</div>
<script type="text/javascript" src="../../dist/orbitdb.min.js" charset="utf-8"></script>
<script type="text/javascript" src="../../node_modules/ipfs/dist/index.min.js" charset="utf-8"></script>
<script type="text/javascript">
const network = '178.62.241.75:3333'
const username = 'user1'
const password = ''
const channel = 'browsertest2.dist'
const key = 'greeting'
const value = 'Hello world'
const elm = document.getElementById("result")
const ipfs = new window.Ipfs()
OrbitDB.connect(network, username, password, ipfs).then((orbit) => {
orbit.kvstore(channel).then((db) => {
let count = 1
const query = () => {
const startTime = new Date().getTime()
db.put(key, value + " " + count).then((res) => {
const endTime = new Date().getTime()
console.log(`db.put (#${count}) took ${(endTime - startTime)} ms\n`)
count ++
const result = db.get(key)
const output = `
---------------------------------------------------
Key | Value
---------------------------------------------------
${key} | ${result}
---------------------------------------------------`
elm.innerHTML = output.split("\n").join("<br>")
console.log(output)
}).catch((e) => console.error(e))
};
setInterval(query, 1000)
}).catch((e) => console.error(e))
}).catch((e) => console.error(e))
</script>
</body>
</html>

View File

@ -39,31 +39,31 @@ try {
const output =
`<b>Key-Value Store</b>
---------------------------------------------------
-------------------------------------------------------
Key | Value
---------------------------------------------------
-------------------------------------------------------
${key} | ${result}
---------------------------------------------------
-------------------------------------------------------
<b>Eventlog</b>
---------------------------------------------------
-------------------------------------------------------
Latest Visitors
---------------------------------------------------
${latest.reverse().map((e) => e.payload.value + " (" + e.payload.from + ") at" + new Date(e.payload.meta.ts).toISOString()).join('\n')}
-------------------------------------------------------
${latest.reverse().map((e) => e.payload.value + " at " + new Date(e.payload.meta.ts).toISOString()).join('\n')}
<b>Counter</b>
---------------------------------------------------
-------------------------------------------------------
Visitor Count: ${count}
---------------------------------------------------
-------------------------------------------------------
`
elm.innerHTML = output.split("\n").join("<br>")
})
.catch((e) => {
elm.innerHTML = "<i>" + e.message + "</i><br><br>" + "Make sure you have an IPFS daemon running at localhost:5001"
elm.innerHTML = "<i>" + e.message + "</i><br><br>" + "Waiting for IPFS daemon to start..."
console.error(e.stack)
})
}
setInterval(query, 1000)
setInterval(query, Math.random() * 3 * 1000)
} catch(e) {
console.error(e.stack)

View File

@ -1,61 +0,0 @@
'use strict';
const async = require('asyncawait/async');
const await = require('asyncawait/await');
const ipfsd = require('ipfsd-ctl');
const OrbitDB = require('../src/OrbitDB');
const Timer = require('./Timer');
// usage: reader.js <network hash> <username> <channel> <interval in ms>
// orbit-server
const network = '178.62.241.75:3333'; // 'localhost:3333'
const username = process.argv[2] ? process.argv[2] : 'testrunner';
const password = '';
const channelName = process.argv[3] ? process.argv[3] : 'c2';
const interval = process.argv[4] ? process.argv[4] : 1000;
const startIpfs = () => {
return new Promise((resolve, reject) => {
ipfsd.disposableApi((err, ipfs) => {
if(err) console.error(err);
resolve(ipfs);
});
});
};
let run = (async(() => {
try {
const ipfs = await(startIpfs());
const orbit = await(OrbitDB.connect(network, username, password, ipfs));
const db = orbit.eventlog(channelName);
let count = 1;
let running = false;
setInterval(async(() => {
if(!running) {
running = true;
let timer2 = new Timer(true);
let items = db.iterator({ limit: 20 }).collect();
console.log("---------------------------------------------------")
console.log("Timestamp | Value")
console.log("---------------------------------------------------")
console.log(items.map((e) => `${e.payload.meta.ts} | ${e.payload.value}`).join("\n"));
console.log("---------------------------------------------------")
console.log(`Query #${count} took ${timer2.stop(true)} ms\n`);
running = false;
count ++;
}
}), interval);
} catch(e) {
console.error(e.stack);
console.log("Exiting...")
process.exit(1);
}
}))();
module.exports = run;

View File

@ -3,7 +3,7 @@
const IpfsDaemon = require('ipfs-daemon')
const OrbitDB = require('../src/OrbitDB')
const userId = Math.floor(Math.random() * 100)
const userId = Math.floor(Math.random() * 1000)
const conf = {
IpfsDataDir: '/tmp/' + userId,
Addresses: {
@ -13,6 +13,8 @@ const conf = {
},
}
console.log("Starting...")
IpfsDaemon(conf)
.then((res) => {
const orbitdb = new OrbitDB(res.ipfs)

View File

@ -1,62 +1,47 @@
'use strict';
'use strict'
const async = require('asyncawait/async');
const await = require('asyncawait/await');
// const IPFS = require('ipfs')
const ipfsd = require('ipfsd-ctl');
const OrbitDB = require('../src/OrbitDB');
const Timer = require('./Timer');
const IpfsDaemon = require('ipfs-daemon')
const OrbitDB = require('../src/OrbitDB')
// usage: keyvalue.js <network hash> <username> <channel> <key> <value>
const userId = Math.floor(Math.random() * 1000)
const conf = {
IpfsDataDir: '/tmp/' + userId,
Addresses: {
API: '/ip4/127.0.0.1/tcp/0',
Swarm: ['/ip4/0.0.0.0/tcp/0'],
Gateway: '/ip4/0.0.0.0/tcp/0'
},
}
// orbit-server
const network = 'QmYPobvobKsyoCKTw476yTui611XABf927KxUPCf4gRLRr'; // 'localhost:3333'
const username = process.argv[2] ? process.argv[2] : 'testrunner';
const password = '';
const channelName = process.argv[3] ? process.argv[3] : 'c1';
console.log("Starting...")
const startIpfs = () => {
return new Promise((resolve, reject) => {
ipfsd.disposableApi((err, ipfs) => {
if(err) console.error(err);
resolve(ipfs);
});
// const ipfs = new IPFS()
// ipfs.goOnline(() => {
// resolve(ipfs)
// })
});
};
IpfsDaemon(conf)
.then((res) => {
const orbitdb = new OrbitDB(res.ipfs)
const db = orbitdb.kvstore("|orbit-db|examples|kvstore-example")
let run = (async(() => {
try {
const ipfs = await(startIpfs());
const orbit = await(OrbitDB.connect(network, username, password, ipfs));
const db = await(orbit.kvstore(channelName));
const creatures = ['🐙', '🐬', '🐋', '🐠', '🐡', '🦀', '🐢', '🐟', '🐳']
let count = 1;
while(true) {
const key = process.argv[5] ? process.argv[5] : 'greeting';
const value = process.argv[6] ? process.argv[6] : 'Hello world';
const timer = new Timer(true);
await(db.put(key, value + " " + count));
const result = db.get(key);
console.log("---------------------------------------------------")
console.log("Key | Value")
console.log("---------------------------------------------------")
console.log(`${key} | ${result}`);
console.log("---------------------------------------------------")
console.log(`Query #${count} took ${timer.stop(true)} ms\n`);
count ++;
const query = () => {
const index = Math.floor(Math.random() * creatures.length)
db.put(userId, { avatar: creatures[index], updated: new Date().getTime() })
.then(() => {
const user = db.get(userId)
let output = `\n`
output += `----------------------\n`
output += `User\n`
output += `----------------------\n`
output += `Id: ${userId}\n`
output += `Avatar: ${user.avatar}\n`
output += `Updated: ${user.updated}\n`
output += `----------------------`
console.log(output)
})
.catch((e) => {
console.error(e.stack)
})
}
} catch(e) {
console.error(e.stack);
process.exit(1);
}
}))();
module.exports = run;
setInterval(query, 1000)
})
.catch((err) => console.error(err))

View File

@ -1,6 +1,7 @@
const IpfsDaemon = require('ipfs-daemon')
module.exports = IpfsDaemon({
IpfsDataDir: './tmp',
IpfsDataDir: '/tmp/orbit-db-examples',
API: {
HTTPHeaders: {
"Access-Control-Allow-Origin": ['*'],
@ -9,5 +10,5 @@ module.exports = IpfsDaemon({
}
}
})
.then((res) => console.log("started"))
.then((res) => console.log("Started IPFS daemon"))
.catch((err) => console.error(err))

View File

@ -40,8 +40,8 @@
"webpack": "^2.1.0-beta.7"
},
"scripts": {
"examples": "npm run example:node",
"examples:node": "LOG=debug node examples/eventlog.js",
"examples": "npm run examples:node",
"examples:node": "node examples/eventlog.js",
"examples:browser": "open examples/browser/index.html && LOG=debug node examples/start-daemon.js",
"postinstall": "./scripts/post_install.sh",
"test": "mocha",