Skip to content

Instantly share code, notes, and snippets.

@phillmac

phillmac/api.js

Created Mar 12, 2019
Embed
What would you like to do?
Orbit-DB Http API
const IpfsApi = require('ipfs-api');
const OrbitDB = require('orbit-db');
const Express = require('express');
const DBManager = require('./dbmanager.js').DBManager
const api_port = process.env.API_PORT;
const ipfs_host = process.env.IPFS_HOST
const ipfs_port = process.env.IPFS_PORT
const orbitdb_dir = process.env.ORBITDB_DIR
const app = Express();
const ipfs = IpfsApi(ipfs_host, ipfs_port)
const orbitdb = new OrbitDB(ipfs, orbitdb_dir)
const dbm = new DBManager(orbitdb)
app.use(function (err, req, res, next) {
console.error(err)
res.status(500).json('ERROR')
})
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
app.get('/dbs', (req, res, next) => {
try {
return res.json(dbm.db_list());
} catch(err) {next(err)}
});
app.get('/db/:dbname', (req, res, next) => {
try {
return res.json(dbm.db_info(req.params.dbname));
} catch(err) {next(err)}
});
app.post('/db/:dbname', asyncMiddleware( async (req, res, next) => {
db = await dbm.get(req.params.dbname, req.body)
return res.json(dbm.db_info(db.dbname));
}));
async function init() {
try {
app.listen(api_port, () => {
console.log(`Server running on port ${api_port}`);
});
} catch (e) {
console.error(e)
process.exit(1)
}
}
init()
class DBManager {
constructor(orbitdb){
let _dbs = {};
this.get = async (dbname, params) => {
if (dbname in _dbs) {
return _dbs[dbname];
} else {
let db
console.log(`Opening db ${dbname}`)
db = await orbitdb.open(dbname, params);
await db.load()
console.log(`Loaded db ${db.dbname}`)
_dbs[db.dbname] = db;
return db;
}
};
this.db_list = () => {
let db_info_list = {};
for (var dbn in _dbs) {
if (_dbs.hasOwnProperty(dbn)) {
db_info_list[dbn] = this.db_info(dbn);
}
}
return JSON.stringify(db_info_list);
};
this.db_info = (dbn) => {
var db = _dbs[dbn]
if (!db) return {}
return {
address: db.address,
dbname: db.dbname,
id: db.id,
options: {
create: db.options.create,
indexBy: db.options.indexBy,
localOnly: db.options.localOnly,
maxHistory: db.options.maxHistory,
overwrite: db.options.overwrite,
path: db.options.path,
replicate: db.options.replicate,
},
type: db.type,
uid: db.uid
};
};
}
}
exports.DBManager = DBManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.