From 4226921b22d2b5a4d5c391a6dbf0024ff198aafc Mon Sep 17 00:00:00 2001 From: Mark Henderson Date: Fri, 31 May 2019 15:56:52 -0400 Subject: [PATCH] Reversting lint fixes --- benchmarks/benchmark-add-go-ipfs.js | 19 ++-- benchmarks/benchmark-add.js | 29 ++--- benchmarks/benchmark-replication-sender.js | 40 +++---- benchmarks/benchmark-replication.js | 34 +++--- conf/webpack.config.js | 10 +- conf/webpack.debug.config.js | 12 +- conf/webpack.example.config.js | 9 +- .../browser/browser-webpack-example/index.js | 6 +- examples/browser/example.js | 104 ++++++++++-------- examples/eventlog.js | 8 +- examples/keyvalue.js | 13 ++- package-lock.json | 2 +- src/OrbitDB.js | 86 +++++++++------ src/db-manifest.js | 2 +- src/exchange-heads.js | 2 +- src/orbit-db-address.js | 6 +- src/utils/index.js | 4 +- test/counterdb.test.js | 24 ++-- test/create-open.test.js | 29 ++--- test/create-type.test.js | 4 +- test/custom-cache.test.js | 16 +-- test/custom-keystore.test.js | 16 +-- test/docstore.test.js | 62 ++++++----- test/drop.test.js | 12 +- test/eventlog.test.js | 33 +++--- test/feed.test.js | 35 +++--- test/kvstore.test.js | 10 +- test/multiple-databases.test.js | 45 ++++---- test/orbit-db-address.test.js | 9 +- test/persistency.js | 33 +++--- test/replicate-and-load.test.js | 26 +++-- test/replicate-automatically.test.js | 22 ++-- test/replicate.test.js | 104 ++++++++++-------- test/replication-status.test.js | 13 ++- test/utils/config.js | 10 +- test/utils/custom-test-keystore.js | 8 +- test/utils/databases.js | 14 +-- test/utils/test-apis.js | 11 +- test/v0-open-load.js | 24 ++-- test/write-permissions.test.js | 22 ++-- 40 files changed, 542 insertions(+), 426 deletions(-) diff --git a/benchmarks/benchmark-add-go-ipfs.js b/benchmarks/benchmark-add-go-ipfs.js index 7a35d2033..6f84f1bc4 100644 --- a/benchmarks/benchmark-add-go-ipfs.js +++ b/benchmarks/benchmark-add-go-ipfs.js @@ -12,14 +12,14 @@ let lastTenSeconds = 0 // Main loop const queryLoop = async (db) => { await db.add(totalQueries) - totalQueries++ - lastTenSeconds++ - queriesPerSecond++ + totalQueries ++ + lastTenSeconds ++ + queriesPerSecond ++ setImmediate(() => queryLoop(db)) } // Start -console.log('Starting...') +console.log("Starting...") // Make sure you have a local IPFS daemon running! const ipfs = IPFS('127.0.0.1') @@ -28,15 +28,16 @@ const run = async () => { try { const orbit = await OrbitDB.createInstance(ipfs, { directory: './orbitdb/benchmarks' }) const db = await orbit.eventlog('orbit-db.benchmark', { - replicate: false + replicate: false, }) // 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!') } + 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 (Oplog: ${db._oplog.length})`) diff --git a/benchmarks/benchmark-add.js b/benchmarks/benchmark-add.js index edb260f28..a91bf5f6e 100644 --- a/benchmarks/benchmark-add.js +++ b/benchmarks/benchmark-add.js @@ -14,19 +14,19 @@ let lastTenSeconds = 0 // Main loop const queryLoop = async (db) => { await db.add(totalQueries) - totalQueries++ - lastTenSeconds++ - queriesPerSecond++ + totalQueries ++ + lastTenSeconds ++ + queriesPerSecond ++ setImmediate(() => queryLoop(db)) } // Start -console.log('Starting IPFS daemon...') +console.log("Starting IPFS daemon...") const repoConf = { storageBackends: { - blocks: DatastoreLevel - } + blocks: DatastoreLevel, + }, } const ipfs = new IPFS({ @@ -35,8 +35,8 @@ const ipfs = new IPFS({ EXPERIMENTAL: { pubsub: false, sharding: false, - dht: false - } + dht: false, + }, }) ipfs.on('error', (err) => console.error(err)) @@ -44,17 +44,18 @@ ipfs.on('error', (err) => console.error(err)) ipfs.on('ready', async () => { const run = async () => { try { - const orbit = await OrbitDB.createInstance(ipfs, { directory: './orbitdb/benchmarks' }) + const orbit = await OrbitDB.createInstance(ipfs,{ directory: './orbitdb/benchmarks' }) const db = await orbit.eventlog('orbit-db.benchmark', { - replicate: false + replicate: false, }) // 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!') } + 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 (Oplog: ${db._oplog.length})`) diff --git a/benchmarks/benchmark-replication-sender.js b/benchmarks/benchmark-replication-sender.js index b4120d554..e37941043 100644 --- a/benchmarks/benchmark-replication-sender.js +++ b/benchmarks/benchmark-replication-sender.js @@ -12,7 +12,7 @@ let metrics1 = { totalQueries: 0, seconds: 0, queriesPerSecond: 0, - lastTenSeconds: 0 + lastTenSeconds: 0, } const ipfsConf = { @@ -26,14 +26,14 @@ const ipfsConf = { MDNS: { Enabled: true, Interval: 1 - } - } + }, + }, } const repoConf = { storageBackends: { - blocks: DatastoreLevel - } + blocks: DatastoreLevel, + }, } const defaultConfig = Object.assign({}, { @@ -41,7 +41,7 @@ const defaultConfig = Object.assign({}, { EXPERIMENTAL: { pubsub: true, sharding: false, - dht: false + dht: false, }, config: ipfsConf }) @@ -56,34 +56,34 @@ const queryLoop = async (db) => { try { await db.add(metrics1.totalQueries) } catch (e) { - console.error(e) + console.error(e) } - metrics1.totalQueries++ - metrics1.lastTenSeconds++ - metrics1.queriesPerSecond++ + metrics1.totalQueries ++ + metrics1.lastTenSeconds ++ + metrics1.queriesPerSecond ++ setImmediate(() => queryLoop(db)) } } // Metrics output function const outputMetrics = (name, db, metrics) => { - metrics.seconds++ - console.log(`[${name}] ${metrics.queriesPerSecond} queries per second, ${metrics.totalQueries} queries in ${metrics.seconds} seconds (Oplog: ${db._oplog.length})`) - metrics.queriesPerSecond = 0 + metrics.seconds ++ + console.log(`[${name}] ${metrics.queriesPerSecond} queries per second, ${metrics.totalQueries} queries in ${metrics.seconds} seconds (Oplog: ${db._oplog.length})`) + metrics.queriesPerSecond = 0 - if (metrics.seconds % 10 === 0) { - console.log(`[${name}] --> Average of ${metrics.lastTenSeconds / 10} q/s in the last 10 seconds`) - metrics.lastTenSeconds = 0 - } + if(metrics.seconds % 10 === 0) { + console.log(`[${name}] --> Average of ${metrics.lastTenSeconds/10} q/s in the last 10 seconds`) + metrics.lastTenSeconds = 0 + } } const database = 'benchmark-replication' const updateCount = 20000 // Start -console.log('Starting IPFS daemons...') +console.log("Starting IPFS daemons...") -pMapSeries([conf1], d => startIpfs('js-ipfs', d)) +pMapSeries([conf1,], d => startIpfs('js-ipfs', d)) .then(async ([ipfs1]) => { try { // Create the databases @@ -108,7 +108,7 @@ pMapSeries([conf1], d => startIpfs('js-ipfs', d)) // Metrics output for the writer, once/sec const writeInterval = setInterval(() => { - outputMetrics('WRITE', db1, metrics1) + outputMetrics("WRITE", db1, metrics1) if (metrics1.totalQueries === updateCount) { clearInterval(writeInterval) } diff --git a/benchmarks/benchmark-replication.js b/benchmarks/benchmark-replication.js index ed6f9b472..eaaf69c8c 100644 --- a/benchmarks/benchmark-replication.js +++ b/benchmarks/benchmark-replication.js @@ -12,7 +12,7 @@ let metrics2 = { totalQueries: 0, seconds: 0, queriesPerSecond: 0, - lastTenSeconds: 0 + lastTenSeconds: 0, } const ipfsConf = { @@ -26,14 +26,14 @@ const ipfsConf = { MDNS: { Enabled: true, Interval: 0 - } - } + }, + }, } const repoConf = { storageBackends: { - blocks: DatastoreLevel - } + blocks: DatastoreLevel, + }, } const defaultConfig = Object.assign({}, { @@ -41,7 +41,7 @@ const defaultConfig = Object.assign({}, { EXPERIMENTAL: { pubsub: true, sharding: false, - dht: false + dht: false, }, config: ipfsConf }) @@ -52,21 +52,21 @@ const conf2 = Object.assign({}, defaultConfig, { // Metrics output function const outputMetrics = (name, db, metrics) => { - metrics.seconds++ - console.log(`[${name}] ${metrics.queriesPerSecond} queries per second, ${metrics.totalQueries} queries in ${metrics.seconds} seconds (Oplog: ${db._oplog.length})`) - metrics.queriesPerSecond = 0 - - if (metrics.seconds % 10 === 0) { - console.log(`[${name}] --> Average of ${metrics.lastTenSeconds / 10} q/s in the last 10 seconds`) - metrics.lastTenSeconds = 0 - } + metrics.seconds ++ + console.log(`[${name}] ${metrics.queriesPerSecond} queries per second, ${metrics.totalQueries} queries in ${metrics.seconds} seconds (Oplog: ${db._oplog.length})`) + metrics.queriesPerSecond = 0 + + if(metrics.seconds % 10 === 0) { + console.log(`[${name}] --> Average of ${metrics.lastTenSeconds/10} q/s in the last 10 seconds`) + metrics.lastTenSeconds = 0 + } } const database = 'benchmark-replication' const updateCount = 20000 // Start -console.log('Starting IPFS daemons...') +console.log("Starting IPFS daemons...") pMapSeries([conf2], d => startIpfs('js-ipfs', d)) .then(async ([ipfs2]) => { @@ -97,10 +97,10 @@ pMapSeries([conf2], d => startIpfs('js-ipfs', d)) metrics2.lastTenSeconds += metrics2.queriesPerSecond prevCount = metrics2.totalQueries - outputMetrics('READ', db2, metrics2) + outputMetrics("READ", db2, metrics2) if (db2._oplog.length === updateCount) { - console.log('Finished') + console.log("Finished") process.exit(0) } } catch (e) { diff --git a/conf/webpack.config.js b/conf/webpack.config.js index ee142d866..0b452adde 100644 --- a/conf/webpack.config.js +++ b/conf/webpack.config.js @@ -14,12 +14,12 @@ module.exports = { devtool: 'none', externals: { fs: '{}', - mkdirp: '{}' + mkdirp: '{}', }, node: { console: false, Buffer: true, - mkdirp: 'empty' + mkdirp: "empty" }, plugins: [ new webpack.DefinePlugin({ @@ -34,8 +34,8 @@ module.exports = { path.resolve(__dirname, '../node_modules') ], alias: { - leveldown: 'level-js' - } + leveldown: 'level-js', + }, }, resolveLoader: { modules: [ @@ -43,5 +43,5 @@ module.exports = { path.resolve(__dirname, '../node_modules') ], moduleExtensions: ['-loader'] - } + }, } diff --git a/conf/webpack.debug.config.js b/conf/webpack.debug.config.js index ed79bf091..812065684 100644 --- a/conf/webpack.debug.config.js +++ b/conf/webpack.debug.config.js @@ -13,13 +13,13 @@ module.exports = { devtool: 'source-map', externals: { fs: '{}', - mkdirp: '{}' + mkdirp: '{}', }, node: { console: false, Buffer: true, - mkdirp: 'empty', - fs: 'empty' + mkdirp: "empty", + fs: "empty" }, plugins: [ ], @@ -29,8 +29,8 @@ module.exports = { path.resolve(__dirname, '../node_modules') ], alias: { - leveldown: 'level-js' - } + leveldown: 'level-js', + }, }, resolveLoader: { modules: [ @@ -38,5 +38,5 @@ module.exports = { path.resolve(__dirname, '../node_modules') ], moduleExtensions: ['-loader'] - } + }, } diff --git a/conf/webpack.example.config.js b/conf/webpack.example.config.js index 345cf2d1c..0bc79c998 100644 --- a/conf/webpack.example.config.js +++ b/conf/webpack.example.config.js @@ -10,6 +10,11 @@ module.exports = { }, target: 'web', devtool: 'none', + node: { + Buffer: true, + mkdirp: "empty", + fs: "empty" + }, plugins: [ new webpack.DefinePlugin({ 'process.env': { @@ -21,7 +26,7 @@ module.exports = { modules: [ 'node_modules', path.resolve(__dirname, '../node_modules') - ] + ], }, resolveLoader: { modules: [ @@ -29,5 +34,5 @@ module.exports = { path.resolve(__dirname, '../node_modules') ], moduleExtensions: ['-loader'] - } + }, } diff --git a/examples/browser/browser-webpack-example/index.js b/examples/browser/browser-webpack-example/index.js index 22c315185..58cb9f508 100644 --- a/examples/browser/browser-webpack-example/index.js +++ b/examples/browser/browser-webpack-example/index.js @@ -4,7 +4,7 @@ This is the entry point for Webpack to build the bundle from. We use the same example code as the html browser example, but we inject the Node.js modules of OrbitDB and IPFS into - the example. + the example. In the html example, IPFS and OrbitDB are loaded from the minified distribution builds (in '../lib') @@ -17,11 +17,11 @@ import IPFS from 'ipfs' import OrbitDB from '../../..' // When 'orbit-db' was installed from npm, use with: -// import OrbitDB from 'orbit-db' +// import OrbitDB from 'orbit-db' // Example main code const example = require('../example') -// Call the start function and pass in the +// Call the start function and pass in the // IPFS and OrbitDB modules example(IPFS, OrbitDB) diff --git a/examples/browser/example.js b/examples/browser/example.js index d44c4f088..b9de405eb 100644 --- a/examples/browser/example.js +++ b/examples/browser/example.js @@ -1,25 +1,25 @@ const creatures = [ - '🐙', '🐷', '🐬', '🐞', + '🐙', '🐷', '🐬', '🐞', '🐈', '🙉', '🐸', '🐓', '🐊', '🕷', '🐠', '🐘', '🐼', '🐰', '🐶', '🐥' ] -const outputHeaderElm = document.getElementById('output-header') -const outputElm = document.getElementById('output') -const statusElm = document.getElementById('status') -const dbnameField = document.getElementById('dbname') -const dbAddressField = document.getElementById('dbaddress') -const createButton = document.getElementById('create') -const openButton = document.getElementById('open') -const createType = document.getElementById('type') -const writerText = document.getElementById('writerText') -const publicCheckbox = document.getElementById('public') -const readonlyCheckbox = document.getElementById('readonly') - -function handleError (e) { +const outputHeaderElm = document.getElementById("output-header") +const outputElm = document.getElementById("output") +const statusElm = document.getElementById("status") +const dbnameField = document.getElementById("dbname") +const dbAddressField = document.getElementById("dbaddress") +const createButton = document.getElementById("create") +const openButton = document.getElementById("open") +const createType = document.getElementById("type") +const writerText = document.getElementById("writerText") +const publicCheckbox = document.getElementById("public") +const readonlyCheckbox = document.getElementById("readonly") + +function handleError(e) { console.error(e.stack) - statusElm.innerHTML = e.message + statusElm.innerHTML = e.message } const main = (IPFS, ORBITDB) => { @@ -31,37 +31,39 @@ const main = (IPFS, ORBITDB) => { // If we're building with Webpack, use the injected IPFS module. // Otherwise use 'Ipfs' which is exposed by ipfs.min.js - if (IPFS) { Ipfs = IPFS } + if (IPFS) + Ipfs = IPFS // If we're building with Webpack, use the injected OrbitDB module. // Otherwise use 'OrbitDB' which is exposed by orbitdb.min.js - if (ORBITDB) { OrbitDB = ORBITDB } + if (ORBITDB) + OrbitDB = ORBITDB // Init UI openButton.disabled = true createButton.disabled = true - statusElm.innerHTML = 'Starting IPFS...' + statusElm.innerHTML = "Starting IPFS..." // Create IPFS instance const ipfs = new Ipfs({ repo: '/orbitdb/examples/browser/new/ipfs/0.33.1', start: true, - preload: { + preload: { enabled: false }, EXPERIMENTAL: { - pubsub: true + pubsub: true, }, config: { Addresses: { Swarm: [ // Use IPFS dev signal server // '/dns4/star-signal.cloud.ipfs.team/wss/p2p-webrtc-star', - '/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star' + '/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star', // Use local signal server // '/ip4/0.0.0.0/tcp/9090/wss/p2p-webrtc-star', ] - } + }, } }) @@ -69,7 +71,7 @@ const main = (IPFS, ORBITDB) => { ipfs.on('ready', async () => { openButton.disabled = false createButton.disabled = false - statusElm.innerHTML = 'IPFS Started' + statusElm.innerHTML = "IPFS Started" orbitdb = await OrbitDB.createInstance(ipfs) }) @@ -87,9 +89,9 @@ const main = (IPFS, ORBITDB) => { db.events.on('replicate.progress', () => queryAndRender(db)) // Hook up to the load progress event and render the progress - let maxTotal = 0; let loaded = 0 + let maxTotal = 0, loaded = 0 db.events.on('load.progress', (address, hash, entry, progress, total) => { - loaded++ + loaded ++ maxTotal = Math.max.apply(null, [maxTotal, progress, 0]) total = Math.max.apply(null, [progress, maxTotal, total, entry.clock.time, 0]) statusElm.innerHTML = `Loading database... ${maxTotal} / ${total}` @@ -123,9 +125,9 @@ const main = (IPFS, ORBITDB) => { } const resetDatabase = async (db) => { - writerText.innerHTML = '' - outputElm.innerHTML = '' - outputHeaderElm.innerHTML = '' + writerText.innerHTML = "" + outputElm.innerHTML = "" + outputHeaderElm.innerHTML = "" clearInterval(updateInterval) @@ -149,16 +151,16 @@ const main = (IPFS, ORBITDB) => { db = await orbitdb.open(name, { // If database doesn't exist, create it - create: true, + create: true, overwrite: true, - // Load only the local version of the database, + // Load only the local version of the database, // don't load the latest from the network yet localOnly: false, type: type, // If "Public" flag is set, allow anyone to write to the database, // otherwise only the creator of the database can write accessController: { - write: publicAccess ? ['*'] : [orbitdb.identity.publicKey] + write: publicAccess ? ['*'] : [orbitdb.identity.publicKey], } }) @@ -180,7 +182,7 @@ const main = (IPFS, ORBITDB) => { createButton.disabled = true try { - statusElm.innerHTML = 'Connecting to peers...' + statusElm.innerHTML = "Connecting to peers..." db = await orbitdb.open(address, { sync: true }) await load(db, 'Loading database...') @@ -197,17 +199,17 @@ const main = (IPFS, ORBITDB) => { } const update = async (db) => { - count++ + count ++ const time = new Date().toISOString() const idx = Math.floor(Math.random() * creatures.length) const creature = creatures[idx] if (db.type === 'eventlog') { - const value = 'GrEEtinGs from ' + orbitdb.id + ' ' + creature + ': Hello #' + count + ' (' + time + ')' + const value = "GrEEtinGs from " + orbitdb.id + " " + creature + ": Hello #" + count + " (" + time + ")" await db.add(value) } else if (db.type === 'feed') { - const value = 'GrEEtinGs from ' + orbitdb.id + ' ' + creature + ': Hello #' + count + ' (' + time + ')' + const value = "GrEEtinGs from " + orbitdb.id + " " + creature + ": Hello #" + count + " (" + time + ")" await db.add(value) } else if (db.type === 'docstore') { const value = { _id: 'peer1', avatar: creature, updated: time } @@ -217,12 +219,23 @@ const main = (IPFS, ORBITDB) => { } else if (db.type === 'counter') { await db.inc(1) } else { - throw new Error('Unknown datatbase type: ', db.type) + throw new Error("Unknown datatbase type: ", db.type) } } const query = (db) => { - if (db.type === 'eventlog') { return db.iterator({ limit: 5 }).collect() } else if (db.type === 'feed') { return db.iterator({ limit: 5 }).collect() } else if (db.type === 'docstore') { return db.get('peer1') } else if (db.type === 'keyvalue') { return db.get('mykey') } else if (db.type === 'counter') { return db.value } else { throw new Error('Unknown datatbase type: ', db.type) } + if (db.type === 'eventlog') + return db.iterator({ limit: 5 }).collect() + else if (db.type === 'feed') + return db.iterator({ limit: 5 }).collect() + else if (db.type === 'docstore') + return db.get('peer1') + else if (db.type === 'keyvalue') + return db.get('mykey') + else if (db.type === 'counter') + return db.value + else + throw new Error("Unknown datatbase type: ", db.type) } const queryAndRender = async (db) => { @@ -232,8 +245,8 @@ const main = (IPFS, ORBITDB) => { const result = query(db) if (dbType !== db.type || dbAddress !== db.address) { - dbType = db.type - dbAddress = db.address + dbType = db.type; + dbAddress = db.address; outputHeaderElm.innerHTML = `

