Skip to content

Instantly share code, notes, and snippets.

@datafatmunger
Created June 27, 2018 10:36
Show Gist options
  • Select an option

  • Save datafatmunger/3734f38f35164b8e990ab3f2f0b5dfbe to your computer and use it in GitHub Desktop.

Select an option

Save datafatmunger/3734f38f35164b8e990ab3f2f0b5dfbe to your computer and use it in GitHub Desktop.
var crypto = require('crypto'),
sha = crypto.createHash('sha1'),
hyperdb = require('hyperdb'),
hyperdiscovery = require('hyperdiscovery'),
cms = require('random-access-idb')('cms'),
webrtc = require('webrtc-swarm'),
signalhub = require('signalhub'),
hyperdrive = require('hyperdrive'),
pump = require('pump');
//var db = hyperdb("./db", { valueEncoding: 'utf-8' });
var db = hyperdb((filename) => {
return cms(filename);
}, { valueEncoding: 'utf-8' });
var DEFAULT_SIGNALHUBS = 'http://localhost/signalhub';
//var archive = hyperdrive();
//var link = archive.discoveryKey.toString('hex');
db.on('ready', function () {
var key = db.key.toString('hex');
var disckey = db.discoveryKey.toString('hex');
console.log('KEY: ' + key);
console.log('DISC KEY: ' + disckey);
console.log('LOCAL KEY: ' + db.local.key.toString('hex'));
var swarm = webrtc(signalhub(disckey, DEFAULT_SIGNALHUBS));
swarm.on('peer', function (conn) {
console.log("PEER!!!!!!!");
var peer = db.replicate({
upload: true,
download: true
});
pump(conn, peer, conn)
});
// swarm = hyperdiscovery(db);
// swarm.on('connection', (peer, type) => {
// console.log('PEER: ' + peer.key.toString('hex'));
// });
});
var createKey = (str) => {
sha.update(JSON.stringify(str));
return sha.digest('hex');
};
var put = (obj, callback) => {
var objStr = JSON.stringify(obj);
var key = createKey(objStr);
db.put(key, objStr, (err) => {
if(err) throw err;
else if(callback) callback(key);
});
};
var get = (key, callback) => {
db.get(key, (err, nodes) => {
if(err) throw err;
else if(callback) callback(JSON.parse(nodes[0].value));
});
};
//put({ foo: "bar" }, (key) => {
// console.log("KEY: " + key);
// get(key, (obj) => {
// console.log(obj);
// console.log(obj.foo);
// });
//});
//
//setInterval(() => {
// console.log("running...");
//}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment