Skip to content

Instantly share code, notes, and snippets.

@haadcode
Created December 2, 2017 06:38
Show Gist options
  • Save haadcode/4bba3ede25e4f2bca191f886e7564c3e to your computer and use it in GitHub Desktop.
Save haadcode/4bba3ede25e4f2bca191f886e7564c3e to your computer and use it in GitHub Desktop.
const IPFS = require('ipfs')
const OrbitDB = require('./src/OrbitDB')
let orbitdb
let access
let userDb
let feedDb
let followingDb
const replicateQueue = []
let isReplicating = false
let replicateCb
function init() {
return new Promise(res => {
const ipfs = new IPFS({
// repo: './vitriol-orbit/1',
repo: './vitriol-orbit/2',
EXPERIMENTAL: { pubsub: true },
config: {
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'
},
}
})
ipfs.on('ready', async () => {
// if (!orbitdb) orbitdb = new OrbitDB(ipfs, './orbitdb/1')
if (!orbitdb) orbitdb = new OrbitDB(ipfs, './orbitdb/2')
if (!access) access = {
// Give write access to ourselves
write: [orbitdb.key.getPublic('hex')]
}
console.log("1")
// await enqueueDb({ type: 'feed', dbAddress: 'hello-feed' })
// await enqueueDb({ type: 'user', dbAddress: 'hello-user' })
await enqueueDb({ type: 'user', dbAddress: '/orbitdb/QmX9QVwjjTM87RjreDUNuaEoyTvc9c9nQou8Zuw8R8PCvN/hello-user' }, (res) => {
console.log("3 user", res)
})
await enqueueDb({ type: 'feed', dbAddress: '/orbitdb/QmRtuym5cfuJFZh5Z4qpt4SmahXdMBjLWFYF5xoquRRaX3/hello-feed' }, (res) => {
console.log("4 feed", res.map(e => e.payload))
})
console.log(getDbAddresses())
setUser('haad', 'Haad', 'Code')
post('hello friend')
console.log("2")
res()
})
})
}
function getPublicKey() {
if (orbitdb) return orbitdb.key.getPublic('hex')
return null
}
function getDbAddresses() {
if (userDb && feedDb) return {
userDb: userDb.address.toString(),
feedDb: feedDb.address.toString()
}
return null
}
async function onUserChange(onChange) {
if (!orbitdb) await init()
if (!userDb) userDb = await orbitdb.keyvalue('user-db', access)
userDb.events.on('write', () => {
onChange(getUser())
})
await userDb.load()
onChange(getUser())
}
function getUser () {
return {
userName: userDb.get('userName'),
firstName: userDb.get('firstName'),
lastName: userDb.get('lastName'),
publicKey: getPublicKey()
}
}
async function setUser(userName, firstName, lastName) {
await userDb.put('userName', userName)
await userDb.put('firstName', firstName)
await userDb.put('lastName', lastName)
}
function getFeed() {
return feedDb.iterator({limit: 10}).collect().reverse()
}
async function onFeedChange(onChange) {
if (!orbitdb) await init()
if (!feedDb) feedDb = await orbitdb.feed('feed-db', access)
feedDb.events.on('write', () => {
onChange(getFeed())
})
await feedDb.load()
onChange(getFeed())
}
async function post(text) {
feedDb.add({
text,
ts: Date.now()
})
}
async function onFollowingChange(onChange) {
if (!orbitdb) await init()
if (!followingDb) followingDb = await orbitdb.docstore('following-db', { indexBy: 'userDb' })
followingDb.events.on('write', () => {
onChange(getFollowing())
})
await followingDb.load()
onChange(getFollowing())
}
function getFollowing() {
return followingDb.query(() => true)
}
async function replicateUser(address) {
console.log('$$ starting replicateUser', address)
userDb = await orbitdb.keyvalue(address)
userDb.events.on('replicated', () => {
console.log('**REPLICATED EVENT (^user^ has been replicated)', address)
replicateCb({
userName: userDb.get('userName'),
firstName: userDb.get('firstName'),
lastName: userDb.get('lastName'),
publicKey: getPublicKey()
}, {
type: 'user',
address
})
})
userDb.events.on('replicate', () => {
console.log('**REPLICATE EVENT (^user^ is being replicated)', address)
})
userDb.events.on('replicate.progress', (addr, hash, entry) => {
console.log('**REPLICATE.PROGRESS EVENT (^user^ has progress)', entry.payload)
})
userDb.events.on('write', (addr, entry, heads) => {
console.log('**WRITE EVENT (^user^ has progress)')
})
console.log('$$ ending replicateUser', address)
}
async function replicateFeed(address) {
console.log('$$ starting replicateFeed', address)
feedDb = await orbitdb.feed(address)
feedDb.events.on('replicated', () => {
console.log('**REPLICATED EVENT (^feed^ has been replicated)', address)
replicateCb(
feedDb.iterator({limit: 10}).collect().reverse(),
{
type: 'feed',
address
}
)
})
feedDb.events.on('replicate', () => {
console.log('**REPLICATE EVENT (^feed^ is being replicated)', address)
})
feedDb.events.on('replicate.progress', (addr, hash, entry, progress, have) => {
console.log('**REPLICATE.PROGRESS EVENT (^feed^ has progress)', entry.payload)
})
feedDb.events.on('write', (addr, entry, heads) => {
console.log('**WRITE EVENT (^feed^ has progress)')
})
console.log('$$ ending replicateFeed', address)
}
async function replicate() {
isReplicating = true
const item = replicateQueue.splice(0, 1)[0]
console.log('replicating', item)
if (item) {
const { type, dbAddress } = item
switch(type) {
case 'user':
await replicateUser(dbAddress)
await replicate()
break
case 'feed':
await replicateFeed(dbAddress)
await replicate()
break
default:
break
}
} else {
isReplicating = false
}
}
async function enqueueDb(dbInfo, cb) {
console.log('enqueuing', dbInfo)
if (cb) replicateCb = cb
replicateQueue.push(dbInfo)
if (!isReplicating) await replicate()
}
async function follow(token) {
return followingDb.put(token)
}
init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment