oasis/src/models/cooler/index.js

119 lines
2.5 KiB
JavaScript
Raw Normal View History

2019-07-28 20:49:01 +00:00
'use strict'
2019-08-15 01:10:22 +00:00
const debug = require('debug')('oasis')
2019-06-23 18:46:22 +00:00
const ssbClient = require('ssb-client')
2019-08-15 01:10:22 +00:00
2019-07-03 18:21:47 +00:00
const rawConnect = () => new Promise((resolve, reject) => {
ssbClient({
manifest: {
2019-10-08 01:53:21 +00:00
about: {
socialValue: 'async',
read: 'source'
},
backlinks: { read: 'source' },
2019-10-01 20:44:31 +00:00
blobs: {
get: 'source',
ls: 'source',
want: 'async'
},
2019-11-15 19:42:32 +00:00
conn: {
peers: 'source'
},
createUserStream: 'source',
2019-09-23 15:45:18 +00:00
createHistoryStream: 'source',
get: 'sync',
messagesByType: 'source',
publish: 'async',
status: 'async',
2019-10-01 00:37:30 +00:00
tangle: { branch: 'async' },
2019-12-07 22:58:08 +00:00
query: { read: 'source' },
friends: {
isFollowing: 'async',
isBlocking: 'async'
2019-12-07 23:22:00 +00:00
},
search: {
query: 'source'
2019-12-07 22:58:08 +00:00
}
}
}, (err, api) => {
2019-08-15 01:10:22 +00:00
if (err) {
reject(err)
} else {
resolve(api)
}
2019-07-03 18:21:47 +00:00
})
})
const db = {
2019-08-15 01:10:22 +00:00
connect () {
// This has interesting behavior that may be unexpected.
//
// If `handle` is already an active [non-closed] connection, return that.
//
// If the connection is closed, we need to restart it. It's important to
// note that if we're depending on an external service (like Patchwork) and
// that app is closed, then Oasis will seamlessly start its own SSB service.
return new Promise((resolve, reject) => {
handle.then((ssb) => {
if (ssb.closed) {
createConnection()
}
resolve(handle)
})
})
2019-06-23 18:46:22 +00:00
},
/**
* @param {function} method
*/
2019-08-15 01:10:22 +00:00
get (method, ...opts) {
2019-06-23 18:46:22 +00:00
return new Promise((resolve, reject) => {
method(...opts, (err, val) => {
2019-08-15 01:10:22 +00:00
if (err) {
reject(err)
} else {
resolve(val)
}
2019-06-23 18:46:22 +00:00
})
})
},
2019-08-15 01:10:22 +00:00
read (method, ...args) {
return new Promise((resolve) => {
2019-06-23 18:46:22 +00:00
resolve(method(...args))
})
}
}
debug.enabled = true
let handle
const createConnection = () => {
handle = new Promise((resolve) => {
rawConnect().then((ssb) => {
debug('Using pre-existing Scuttlebutt server instead of starting one')
resolve(ssb)
}).catch(() => {
debug('Initial connection attempt failed')
debug('Starting Scuttlebutt server')
require('./server')
const connectOrRetry = () => {
rawConnect().then((ssb) => {
debug('Retrying connection to own server')
resolve(ssb)
}).catch((e) => {
debug(e)
connectOrRetry()
})
}
connectOrRetry()
})
2019-07-03 18:21:47 +00:00
})
return handle
}
createConnection()
module.exports = db