From 87652467b55b3c22ea5cfb17d9e6eafa3b6bd63c Mon Sep 17 00:00:00 2001 From: Bradley Matusiak Date: Mon, 6 Jun 2022 18:02:36 -0400 Subject: [PATCH] chain fork (#1247) * chain fork * removed test * removed unbuild * moved chain fork to libs folder --- lib/fork.js | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 lib/fork.js diff --git a/lib/fork.js b/lib/fork.js new file mode 100644 index 00000000..3d60d9a0 --- /dev/null +++ b/lib/fork.js @@ -0,0 +1,81 @@ +/* +describe('API Chain Features', function(){ + + describe('Gun.chain.fork', function(){ + var gun = Gun(); + var fork; + it('create fork', function(done){ + fork = gun.fork().wire(); + done(); + }); + it('put data via fork', function(done){ + fork.get("fork-test").get("fork").put("test123").once(()=>done()); + }); + it('get data via main', function(done){ + gun.get("fork-test").get("fork").once((data)=>{ + expect(data).to.be("test123"); + done(); + }); + }); + it('put data via main', function(done){ + gun.get("fork-test").get("main").put("test321").once(()=>done()); + }); + it('get data via fork', function(done){ + fork.get("fork-test").get("main").once((data)=>{ + expect(data).to.be("test321"); + done(); + }); + }); + }) + +}) +*/ +(function (Gun, u) { + /** + * + * credits: + * github:bmatusiak + * + */ + Gun.chain.fork = function(g) { + var gun = this._; + var w = {}, + mesh = () => { + var root = gun.root, + opt = root.opt; + return opt.mesh || Gun.Mesh(root); + } + w.link = function() { + if (this._l) return this._l; + this._l = { + send: (msg) => { + if (!this.l || !this.l.onmessage) + throw 'not attached'; + this.l.onmessage(msg); + } + } + return this._l; + }; + w.attach = function(l) { + if (this.l) + throw 'already attached'; + var peer = { wire: l }; + l.onmessage = function(msg) { + mesh().hear(msg.data || msg, peer); + }; + mesh().hi(this.l = l && peer); + }; + w.wire = function(opts) { + var f = new Gun(opts); + f.fork(w); + return f; + }; + if (g) { + w.attach(g.link()); + g.attach(w.link()); + } + return w; + }; + + +})((typeof window !== "undefined") ? window.Gun : require('../gun')) \ No newline at end of file