From 9ca1930abbb467efaeaa10fb866c98948c689c64 Mon Sep 17 00:00:00 2001 From: haad Date: Wed, 5 Oct 2016 10:33:45 +0200 Subject: [PATCH] Add API documentation. Fix examples. Improve README. --- API.md | 274 ++++++++++++++++++++++++++++++++++ README.md | 200 ++++++------------------- examples/benchmark-kv.js | 88 ----------- examples/benchmark.js | 47 +++--- examples/browser/browser.html | 47 ------ examples/browser/index.js | 20 +-- examples/eventlog-reader.js | 61 -------- examples/eventlog.js | 4 +- examples/keyvalue.js | 93 +++++------- examples/start-daemon.js | 5 +- package.json | 4 +- 11 files changed, 397 insertions(+), 446 deletions(-) create mode 100644 API.md delete mode 100644 examples/benchmark-kv.js delete mode 100644 examples/browser/browser.html delete mode 100644 examples/eventlog-reader.js diff --git a/API.md b/API.md new file mode 100644 index 0000000..8e9f5ee --- /dev/null +++ b/API.md @@ -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) => ... ) + ``` diff --git a/README.md b/README.md index 27e8d3b..00cf92a 100644 --- a/README.md +++ b/README.md @@ -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 ``` - + +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 ``` - + -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 diff --git a/examples/benchmark-kv.js b/examples/benchmark-kv.js deleted file mode 100644 index 648d002..0000000 --- a/examples/benchmark-kv.js +++ /dev/null @@ -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 ; - -// 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; diff --git a/examples/benchmark.js b/examples/benchmark.js index 7d25808..8a286ba 100644 --- a/examples/benchmark.js +++ b/examples/benchmark.js @@ -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 diff --git a/examples/browser/browser.html b/examples/browser/browser.html deleted file mode 100644 index fd08c6d..0000000 --- a/examples/browser/browser.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - -
Loading...
- - - - - - diff --git a/examples/browser/index.js b/examples/browser/index.js index 806e858..ba69016 100644 --- a/examples/browser/index.js +++ b/examples/browser/index.js @@ -39,31 +39,31 @@ try { const output = `Key-Value Store ---------------------------------------------------- +------------------------------------------------------- Key | Value ---------------------------------------------------- +------------------------------------------------------- ${key} | ${result} ---------------------------------------------------- +------------------------------------------------------- Eventlog ---------------------------------------------------- +------------------------------------------------------- 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')} Counter ---------------------------------------------------- +------------------------------------------------------- Visitor Count: ${count} ---------------------------------------------------- +------------------------------------------------------- ` elm.innerHTML = output.split("\n").join("
") }) .catch((e) => { - elm.innerHTML = "" + e.message + "

" + "Make sure you have an IPFS daemon running at localhost:5001" + elm.innerHTML = "" + e.message + "

" + "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) diff --git a/examples/eventlog-reader.js b/examples/eventlog-reader.js deleted file mode 100644 index 7b1cff1..0000000 --- a/examples/eventlog-reader.js +++ /dev/null @@ -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 - -// 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; diff --git a/examples/eventlog.js b/examples/eventlog.js index d3ee6ff..d2006c4 100644 --- a/examples/eventlog.js +++ b/examples/eventlog.js @@ -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) diff --git a/examples/keyvalue.js b/examples/keyvalue.js index 1e17dd6..8eccf8b 100644 --- a/examples/keyvalue.js +++ b/examples/keyvalue.js @@ -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 +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)) diff --git a/examples/start-daemon.js b/examples/start-daemon.js index 5652059..042a9bf 100644 --- a/examples/start-daemon.js +++ b/examples/start-daemon.js @@ -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)) diff --git a/package.json b/package.json index 0c3209c..103204a 100644 --- a/package.json +++ b/package.json @@ -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",