${dbType.toUpperCase()}

@@ -250,11 +263,11 @@ const main = (IPFS, ORBITDB) => {
${result && Array.isArray(result) && result.length > 0 && db.type !== 'docstore' && db.type !== 'keyvalue' - ? result.slice().reverse().map((e) => e.payload.value).join('
\n') - : db.type === 'docstore' - ? JSON.stringify(result, null, 2) - : result ? result.toString().replace('"', '').replace('"', '') : result -} + ? result.slice().reverse().map((e) => e.payload.value).join('
\n') + : db.type === 'docstore' + ? JSON.stringify(result, null, 2) + : result ? result.toString().replace('"', '').replace('"', '') : result + }
` @@ -264,4 +277,5 @@ const main = (IPFS, ORBITDB) => { createButton.addEventListener('click', createDatabase) } -if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = main } +if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') + module.exports = main diff --git a/examples/eventlog.js b/examples/eventlog.js index cae777051..835909ce9 100644 --- a/examples/eventlog.js +++ b/examples/eventlog.js @@ -5,14 +5,14 @@ const OrbitDB = require('../src/OrbitDB') const creatures = ['🐙', '🐷', '🐬', '🐞', '🐈', '🙉', '🐸', '🐓'] -console.log('Starting...') +console.log("Starting...") -const ipfs = new IPFS({ +const ipfs = new IPFS({ repo: './orbitdb/examples/ipfs', start: true, EXPERIMENTAL: { - pubsub: true - } + pubsub: true, + }, }) ipfs.on('error', (err) => console.error(err)) diff --git a/examples/keyvalue.js b/examples/keyvalue.js index f8c3d5762..15e8c1e8e 100644 --- a/examples/keyvalue.js +++ b/examples/keyvalue.js @@ -7,7 +7,8 @@ const userId = 1 const creatures = ['🐙', '🐬', '🐋', '🐠', '🐡', '🦀', '🐢', '🐟', '🐳'] const output = (user) => { - if (!user) { return } + if (!user) + return let output = `` output += `----------------------\n` @@ -20,14 +21,14 @@ const output = (user) => { console.log(output) } -console.log('Starting...') +console.log("Starting...") -const ipfs = new IPFS({ +const ipfs = new IPFS({ repo: './orbitdb/examples/ipfs', start: true, EXPERIMENTAL: { - pubsub: true - } + pubsub: true, + }, }) ipfs.on('error', (err) => console.error(err)) @@ -62,6 +63,6 @@ ipfs.on('ready', async () => { output(user) } - console.log('Starting update loop...') + console.log("Starting update loop...") setInterval(query, 1000) }) diff --git a/package-lock.json b/package-lock.json index 735c2d4ce..1e6518d28 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11796,7 +11796,7 @@ } }, "orbit-db-identity-provider": { - "version": "github:orbitdb/orbit-db-identity-provider#e0e52f05c980389731584cb03a99433850e394b5", + "version": "github:orbitdb/orbit-db-identity-provider#92f033a65781954bff5bdf236dc89654a3137e1d", "from": "github:orbitdb/orbit-db-identity-provider#fix/persistent-store", "requires": { "ethers": "^4.0.20", diff --git a/src/OrbitDB.js b/src/OrbitDB.js index 28701189e..3b9595bcd 100644 --- a/src/OrbitDB.js +++ b/src/OrbitDB.js @@ -32,7 +32,7 @@ if (isNode) { } const Logger = require('logplease') -const logger = Logger.create('orbit-db') +const logger = Logger.create("orbit-db") Logger.setLogLevel('ERROR') // Mapping for 'database type' -> Class @@ -41,14 +41,16 @@ let databaseTypes = { 'eventlog': EventStore, 'feed': FeedStore, 'docstore': DocumentStore, - 'keyvalue': KeyValueStore + 'keyvalue': KeyValueStore, } class OrbitDB { - constructor (ipfs, identity, options = {}) { - if (!isDefined(ipfs)) { throw new Error('IPFS is a required argument. See https://github.com/orbitdb/orbit-db/blob/master/API.md#createinstance') } + constructor(ipfs, identity, options = {}) { + if (!isDefined(ipfs)) + throw new Error('IPFS is a required argument. See https://github.com/orbitdb/orbit-db/blob/master/API.md#createinstance') - if (!isDefined(identity)) { throw new Error('identity is a required argument. See https://github.com/orbitdb/orbit-db/blob/master/API.md#createinstance') } + if (!isDefined(identity)) + throw new Error('identity is a required argument. See https://github.com/orbitdb/orbit-db/blob/master/API.md#createinstance') this._ipfs = ipfs this.identity = identity @@ -68,24 +70,24 @@ class OrbitDB { } static async createInstance (ipfs, options = {}) { - if (!isDefined(ipfs)) { throw new Error('IPFS is a required argument. See https://github.com/orbitdb/orbit-db/blob/master/API.md#createinstance') } + if (!isDefined(ipfs)) + throw new Error('IPFS is a required argument. See https://github.com/orbitdb/orbit-db/blob/master/API.md#createinstance') const { id } = await ipfs.id() const directory = options.directory || './orbitdb' - const defaultStorage = { + const storageOptions = Object.assign({}, options.storage, { keystore: await storage.createStore(path.join(directory, id, '/keystore')), cache: await storage.createStore(path.join(directory, id, '/cache')) - } - const storageOptions = Object.assign({}, options.storage, defaultStorage) + }) const keystore = options.keystore || new Keystore(storageOptions.keystore) const identity = options.identity || await Identities.createIdentity({ id: options.id || id, - keystore: keystore + keystore: keystore, }) options = Object.assign({}, options, { - peerId: id, + peerId: id , directory: directory, keystore: keystore, storage: storageOptions @@ -133,11 +135,13 @@ class OrbitDB { } async disconnect () { - // close Keystore - if (this.storage.keystore.close) { await this.storage.keystore.close() } + //close Keystore + if (this.storage.keystore.close) + await this.storage.keystore.close() - // close Cache - if (this.storage.cache.close) { await this.storage.cache.close() } + //close Cache + if (this.storage.cache.close) + await this.storage.cache.close() // Close all open databases const databases = Object.values(this.stores) @@ -174,7 +178,8 @@ class OrbitDB { // Get the type -> class mapping const Store = databaseTypes[type] - if (!Store) { throw new Error(`Invalid database type '${type}'`) } + if (!Store) + throw new Error(`Invalid database type '${type}'`) let accessController if (options.accessControllerAddress) { @@ -187,7 +192,7 @@ class OrbitDB { accessController: accessController, keystore: this.keystore, cache: this.cache, - onClose: this._onClose.bind(this) + onClose: this._onClose.bind(this), }) const identity = options.identity || this.identity @@ -200,15 +205,16 @@ class OrbitDB { // Subscribe to pubsub to get updates from peers, // this is what hooks us into the message propagation layer // and the p2p network - if (opts.replicate && this._pubsub) { this._pubsub.subscribe(addr, this._onMessage.bind(this), this._onPeerConnected.bind(this)) } + if(opts.replicate && this._pubsub) + this._pubsub.subscribe(addr, this._onMessage.bind(this), this._onPeerConnected.bind(this)) return store } // Callback for local writes to the database. We the update to pubsub. _onWrite (address, entry, heads) { - if (!heads) throw new Error("'heads' not defined") - if (this._pubsub) this._pubsub.publish(address, heads) + if(!heads) throw new Error("'heads' not defined") + if(this._pubsub) this._pubsub.publish(address, heads) } // Callback for receiving a message from the network @@ -243,7 +249,8 @@ class OrbitDB { onChannelCreated ) - if (getStore(address)) { getStore(address).events.emit('peer', peer) } + if (getStore(address)) + getStore(address).events.emit('peer', peer) } // Callback when database was closed @@ -258,12 +265,15 @@ class OrbitDB { delete this.stores[address] } - async _determineAddress (name, type, options = {}, onlyHash) { - if (!OrbitDB.isValidType(type)) { throw new Error(`Invalid database type '${type}'`) } - if (OrbitDBAddress.isValid(name)) { throw new Error(`Given database name is an address. Please give only the name of the database!`) } + async _determineAddress(name, type, options = {}, onlyHash) { + if (!OrbitDB.isValidType(type)) + throw new Error(`Invalid database type '${type}'`) + + if (OrbitDBAddress.isValid(name)) + throw new Error(`Given database name is an address. Please give only the name of the database!`) // Create an AccessController, use IPFS AC as the default - options.accessController = Object.assign({}, { name: name, type: 'ipfs' }, options.accessController) + options.accessController = Object.assign({}, { name: name , type: 'ipfs' }, options.accessController) const accessControllerAddress = await AccessControllers.create(this, options.accessController.type, options.accessController || {}) // Save the manifest to IPFS @@ -298,7 +308,8 @@ class OrbitDB { // Check if we have the database locally const haveDB = await this._haveLocalData(this.cache, dbAddress) - if (haveDB && !options.overwrite) { throw new Error(`Database '${dbAddress}' already exists!`) } + if (haveDB && !options.overwrite) + throw new Error(`Database '${dbAddress}' already exists!`) // Save the database locally await this._addManifestToCache(directory, dbAddress) @@ -309,9 +320,8 @@ class OrbitDB { return this.open(dbAddress, options) } - async determineAddress (name, type, options = {}) { - const opts = Object.assign({}, { onlyHash: true }, options) - return this._determineAddress(name, type, opts) + async determineAddress(name, type, options = {}) { + return this._determineAddress(name, type, options, true) } /* @@ -371,7 +381,8 @@ class OrbitDB { logger.debug(`Manifest for '${dbAddress}':\n${JSON.stringify(manifest, null, 2)}`) // Make sure the type from the manifest matches the type that was given as an option - if (options.type && manifest.type !== options.type) { throw new Error(`Database '${dbAddress}' is type '${manifest.type}' but was opened as '${options.type}'`) } + if (options.type && manifest.type !== options.type) + throw new Error(`Database '${dbAddress}' is type '${manifest.type}' but was opened as '${options.type}'`) // Save the database locally await this._addManifestToCache(directory, dbAddress) @@ -383,13 +394,22 @@ class OrbitDB { // Save the database locally async _addManifestToCache (directory, dbAddress) { + // const cache = await this._loadCache(directory, dbAddress) await this.cache.set(path.join(dbAddress.toString(), '_manifest'), dbAddress.root) logger.debug(`Saved manifest to IPFS as '${dbAddress.root}'`) } - async _loadCache (directory, dbAddress) { - return this.cache - } + // async _loadCache (directory, dbAddress) { + // let cache + // try { + // cache = await this.cache.load(directory, dbAddress) + // } catch (e) { + // console.log(e) + // logger.error("Couldn't load Cache:", e) + // } + + // return cache + // } /** * Check if we have the database, or part of it, saved locally diff --git a/src/db-manifest.js b/src/db-manifest.js index 25605b8e2..1940f73c5 100644 --- a/src/db-manifest.js +++ b/src/db-manifest.js @@ -6,7 +6,7 @@ const createDBManifest = async (ipfs, name, type, accessControllerAddress, optio const manifest = { name: name, type: type, - accessController: path.join('/ipfs', accessControllerAddress) + accessController: path.join('/ipfs', accessControllerAddress), } return io.write(ipfs, options.format || 'dag-cbor', manifest, options) diff --git a/src/exchange-heads.js b/src/exchange-heads.js index f4bbfed87..6c74d319d 100644 --- a/src/exchange-heads.js +++ b/src/exchange-heads.js @@ -3,7 +3,7 @@ const Channel = require('ipfs-pubsub-1on1') const Logger = require('logplease') -const logger = Logger.create('exchange-heads', { color: Logger.Colors.Yellow }) +const logger = Logger.create("exchange-heads", { color: Logger.Colors.Yellow }) Logger.setLogLevel('ERROR') const getHeadsForDatabase = store => (store && store._oplog) ? store._oplog.heads : [] diff --git a/src/orbit-db-address.js b/src/orbit-db-address.js index 9de8874b1..bd78440e9 100644 --- a/src/orbit-db-address.js +++ b/src/orbit-db-address.js @@ -37,9 +37,11 @@ class OrbitDBAddress { } static parse (address) { - if (!address) { throw new Error(`Not a valid OrbitDB address: ${address}`) } + if (!address) + throw new Error(`Not a valid OrbitDB address: ${address}`) - if (!OrbitDBAddress.isValid(address)) { throw new Error(`Not a valid OrbitDB address: ${address}`) } + if (!OrbitDBAddress.isValid(address)) + throw new Error(`Not a valid OrbitDB address: ${address}`) const parts = address.toString() .split('/') diff --git a/src/utils/index.js b/src/utils/index.js index 9218f014a..eed74f1fd 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -2,10 +2,8 @@ const isDefined = require('./is-defined') const io = require('orbit-db-io') -const isNode = require('is-node') module.exports = { isDefined, - io, - isNode + io } diff --git a/test/counterdb.test.js b/test/counterdb.test.js index 23b001506..4d335eea5 100644 --- a/test/counterdb.test.js +++ b/test/counterdb.test.js @@ -12,7 +12,7 @@ const { stopIpfs, testAPIs, connectPeers, - waitForPeers + waitForPeers, } = require('./utils') const dbPath1 = './orbitdb/tests/counters/peer1' @@ -21,7 +21,7 @@ const ipfsPath1 = './orbitdb/tests/counters/peer1/ipfs' const ipfsPath2 = './orbitdb/tests/counters/peer2/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Counters (${API})`, function () { + describe(`orbit-db - Counters (${API})`, function() { this.timeout(config.timeout) let orbitdb1, orbitdb2 @@ -41,13 +41,17 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if (orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if (orbitdb2) + await orbitdb2.stop() - if (ipfsd1) { await stopIpfs(ipfsd1) } + if (ipfsd1) + await stopIpfs(ipfsd1) - if (ipfsd2) { await stopIpfs(ipfsd2) } + if (ipfsd2) + await stopIpfs(ipfsd2) }) beforeEach(async () => { @@ -56,12 +60,14 @@ Object.keys(testAPIs).forEach(API => { }) afterEach(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if (orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if (orbitdb2) + await orbitdb2.stop() }) - describe('counters', function () { + describe('counters', function() { let address it('creates and opens a database', async () => { diff --git a/test/create-open.test.js b/test/create-open.test.js index bf1dde597..3dc94c46f 100644 --- a/test/create-open.test.js +++ b/test/create-open.test.js @@ -17,14 +17,14 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath = './orbitdb/tests/create-open' const ipfsPath = './orbitdb/tests/create-open/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Create & Open (${API})`, function () { + describe(`orbit-db - Create & Open (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb, db, address @@ -40,13 +40,15 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb) { await orbitdb.stop() } + if(orbitdb) + await orbitdb.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('Create', function () { - describe('Errors', function () { + describe('Create', function() { + describe('Errors', function() { it('throws an error if given an invalid database type', async () => { let err try { @@ -78,6 +80,7 @@ Object.keys(testAPIs).forEach(API => { assert.equal(err, `Error: Database '${db.address}' already exists!`) }) + it('throws an error if database type doesn\'t match', async () => { let err, log, kv try { @@ -90,7 +93,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Success', function () { + describe('Success', function() { before(async () => { db = await orbitdb.create('second', 'feed', { replicate: false }) localDataPath = path.join(dbPath, orbitdb.id, 'cache') @@ -131,7 +134,7 @@ Object.keys(testAPIs).forEach(API => { it('saves database manifest file locally', async () => { const manifest = await io.read(ipfs, db.address.root) - assert.notEqual(manifest) + assert.notEqual(manifest, ) assert.equal(manifest.name, 'second') assert.equal(manifest.type, 'feed') assert.notEqual(manifest.accessController, null) @@ -146,7 +149,7 @@ Object.keys(testAPIs).forEach(API => { assert.equal(fs.existsSync(localDataPath), true) }) - describe('Access Controller', function () { + describe('Access Controller', function() { before(async () => { if (db) { await db.close() @@ -183,8 +186,8 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('determineAddress', function () { - describe('Errors', function () { + describe('determineAddress', function() { + describe('Errors', function() { it('throws an error if given an invalid database type', async () => { let err try { @@ -206,7 +209,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Success', function () { + describe('Success', function() { before(async () => { address = await orbitdb.determineAddress('third', 'feed', { replicate: false }) localDataPath = path.join(dbPath, address.root, address.path) @@ -225,7 +228,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Open', function () { + describe('Open', function() { beforeEach(async () => { db = await orbitdb.open('abc', { create: true, type: 'feed' }) }) diff --git a/test/create-type.test.js b/test/create-type.test.js index ebeed0cfe..4791b1ac2 100644 --- a/test/create-type.test.js +++ b/test/create-type.test.js @@ -10,7 +10,7 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath = './orbitdb/tests/create-open' @@ -28,7 +28,7 @@ class CustomStore extends DocumentStore { } Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Create Custom Database Type (${API})`, function () { + describe(`orbit-db - Create Custom Database Type (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb diff --git a/test/custom-cache.test.js b/test/custom-cache.test.js index 0feadde1b..4cde44e10 100644 --- a/test/custom-cache.test.js +++ b/test/custom-cache.test.js @@ -6,7 +6,7 @@ const path = require('path') const OrbitDB = require('../src/OrbitDB') const CustomCache = require('orbit-db-cache') const localdown = require('localstorage-down') -const storage = require('orbit-db-storage-adapter')(localdown) +const storage = require("orbit-db-storage-adapter")(localdown) // Include test utilities const { @@ -14,20 +14,20 @@ const { startIpfs, stopIpfs, testAPIs, - databases + databases, } = require('./utils') const dbPath = './orbitdb/tests/customKeystore' const ipfsPath = './orbitdb/tests/customKeystore/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Use a Custom Cache (${API})`, function () { + describe(`orbit-db - Use a Custom Cache (${API})`, function() { this.timeout(20000) let ipfsd, ipfs, orbitdb1 before(async () => { - const store = await storage.createStore('local') + const store = await storage.createStore("local") const cache = new CustomCache(store) config.daemon1.repo = ipfsPath @@ -42,12 +42,14 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('allows orbit to use a custom cache with different store types', function () { + describe('allows orbit to use a custom cache with different store types', function() { databases.forEach(async (database) => { it(database.type + ' allows custom keystore', async () => { const db1 = await database.create(orbitdb1, 'custom-keystore') diff --git a/test/custom-keystore.test.js b/test/custom-keystore.test.js index 3da18f8f7..c2b51616b 100644 --- a/test/custom-keystore.test.js +++ b/test/custom-keystore.test.js @@ -12,7 +12,7 @@ const { stopIpfs, testAPIs, CustomTestKeystore, - databases + databases, } = require('./utils') Identities.addIdentityProvider(CustomTestKeystore().identityProvider) @@ -21,8 +21,8 @@ const dbPath = './orbitdb/tests/customKeystore' const ipfsPath = './orbitdb/tests/customKeystore/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Use a Custom Keystore (${API})`, function () { - this.timeout(config.timeout) + describe(`orbit-db - Use a Custom Keystore (${API})`, function() { + this.timeout(20000) let ipfsd, ipfs, orbitdb1 @@ -40,12 +40,14 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('allows orbit to use a custom keystore with different store types', function () { + describe('allows orbit to use a custom keystore with different store types', function() { databases.forEach(async (database) => { it(database.type + ' allows custom keystore', async () => { const db1 = await database.create(orbitdb1, 'custom-keystore') @@ -58,7 +60,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('allows a custom keystore to be used with different store and write permissions', function () { + describe('allows a custom keystore to be used with different store and write permissions', function() { databases.forEach(async (database) => { it(database.type + ' allows custom keystore', async () => { const options = { diff --git a/test/docstore.test.js b/test/docstore.test.js index db4c5ee52..a1ad4144a 100644 --- a/test/docstore.test.js +++ b/test/docstore.test.js @@ -10,14 +10,14 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath = './orbitdb/tests/docstore' const ipfsPath = './orbitdb/tests/docstore/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Document Store (${API})`, function () { + describe(`orbit-db - Document Store (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb1, db @@ -31,9 +31,11 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) it('creates and opens a database', async () => { @@ -43,12 +45,12 @@ Object.keys(testAPIs).forEach(API => { assert.equal(db.dbname, 'first doc database') }) - describe('Default index \'_id\'', function () { + describe('Default index \'_id\'', function() { beforeEach(async () => { const options = { replicate: false, maxHistory: 0, - path: dbPath + path: dbPath, } db = await orbitdb1.docstore(config.dbname, options) }) @@ -58,16 +60,16 @@ Object.keys(testAPIs).forEach(API => { }) it('put', async () => { - const doc = { _id: 'hello world', doc: 'all the things' } + const doc = { _id: 'hello world', doc: 'all the things'} await db.put(doc) const value = db.get('hello world') assert.deepEqual(value, [doc]) }) it('get - partial term match', async () => { - const doc1 = { _id: 'hello world', doc: 'some things' } - const doc2 = { _id: 'hello universe', doc: 'all the things' } - const doc3 = { _id: 'sup world', doc: 'other things' } + const doc1 = { _id: 'hello world', doc: 'some things'} + const doc2 = { _id: 'hello universe', doc: 'all the things'} + const doc3 = { _id: 'sup world', doc: 'other things'} await db.put(doc1) await db.put(doc2) await db.put(doc3) @@ -76,9 +78,9 @@ Object.keys(testAPIs).forEach(API => { }) it('get after delete', async () => { - const doc1 = { _id: 'hello world', doc: 'some things' } - const doc2 = { _id: 'hello universe', doc: 'all the things' } - const doc3 = { _id: 'sup world', doc: 'other things' } + const doc1 = { _id: 'hello world', doc: 'some things'} + const doc2 = { _id: 'hello universe', doc: 'all the things'} + const doc3 = { _id: 'sup world', doc: 'other things'} await db.put(doc1) await db.put(doc2) await db.put(doc3) @@ -90,8 +92,8 @@ Object.keys(testAPIs).forEach(API => { }) it('put updates a value', async () => { - const doc1 = { _id: 'hello world', doc: 'all the things' } - const doc2 = { _id: 'hello world', doc: 'some of the things' } + const doc1 = { _id: 'hello world', doc: 'all the things'} + const doc2 = { _id: 'hello world', doc: 'some of the things'} await db.put(doc1) await db.put(doc2) const value = db.get('hello') @@ -99,10 +101,10 @@ Object.keys(testAPIs).forEach(API => { }) it('query', async () => { - const doc1 = { _id: 'hello world', doc: 'all the things', views: 17 } - const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10 } - const doc3 = { _id: 'hello other world', doc: 'none of the things', views: 5 } - const doc4 = { _id: 'hey universe', doc: '' } + const doc1 = { _id: 'hello world', doc: 'all the things', views: 17} + const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10} + const doc3 = { _id: 'hello other world', doc: 'none of the things', views: 5} + const doc4 = { _id: 'hey universe', doc: ''} await db.put(doc1) await db.put(doc2) @@ -119,10 +121,10 @@ Object.keys(testAPIs).forEach(API => { }) it('query after delete', async () => { - const doc1 = { _id: 'hello world', doc: 'all the things', views: 17 } - const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10 } - const doc3 = { _id: 'hello other world', doc: 'none of the things', views: 5 } - const doc4 = { _id: 'hey universe', doc: '' } + const doc1 = { _id: 'hello world', doc: 'all the things', views: 17} + const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10} + const doc3 = { _id: 'hello other world', doc: 'none of the things', views: 5} + const doc4 = { _id: 'hey universe', doc: ''} await db.put(doc1) await db.put(doc2) @@ -136,8 +138,8 @@ Object.keys(testAPIs).forEach(API => { }) it('query returns full op', async () => { - const doc1 = { _id: 'hello world', doc: 'all the things', views: 17 } - const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10 } + const doc1 = { _id: 'hello world', doc: 'all the things', views: 17} + const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10} const expectedOperation = { op: 'PUT', @@ -146,7 +148,7 @@ Object.keys(testAPIs).forEach(API => { _id: 'sup world', doc: 'some of the things', views: 10 - } + }, } await db.put(doc1) @@ -167,7 +169,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Specified index', function () { + describe('Specified index', function() { beforeEach(async () => { const options = { indexBy: 'doc', @@ -182,15 +184,15 @@ Object.keys(testAPIs).forEach(API => { }) it('put', async () => { - const doc = { _id: 'hello world', doc: 'all the things' } + const doc = { _id: 'hello world', doc: 'all the things'} await db.put(doc) const value = db.get('all') assert.deepEqual(value, [doc]) }) it('get - matches specified index', async () => { - const doc1 = { _id: 'hello world', doc: 'all the things' } - const doc2 = { _id: 'hello world', doc: 'some things' } + const doc1 = { _id: 'hello world', doc: 'all the things'} + const doc2 = { _id: 'hello world', doc: 'some things'} await db.put(doc1) await db.put(doc2) const value1 = db.get('all') diff --git a/test/drop.test.js b/test/drop.test.js index bbab0f170..ee713c3aa 100644 --- a/test/drop.test.js +++ b/test/drop.test.js @@ -11,14 +11,14 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath = './orbitdb/tests/drop' const ipfsPath = './orbitdb/tests/drop/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Drop Database (${API})`, function () { + describe(`orbit-db - Drop Database (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb, db, address @@ -34,14 +34,16 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb) { await orbitdb.stop() } + if(orbitdb) + await orbitdb.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) rmrf.sync(dbPath) }) - describe('Drop', function () { + describe('Drop', function() { before(async () => { db = await orbitdb.create('first', 'feed') localDataPath = path.join(dbPath) diff --git a/test/eventlog.test.js b/test/eventlog.test.js index f87b98404..f79e22206 100644 --- a/test/eventlog.test.js +++ b/test/eventlog.test.js @@ -11,7 +11,7 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const last = arr => arr[arr.length - 1] @@ -20,7 +20,7 @@ const dbPath = './orbitdb/tests/eventlog' const ipfsPath = './orbitdb/tests/eventlog/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Log Database (${API})`, function () { + describe(`orbit-db - Log Database (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb1, db @@ -35,9 +35,11 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) describe('Eventlog', function () { @@ -95,7 +97,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Iterator', function () { + describe('Iterator', function() { let hashes = [] const itemCount = 5 @@ -105,7 +107,7 @@ Object.keys(testAPIs).forEach(API => { hashes = await mapSeries([0, 1, 2, 3, 4], (i) => db.add('hello' + i)) }) - describe('Defaults', function () { + describe('Defaults', function() { it('returns an iterator', () => { const iter = db.iterator() const next = iter.next().value @@ -126,7 +128,8 @@ Object.keys(testAPIs).forEach(API => { const iter = db.iterator({ limit: -1 }) let messages = [] - for (let i of iter) { messages.push(i.key) } + for(let i of iter) + messages.push(i.key) assert.equal(messages.length, hashes.length) }) @@ -144,14 +147,14 @@ Object.keys(testAPIs).forEach(API => { const amount = 3 const iter = db.iterator({ limit: amount }) let i = hashes.length - amount - for (let item of iter) { + for(let item of iter) { assert.equal(item.payload.value, 'hello' + i) - i++ + i ++ } }) }) - describe('Collect', function () { + describe('Collect', function() { it('returns all items', () => { const messages = db.iterator({ limit: -1 }).collect() assert.equal(messages.length, hashes.length) @@ -170,7 +173,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Options: limit', function () { + describe('Options: limit', function() { it('returns 1 item when limit is 0', () => { const iter = db.iterator({ limit: 0 }) const first = iter.next().value @@ -228,8 +231,8 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Option: ranges', function () { - describe('gt & gte', function () { + describe('Option: ranges', function() { + describe('gt & gte', function() { it('returns 1 item when gte is the head', () => { const messages = db.iterator({ gte: last(hashes), limit: -1 }) .collect() @@ -276,7 +279,7 @@ Object.keys(testAPIs).forEach(API => { }) it('returns items when gt is defined', () => { - const messages = db.iterator({ limit: -1 }) + const messages = db.iterator({ limit: -1}) .collect() .map((e) => e.hash) @@ -292,7 +295,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('lt & lte', function () { + describe('lt & lte', function() { it('returns one item after head when lt is the head', () => { const messages = db.iterator({ lt: last(hashes) }) .collect() diff --git a/test/feed.test.js b/test/feed.test.js index c2698b3fd..e6ebd2885 100644 --- a/test/feed.test.js +++ b/test/feed.test.js @@ -11,7 +11,7 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const last = arr => arr[arr.length - 1] @@ -20,7 +20,7 @@ const dbPath = './orbitdb/tests/feed' const ipfsPath = './orbitdb/tests/feed/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Feed Database (${API})`, function () { + describe(`orbit-db - Feed Database (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb1, db, address @@ -35,12 +35,14 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('Feed', function () { + describe('Feed', function() { it('creates and opens a database', async () => { db = await orbitdb1.feed('feed database') assert.notEqual(db, null) @@ -135,7 +137,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Iterator', function () { + describe('Iterator', function() { let hashes = [] const itemCount = 5 @@ -145,7 +147,7 @@ Object.keys(testAPIs).forEach(API => { hashes = await mapSeries([0, 1, 2, 3, 4], (i) => db.add('hello' + i)) }) - describe('Defaults', function () { + describe('Defaults', function() { it('returns an iterator', () => { const iter = db.iterator() const next = iter.next().value @@ -166,7 +168,8 @@ Object.keys(testAPIs).forEach(API => { const iter = db.iterator({ limit: -1 }) let messages = [] - for (let i of iter) { messages.push(i.key) } + for(let i of iter) + messages.push(i.key) assert.equal(messages.length, hashes.length) }) @@ -184,14 +187,14 @@ Object.keys(testAPIs).forEach(API => { const amount = 3 const iter = db.iterator({ limit: amount }) let i = hashes.length - amount - for (let item of iter) { + for(let item of iter) { assert.equal(item.payload.value, 'hello' + i) - i++ + i ++ } }) }) - describe('Collect', function () { + describe('Collect', function() { it('returns all items', () => { const messages = db.iterator({ limit: -1 }).collect() assert.equal(messages.length, hashes.length) @@ -210,7 +213,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Options: limit', function () { + describe('Options: limit', function() { it('returns 1 item when limit is 0', () => { const iter = db.iterator({ limit: 0 }) const first = iter.next().value @@ -268,8 +271,8 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('Option: ranges', function () { - describe('gt & gte', function () { + describe('Option: ranges', function() { + describe('gt & gte', function() { it('returns 1 item when gte is the head', () => { const messages = db.iterator({ gte: last(hashes), limit: -1 }) .collect() @@ -316,7 +319,7 @@ Object.keys(testAPIs).forEach(API => { }) it('returns items when gt is defined', () => { - const messages = db.iterator({ limit: -1 }) + const messages = db.iterator({ limit: -1}) .collect() .map((e) => e.hash) @@ -332,7 +335,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('lt & lte', function () { + describe('lt & lte', function() { it('returns one item after head when lt is the head', () => { const messages = db.iterator({ lt: last(hashes) }) .collect() diff --git a/test/kvstore.test.js b/test/kvstore.test.js index 8e1d3cdeb..f7cdcb4cf 100644 --- a/test/kvstore.test.js +++ b/test/kvstore.test.js @@ -10,14 +10,14 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath = './orbitdb/tests/kvstore' const ipfsPath = './orbitdb/tests/kvstore/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Key-Value Database (${API})`, function () { + describe(`orbit-db - Key-Value Database (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb1, db @@ -32,9 +32,11 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) beforeEach(async () => { diff --git a/test/multiple-databases.test.js b/test/multiple-databases.test.js index 8d67bdd8f..15ecf122b 100644 --- a/test/multiple-databases.test.js +++ b/test/multiple-databases.test.js @@ -12,7 +12,7 @@ const { stopIpfs, connectPeers, waitForPeers, - testAPIs + testAPIs, } = require('./utils') const dbPath1 = './orbitdb/tests/multiple-databases/1' @@ -25,25 +25,25 @@ const databaseInterfaces = [ name: 'logdb', open: async (orbitdb, address, options) => await orbitdb.log(address, options), write: async (db, index) => await db.add('hello' + index), - query: (db) => db.iterator({ limit: -1 }).collect().length + query: (db) => db.iterator({ limit: -1 }).collect().length, }, { name: 'feed', open: async (orbitdb, address, options) => await orbitdb.feed(address, options), write: async (db, index) => await db.add('hello' + index), - query: (db) => db.iterator({ limit: -1 }).collect().length + query: (db) => db.iterator({ limit: -1 }).collect().length, }, { name: 'key-value', open: async (orbitdb, address, options) => await orbitdb.keyvalue(address, options), write: async (db, index) => await db.put('hello', index), - query: (db) => db.get('hello') + query: (db) => db.get('hello'), }, { name: 'counterdb', open: async (orbitdb, address, options) => await orbitdb.counter(address, options), write: async (db, index) => await db.inc(1), - query: (db) => db.value + query: (db) => db.value, }, { name: 'documents', @@ -52,12 +52,12 @@ const databaseInterfaces = [ query: (db) => { const docs = db.get('hello') return docs ? docs[0].testing : 0 - } - } + }, + }, ] Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Multiple Databases (${API})`, function () { + describe(`orbit-db - Multiple Databases (${API})`, function() { this.timeout(config.timeout) let ipfsd1, ipfsd2, ipfs1, ipfs2 @@ -85,13 +85,17 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if(orbitdb2) + await orbitdb2.stop() - if (ipfsd1) { await stopIpfs(ipfsd1) } + if (ipfsd1) + await stopIpfs(ipfsd1) - if (ipfsd2) { await stopIpfs(ipfsd2) } + if (ipfsd2) + await stopIpfs(ipfsd2) }) beforeEach(async () => { @@ -102,7 +106,7 @@ Object.keys(testAPIs).forEach(API => { orbitdb2.identity.publicKey ], - console.log('Creating databases and waiting for peers to connect') + console.log("Creating databases and waiting for peers to connect") // Open the databases on the first node options = Object.assign({}, options, { create: true }) @@ -126,13 +130,15 @@ Object.keys(testAPIs).forEach(API => { await waitForPeers(ipfs1, [orbitdb2.id], localDatabases[0].address.toString()) await waitForPeers(ipfs1, [orbitdb2.id], localDatabases[0].address.toString()) - console.log('Peers connected') + console.log("Peers connected") }) afterEach(async () => { - for (let db of remoteDatabases) { await db.drop() } + for (let db of remoteDatabases) + await db.drop() - for (let db of localDatabases) { await db.drop() } + for (let db of localDatabases) + await db.drop() }) it('replicates multiple open databases', async () => { @@ -140,7 +146,8 @@ Object.keys(testAPIs).forEach(API => { const entryArr = [] // Create an array that we use to create the db entries - for (let i = 1; i < entryCount + 1; i++) { entryArr.push(i) } + for (let i = 1; i < entryCount + 1; i ++) + entryArr.push(i) // Result state, // we count how many times 'replicated' event was fired per db @@ -157,7 +164,7 @@ Object.keys(testAPIs).forEach(API => { }) // Write entries to each database - console.log('Writing to databases') + console.log("Writing to databases") for (let index = 0; index < databaseInterfaces.length; index++) { const dbInterface = databaseInterfaces[index] const db = localDatabases[index] @@ -170,7 +177,7 @@ Object.keys(testAPIs).forEach(API => { return remoteDatabases.every(db => db._oplog.length === entryCount) } - console.log('Waiting for replication to finish') + console.log("Waiting for replication to finish") return new Promise((resolve, reject) => { const interval = setInterval(() => { diff --git a/test/orbit-db-address.test.js b/test/orbit-db-address.test.js index b342ab21b..1e73d271d 100644 --- a/test/orbit-db-address.test.js +++ b/test/orbit-db-address.test.js @@ -16,7 +16,7 @@ const { } = require('./utils') Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - OrbitDB Address (${API})`, function () { + describe(`orbit-db - OrbitDB Address (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb @@ -31,9 +31,11 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb) { await orbitdb.stop() } + if(orbitdb) + await orbitdb.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) describe('Parse Address', () => { @@ -96,5 +98,6 @@ Object.keys(testAPIs).forEach(API => { assert.equal(result, false) }) }) + }) }) diff --git a/test/persistency.js b/test/persistency.js index d87f033f8..20cf801e6 100644 --- a/test/persistency.js +++ b/test/persistency.js @@ -34,7 +34,7 @@ const tests = [ Object.keys(testAPIs).forEach(API => { tests.forEach(test => { - describe(`orbit-db - ${test.title} (${API})`, function () { + describe(`orbit-db - ${test.title} (${API})`, function() { this.timeout(config.timeout) const entryCount = 65 @@ -42,7 +42,7 @@ Object.keys(testAPIs).forEach(API => { let ipfsd, ipfs, orbitdb1, db, address before(async () => { - if (test.orbitDBConfig === 'custom') { + if(test.orbitDBConfig === "custom") { const customStorage = await Storage.create(localdown) test.orbitDBConfig = new Cache(customStorage) } @@ -56,17 +56,20 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('load', function () { + describe('load', function() { beforeEach(async () => { const dbName = new Date().getTime().toString() const entryArr = [] - for (let i = 0; i < entryCount; i++) { entryArr.push(i) } + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) db = await orbitdb1.eventlog(dbName) address = db.address.toString() @@ -90,7 +93,6 @@ Object.keys(testAPIs).forEach(API => { it('loads database partially', async () => { const amount = 33 - debugger db = await orbitdb1.eventlog(address) await db.load(amount) const items = db.iterator({ limit: -1 }).collect() @@ -102,7 +104,7 @@ Object.keys(testAPIs).forEach(API => { it('load and close several times', async () => { const amount = 8 - for (let i = 0; i < amount; i++) { + for (let i = 0; i < amount; i ++) { db = await orbitdb1.eventlog(address) await db.load() const items = db.iterator({ limit: -1 }).collect() @@ -123,7 +125,7 @@ Object.keys(testAPIs).forEach(API => { it('load, add one, close - several times', async () => { const amount = 8 - for (let i = 0; i < amount; i++) { + for (let i = 0; i < amount; i ++) { db = await orbitdb1.eventlog(address) await db.load() await db.add('hello' + (entryCount + i)) @@ -153,7 +155,7 @@ Object.keys(testAPIs).forEach(API => { return new Promise(async (resolve, reject) => { let count = 0 db.events.on('load.progress', (address, hash, entry) => { - count++ + count ++ try { assert.equal(address, db.address.toString()) @@ -179,7 +181,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('load from empty snapshot', function () { + describe('load from empty snapshot', function() { it('loads database from an empty snapshot', async () => { db = await orbitdb1.eventlog('empty-snapshot') address = db.address.toString() @@ -193,12 +195,13 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('load from snapshot', function () { + describe('load from snapshot', function() { beforeEach(async () => { const dbName = new Date().getTime().toString() const entryArr = [] - for (let i = 0; i < entryCount; i++) { entryArr.push(i) } + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) db = await orbitdb1.eventlog(dbName) address = db.address.toString() @@ -223,7 +226,7 @@ Object.keys(testAPIs).forEach(API => { it('load, add one and save snapshot several times', async () => { const amount = 4 - for (let i = 0; i < amount; i++) { + for (let i = 0; i < amount; i ++) { db = await orbitdb1.eventlog(address) await db.loadFromSnapshot() await db.add('hello' + (entryCount + i)) @@ -270,7 +273,7 @@ Object.keys(testAPIs).forEach(API => { return new Promise(async (resolve, reject) => { let count = 0 db.events.on('load.progress', (address, hash, entry) => { - count++ + count ++ try { assert.equal(address, db.address.toString()) diff --git a/test/replicate-and-load.test.js b/test/replicate-and-load.test.js index edda814fe..6805b48cd 100644 --- a/test/replicate-and-load.test.js +++ b/test/replicate-and-load.test.js @@ -12,7 +12,7 @@ const { stopIpfs, testAPIs, connectPeers, - waitForPeers + waitForPeers, } = require('./utils') const dbPath1 = './orbitdb/tests/replicate-and-load/1' @@ -21,7 +21,7 @@ const ipfsPath1 = './orbitdb/tests/replicate-and-load/1/ipfs' const ipfsPath2 = './orbitdb/tests/replicate-and-load/2/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Replicate and Load (${API})`, function () { + describe(`orbit-db - Replicate and Load (${API})`, function() { this.timeout(config.timeout) let ipfsd1, ipfsd2, ipfs1, ipfs2 @@ -45,16 +45,20 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if(orbitdb2) + await orbitdb2.stop() - if (ipfsd1) { await stopIpfs(ipfsd1) } + if (ipfsd1) + await stopIpfs(ipfsd1) - if (ipfsd2) { await stopIpfs(ipfsd2) } + if (ipfsd2) + await stopIpfs(ipfsd2) }) - describe('two peers', function () { + describe('two peers', function() { // Opens two databases db1 and db2 and gives write-access to both of the peers const openDatabases1 = async (options) => { // Set write access for both clients @@ -89,10 +93,10 @@ Object.keys(testAPIs).forEach(API => { assert.equal(db1.address.toString(), db2.address.toString()) - console.log('Waiting for peers...') + console.log("Waiting for peers...") await waitForPeers(ipfs1, [orbitdb2.id], db1.address.toString()) await waitForPeers(ipfs2, [orbitdb1.id], db1.address.toString()) - console.log('Found peers') + console.log("Found peers") }) afterEach(async () => { @@ -105,7 +109,8 @@ Object.keys(testAPIs).forEach(API => { const entryArr = [] let timer - for (let i = 0; i < entryCount; i++) { entryArr.push(i) } + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) await mapSeries(entryArr, (i) => db1.add('hello' + i)) @@ -121,6 +126,7 @@ Object.keys(testAPIs).forEach(API => { db2 = null try { + // Set write access for both clients let options = { accessController: { diff --git a/test/replicate-automatically.test.js b/test/replicate-automatically.test.js index dcf45fdd7..6c0f9d476 100644 --- a/test/replicate-automatically.test.js +++ b/test/replicate-automatically.test.js @@ -12,7 +12,7 @@ const { stopIpfs, testAPIs, connectPeers, - waitForPeers + waitForPeers, } = require('./utils') const dbPath1 = './orbitdb/tests/replicate-automatically/1' @@ -21,7 +21,7 @@ const ipfsPath1 = './orbitdb/tests/replicate-automatically/1/ipfs' const ipfsPath2 = './orbitdb/tests/replicate-automatically/2/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Automatic Replication (${API})`, function () { + describe(`orbit-db - Automatic Replication (${API})`, function() { this.timeout(config.timeout) let ipfsd1, ipfsd2, ipfs1, ipfs2 @@ -45,13 +45,17 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if(orbitdb2) + await orbitdb2.stop() - if (ipfsd1) { await stopIpfs(ipfsd1) } + if (ipfsd1) + await stopIpfs(ipfsd1) - if (ipfs2) { await stopIpfs(ipfsd2) } + if (ipfs2) + await stopIpfs(ipfsd2) }) beforeEach(async () => { @@ -81,7 +85,8 @@ Object.keys(testAPIs).forEach(API => { let timer // Create the entries in the first database - for (let i = 0; i < entryCount; i++) { entryArr.push(i) } + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) await mapSeries(entryArr, (i) => db1.add('hello' + i)) @@ -115,7 +120,8 @@ Object.keys(testAPIs).forEach(API => { let timer // Create the entries in the first database - for (let i = 0; i < entryCount; i++) { entryArr.push(i) } + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) await mapSeries(entryArr, (i) => db1.add('hello' + i)) diff --git a/test/replicate.test.js b/test/replicate.test.js index cef98844d..8d3a0f259 100644 --- a/test/replicate.test.js +++ b/test/replicate.test.js @@ -1,4 +1,4 @@ -'use strict' + 'use strict' const assert = require('assert') const mapSeries = require('p-each-series') @@ -13,7 +13,7 @@ const { testAPIs, connectPeers, waitForPeers, - MemStore + MemStore, } = require('./utils') const dbPath1 = './orbitdb/tests/replication/1' @@ -22,7 +22,7 @@ const ipfsPath1 = './orbitdb/tests/replication/1/ipfs' const ipfsPath2 = './orbitdb/tests/replication/2/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Replication (${API})`, function () { + describe(`orbit-db - Replication (${API})`, function() { this.timeout(config.timeout) let ipfsd1, ipfsd2, ipfs1, ipfs2 @@ -54,9 +54,11 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (ipfsd1) { await stopIpfs(ipfsd1) } + if (ipfsd1) + await stopIpfs(ipfsd1) - if (ipfsd2) { await stopIpfs(ipfsd2) } + if (ipfsd2) + await stopIpfs(ipfsd2) }) beforeEach(async () => { @@ -81,13 +83,17 @@ Object.keys(testAPIs).forEach(API => { afterEach(async () => { clearInterval(timer) options = {} - if (db1) { await db1.drop() } + if (db1) + await db1.drop() - if (db2) { await db2.drop() } + if (db2) + await db2.drop() - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if(orbitdb2) + await orbitdb2.stop() }) it('replicates database of 1 entry', async () => { @@ -116,7 +122,8 @@ Object.keys(testAPIs).forEach(API => { const entryCount = 100 const entryArr = [] - for (let i = 0; i < entryCount; i++) { entryArr.push(i) } + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) return new Promise(async (resolve, reject) => { try { @@ -150,36 +157,36 @@ Object.keys(testAPIs).forEach(API => { let expectedEventCount = 99 db2.events.on('replicate', (address, entry) => { - eventCount['replicate']++ + eventCount['replicate'] ++ events.push({ event: 'replicate', count: eventCount['replicate'], - entry: entry + entry: entry, }) }) db2.events.on('replicate.progress', (address, hash, entry, progress, total) => { - eventCount['replicate.progress']++ + eventCount['replicate.progress'] ++ events.push({ event: 'replicate.progress', count: eventCount['replicate.progress'], - entry: entry, + entry: entry , replicationInfo: { max: db2.replicationStatus.max, - progress: db2.replicationStatus.progress - } + progress: db2.replicationStatus.progress, + }, }) }) db2.events.on('replicated', (address) => { - eventCount['replicated']++ + eventCount['replicated'] ++ events.push({ event: 'replicated', count: eventCount['replicate'], replicationInfo: { max: db2.replicationStatus.max, - progress: db2.replicationStatus.progress - } + progress: db2.replicationStatus.progress, + }, }) // Resolve with a little timeout to make sure we // don't receive more than one event @@ -222,7 +229,7 @@ Object.keys(testAPIs).forEach(API => { // Trigger replication let adds = [] - for (let i = 0; i < expectedEventCount; i++) { + for (let i = 0; i < expectedEventCount; i ++) { adds.push(i) } @@ -239,12 +246,12 @@ Object.keys(testAPIs).forEach(API => { // Trigger replication let adds = [] - for (let i = 0; i < expectedEventCount; i++) { + for (let i = 0; i < expectedEventCount; i ++) { adds.push(i) } const add = async (i) => { - process.stdout.write('\rWriting ' + (i + 1) + ' / ' + expectedEventCount + ' ') + process.stdout.write("\rWriting " + (i + 1) + " / " + expectedEventCount + " ") await db1.add('hello ' + i) } @@ -254,33 +261,33 @@ Object.keys(testAPIs).forEach(API => { options = { directory: dbPath2 + '1', overwrite: true, - sync: true + sync: true, } db2 = await orbitdb2.eventlog(db1.address.toString(), options) db2.events.on('replicate', (address, entry) => { - eventCount['replicate']++ + eventCount['replicate'] ++ // console.log("[replicate] ", '#' + eventCount['replicate'] + ':', db2.replicationStatus.progress, '/', db2.replicationStatus.max, '| Tasks (in/queued/running/out):', db2._loader.tasksRequested, '/', db2._loader.tasksQueued, '/', db2._loader.tasksRunning, '/', db2._loader.tasksFinished) events.push({ event: 'replicate', count: eventCount['replicate'], - entry: entry + entry: entry, }) }) db2.events.on('replicate.progress', (address, hash, entry) => { - eventCount['replicate.progress']++ + eventCount['replicate.progress'] ++ // console.log("[progress] ", '#' + eventCount['replicate.progress'] + ':', db2.replicationStatus.progress, '/', db2.replicationStatus.max, '| Tasks (in/queued/running/out):', db2._loader.tasksRequested, '/', db2._loader.tasksQueued, '/', db2._loader.tasksRunning, '/', db2._loader.tasksFinished) // assert.equal(db2.replicationStatus.progress, eventCount['replicate.progress']) events.push({ event: 'replicate.progress', count: eventCount['replicate.progress'], - entry: entry, + entry: entry , replicationInfo: { max: db2.replicationStatus.max, - progress: db2.replicationStatus.progress - } + progress: db2.replicationStatus.progress, + }, }) }) @@ -301,12 +308,12 @@ Object.keys(testAPIs).forEach(API => { count: eventCount['replicate'], replicationInfo: { max: db2.replicationStatus.max, - progress: db2.replicationStatus.progress - } + progress: db2.replicationStatus.progress, + }, }) // Resolve with a little timeout to make sure we // don't receive more than one event - setTimeout(async () => { + setTimeout( async () => { if (eventCount['replicated'] === expectedEventCount) { finished = true } @@ -319,7 +326,7 @@ Object.keys(testAPIs).forEach(API => { clearInterval(timer) const et = new Date().getTime() - console.log('Duration:', et - st, 'ms') + console.log("Duration:", et - st, "ms") try { assert.equal(eventCount['replicate'], expectedEventCount) @@ -359,7 +366,7 @@ Object.keys(testAPIs).forEach(API => { // Trigger replication let adds = [] - for (let i = 0; i < expectedEventCount; i++) { + for (let i = 0; i < expectedEventCount; i ++) { adds.push(i) } @@ -372,7 +379,7 @@ Object.keys(testAPIs).forEach(API => { let options = { directory: dbPath2, overwrite: true, - sync: true + sync: true, } db2 = await orbitdb2.eventlog(db1.address.toString(), options) @@ -380,34 +387,34 @@ Object.keys(testAPIs).forEach(API => { await waitForPeers(ipfs2, [orbitdb1.id], db1.address.toString()) db2.events.on('replicate', (address, entry) => { - eventCount['replicate']++ + eventCount['replicate'] ++ // console.log("[replicate] ", '#' + eventCount['replicate'] + ':', current, '/', total, '| Tasks (in/queued/running/out):', db2._loader.tasksRequested, '/', db2._loader.tasksQueued, '/', db2._loader.tasksRunning, '/', db2._loader.tasksFinished) events.push({ event: 'replicate', count: eventCount['replicate'], - entry: entry + entry: entry, }) }) let prevProgress = 0 db2.events.on('replicate.progress', (address, hash, entry) => { - eventCount['replicate.progress']++ + eventCount['replicate.progress'] ++ // console.log("[progress] ", '#' + eventCount['replicate.progress'] + ':', current, '/', total, '| Tasks (in/queued/running/out):', db2._loader.tasksRequested, '/', db2._loader.tasksQueued, '/', db2._loader.tasksRunning, '/', db2._loader.tasksFinished) // assert.equal(current, total) events.push({ event: 'replicate.progress', count: eventCount['replicate.progress'], - entry: entry, + entry: entry , replicationInfo: { max: db2.replicationStatus.max, - progress: db2.replicationStatus.progress - } + progress: db2.replicationStatus.progress, + }, }) }) db2.events.on('replicated', (address, length) => { eventCount['replicated'] += length - const values = db2.iterator({ limit: -1 }).collect() + const values = db2.iterator({limit: -1}).collect() // console.log("[replicated]", '#' + eventCount['replicated'] + ':', current, '/', total, '| Tasks (in/queued/running/out):', db2._loader.tasksRequested, '/', db2._loader.tasksQueued, '/', db2._loader.tasksRunning, '/', db2._loader.tasksFinished, "|", db2._loader._stats.a, db2._loader._stats.b, db2._loader._stats.c, db2._loader._stats.d) try { assert.equal(db2.replicationStatus.progress <= db2.replicationStatus.max, true) @@ -420,12 +427,13 @@ Object.keys(testAPIs).forEach(API => { count: eventCount['replicate'], replicationInfo: { max: db2.replicationStatus.max, - progress: db2.replicationStatus.progress - } + progress: db2.replicationStatus.progress, + }, }) - if (db2.replicationStatus.max >= expectedEventCount * 2 && - db2.replicationStatus.progress >= expectedEventCount * 2) { finished = true } + if (db2.replicationStatus.max >= expectedEventCount * 2 + && db2.replicationStatus.progress >= expectedEventCount * 2) + finished = true }) const st = new Date().getTime() @@ -457,8 +465,8 @@ Object.keys(testAPIs).forEach(API => { assert.equal(replicatedEvents[replicatedEvents.length - 1].replicationInfo.progress, expectedEventCount * 2) assert.equal(replicatedEvents[replicatedEvents.length - 1].replicationInfo.max, expectedEventCount * 2) - const values1 = db1.iterator({ limit: -1 }).collect() - const values2 = db2.iterator({ limit: -1 }).collect() + const values1 = db1.iterator({limit: -1}).collect() + const values2 = db2.iterator({limit: -1}).collect() assert.deepEqual(values1, values2) // Test the replicator state diff --git a/test/replication-status.test.js b/test/replication-status.test.js index 15fae8d52..611e2980e 100644 --- a/test/replication-status.test.js +++ b/test/replication-status.test.js @@ -15,7 +15,7 @@ const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath1 = './orbitdb/tests/create-open/1' @@ -23,7 +23,7 @@ const dbPath2 = './orbitdb/tests/create-open/2' const ipfsPath = './orbitdb/tests/create-open/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Replication Status (${API})`, function () { + describe(`orbit-db - Replication Status (${API})`, function() { this.timeout(config.timeout) let ipfsd, ipfs, orbitdb1, orbitdb2, db, address @@ -42,11 +42,14 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if(orbitdb2) + await orbitdb2.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) it('has correct initial state', async () => { diff --git a/test/utils/config.js b/test/utils/config.js index 0d4c61fea..f3fabc9f8 100644 --- a/test/utils/config.js +++ b/test/utils/config.js @@ -21,7 +21,7 @@ module.exports = { webRTCStar: { Enabled: false } - } + }, } }, daemon1: { @@ -43,8 +43,8 @@ module.exports = { webRTCStar: { Enabled: false } - } - } + }, + }, }, daemon2: { EXPERIMENTAL: { @@ -65,7 +65,7 @@ module.exports = { webRTCStar: { Enabled: false } - } - } + }, + }, } } diff --git a/test/utils/custom-test-keystore.js b/test/utils/custom-test-keystore.js index 8a98895bf..8038658a3 100644 --- a/test/utils/custom-test-keystore.js +++ b/test/utils/custom-test-keystore.js @@ -12,18 +12,18 @@ class CustomTestKeystore { } hasKey () { - return this.key !== undefined + return this.key !== undefined ? true : false } createKey (id) { const key = ec.genKeyPair() const keyPair = { - public: { + public: { marshal: () => key.getPublic('hex') }, priv: key.getPrivate('hex'), privEnc: 'hex', - pubEnc: 'hex' + pubEnc: 'hex', } return keyPair @@ -40,7 +40,7 @@ class CustomTestKeystore { verify (signature, publicKey, data) { return Promise.resolve(true) } - + getPublic (key) { return key.public.marshal() } diff --git a/test/utils/databases.js b/test/utils/databases.js index 49f046244..04f97c1d7 100644 --- a/test/utils/databases.js +++ b/test/utils/databases.js @@ -5,7 +5,7 @@ const databases = [ tryInsert: (db) => db.add('hello'), query: (db) => db.iterator({ limit: -1 }).collect(), getTestValue: (db) => db.iterator({ limit: -1 }).collect()[0].payload.value, - expectedValue: 'hello' + expectedValue: 'hello', }, { type: 'feed', @@ -13,7 +13,7 @@ const databases = [ tryInsert: (db) => db.add('hello'), query: (db) => db.iterator({ limit: -1 }).collect(), getTestValue: (db) => db.iterator({ limit: -1 }).collect()[0].payload.value, - expectedValue: 'hello' + expectedValue: 'hello', }, { type: 'key-value', @@ -21,15 +21,15 @@ const databases = [ tryInsert: (db) => db.set('one', 'hello'), query: (db) => [], getTestValue: (db) => db.get('one'), - expectedValue: 'hello' + expectedValue: 'hello', }, { type: 'documents', create: (orbitdb, name, options) => orbitdb.docstore(name, options), - tryInsert: (db) => db.put({ _id: 'hello world', doc: 'all the things' }), + tryInsert: (db) => db.put({ _id: 'hello world', doc: 'all the things'}), query: (db) => [], getTestValue: (db) => db.get('hello world'), - expectedValue: [{ _id: 'hello world', doc: 'all the things' }] + expectedValue: [{ _id: 'hello world', doc: 'all the things'}], }, { type: 'counter', @@ -37,8 +37,8 @@ const databases = [ tryInsert: (db) => db.inc(8), query: (db) => [], getTestValue: (db) => db.value, - expectedValue: 8 - } + expectedValue: 8, + }, ] module.exports = databases diff --git a/test/utils/test-apis.js b/test/utils/test-apis.js index f7e583746..0eafd8dc3 100644 --- a/test/utils/test-apis.js +++ b/test/utils/test-apis.js @@ -8,14 +8,14 @@ const IPFS = require('ipfs') // https://github.com/ipfs/js-ipfsd-ctl#ipfsfactory---const-f--ipfsfactorycreateoptions let jsIpfs = { 'js-ipfs': { - type: 'proc', - exec: IPFS + type: 'proc', + exec: IPFS, } } const goIpfs = { 'go-ipfs': { - type: 'go' + type: 'go', } } @@ -25,6 +25,9 @@ let testAPIs = Object.assign({}, jsIpfs) // Setting env variable 'TEST=all' will make tests run with js-ipfs and go-ipfs. // Setting env variable 'TEST=go' will make tests run with go-ipfs. // Eg. 'TEST=go mocha' runs tests with go-ipfs -if (process.env.TEST === 'all') { testAPIs = Object.assign({}, testAPIs, goIpfs) } else if (process.env.TEST === 'go') { testAPIs = Object.assign({}, goIpfs) } +if (process.env.TEST === 'all') + testAPIs = Object.assign({}, testAPIs, goIpfs) +else if (process.env.TEST === 'go') + testAPIs = Object.assign({}, goIpfs) module.exports = testAPIs diff --git a/test/v0-open-load.js b/test/v0-open-load.js index c2bce056d..8be7dba98 100644 --- a/test/v0-open-load.js +++ b/test/v0-open-load.js @@ -15,13 +15,16 @@ const Identities = require('orbit-db-identity-provider') const migrate = require('localstorage-level-migration') const Keystore = require('orbit-db-keystore') const storage = require('orbit-db-storage-adapter')(leveldown) +storage.preCreate = async (directory, options) => { + fs.mkdirSync(directory, { recursive: true }) +} // Include test utilities const { config, startIpfs, stopIpfs, - testAPIs + testAPIs, } = require('./utils') const dbPath = './orbitdb/tests/v0' @@ -44,7 +47,6 @@ Object.keys(testAPIs).forEach(API => { const store = await storage.createStore(dbPath + "/keys") const keystore = new Keystore(store) - // copy data files to ipfs and orbitdb repos await fs.copy(path.join(ipfsFixturesDir, 'blocks'), path.join(ipfsd.path, 'blocks')) await fs.copy(path.join(ipfsFixturesDir, 'datastore'), path.join(ipfsd.path, 'datastore')) await fs.copy(dbFixturesDir, dbPath) @@ -56,19 +58,22 @@ Object.keys(testAPIs).forEach(API => { after(async () => { rmrf.sync(dbPath) - if (orbitdb) { await orbitdb.stop() } + if(orbitdb) + await orbitdb.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('Open & Load', function () { + describe('Open & Load', function() { before(async () => { db = await orbitdb.open('/orbitdb/QmWDUfC4zcWJGgc9UHn1X3qQ5KZqBv4KCiCtjnpMmBT8JC/v0-db', { accessController: { type: 'legacy-ipfs', skipManifest: true } }) await db.load() }) after(async () => { - if (db) { await db.close() } + if (db) + await db.close() }) it('open v0 orbitdb address', async () => { @@ -91,12 +96,13 @@ Object.keys(testAPIs).forEach(API => { assert.strictEqual(db.access.write[0], '04b54f6ef529cd2dd2f9c6897a382c492222d42e57826269a38101ffe752aa07260ecd092a970d7eef08c4ddae2b7006ee25f07e4ab62fa5262ae3b51fdea29f78') }) - it.skip('load v0 orbitdb address', async () => { + it('load v0 orbitdb address', async () => { + assert.equal(db.all.length, 3) }) - it.skip('allows migrated key to write', async () => { - const hash = await db.add({ thing: 'new addition' }) + it('allows migrated key to write', async () => { + const hash = await db.add({ thing: 'new addition'}) const newEntries = db.all.filter(e => e.v === 1) assert.equal(newEntries.length, 1) assert.strictEqual(newEntries[0].hash, hash) diff --git a/test/write-permissions.test.js b/test/write-permissions.test.js index baf710298..c6d31974f 100644 --- a/test/write-permissions.test.js +++ b/test/write-permissions.test.js @@ -18,7 +18,7 @@ const dbPath = './orbitdb/tests/write-permissions' const ipfsPath = './orbitdb/tests/write-permissions/ipfs' Object.keys(testAPIs).forEach(API => { - describe(`orbit-db - Write Permissions (${API})`, function () { + describe(`orbit-db - Write Permissions (${API})`, function() { this.timeout(20000) let ipfsd, ipfs, orbitdb1, orbitdb2 @@ -34,14 +34,17 @@ Object.keys(testAPIs).forEach(API => { }) after(async () => { - if (orbitdb1) { await orbitdb1.stop() } + if(orbitdb1) + await orbitdb1.stop() - if (orbitdb2) { await orbitdb2.stop() } + if(orbitdb2) + await orbitdb2.stop() - if (ipfsd) { await stopIpfs(ipfsd) } + if (ipfsd) + await stopIpfs(ipfsd) }) - describe('allows multiple peers to write to the databases', function () { + describe('allows multiple peers to write to the databases', function() { databases.forEach(async (database) => { it(database.type + ' allows multiple writers', async () => { let options = { @@ -70,7 +73,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('syncs databases', function () { + describe('syncs databases', function() { databases.forEach(async (database) => { it(database.type + ' syncs', async () => { let options = { @@ -105,7 +108,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('syncs databases that anyone can write to', function () { + describe('syncs databases that anyone can write to', function() { databases.forEach(async (database) => { it(database.type + ' syncs', async () => { let options = { @@ -137,9 +140,10 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('doesn\'t sync if peer is not allowed to write to the database', function () { + describe('doesn\'t sync if peer is not allowed to write to the database', function() { databases.forEach(async (database) => { it(database.type + ' doesn\'t sync', async () => { + let options = { // Only peer 1 can write accessController: { @@ -187,7 +191,7 @@ Object.keys(testAPIs).forEach(API => { }) }) - describe('throws an error if peer is not allowed to write to the database', function () { + describe('throws an error if peer is not allowed to write to the database', function() { databases.forEach(async (database) => { it(database.type + ' throws an error', async () => { let options = {