store.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var Gun = (typeof window !== "undefined")? window.Gun : require('../gun');
  2. Gun.on('create', function(root){
  3. this.to.next(root);
  4. var opt = root.opt, u;
  5. if(typeof window !== "undefined"){
  6. opt.window = window;
  7. }
  8. //if(true !== opt.radisk && (!opt.window && !process.env.RAD_ENV && !process.env.AWS_S3_BUCKET) && false !== opt.localStorage){ return }
  9. //if(true !== opt.radisk){ return }
  10. if(false === opt.radisk){ return }
  11. var Radisk = (opt.window && opt.window.Radisk) || require('./radisk');
  12. var Radix = Radisk.Radix;
  13. opt.store = opt.store || (!opt.window && require('./rfs')(opt));
  14. var rad = Radisk(opt), esc = String.fromCharCode(27);
  15. root.on('put', function(msg){
  16. this.to.next(msg);
  17. var id = msg['#'], track = !msg['@'], acks = track? 0 : u; // only ack non-acks.
  18. if(msg.rad && !track){ return } // don't save our own acks
  19. Gun.graph.is(msg.put, null, function(val, key, node, soul){
  20. if(track){ ++acks }
  21. val = Radisk.encode(val, null, esc)+'>'+Radisk.encode(Gun.state.is(node, key), null, esc);
  22. rad(soul+'.'+key, val, (track? ack : u));
  23. });
  24. function ack(err, ok){
  25. acks--;
  26. if(ack.err){ return }
  27. if(ack.err = err){
  28. root.on('in', {'@': id, err: err});
  29. return;
  30. }
  31. if(acks){ return }
  32. root.on('in', {'@': id, ok: 1});
  33. }
  34. });
  35. root.on('get', function(msg){
  36. this.to.next(msg);
  37. var id = msg['#'], soul = msg.get['#'], key = msg.get['.']||'', tmp = soul+'.'+key, node;
  38. rad(tmp, function(err, val){
  39. if(val){
  40. if(val && typeof val !== 'string'){ Radix.map(val, each) }
  41. if(!node){ each(val, key) }
  42. }
  43. root.on('in', {'@': id, put: Gun.graph.node(node), err: err? err : u, rad: Radix});
  44. });
  45. function each(val, key){
  46. tmp = val.lastIndexOf('>');
  47. var state = Radisk.decode(val.slice(tmp+1), null, esc);
  48. val = Radisk.decode(val.slice(0,tmp), null, esc);
  49. node = Gun.state.ify(node, key, state, val, soul);
  50. }
  51. });
  52. });