memdisk.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Take caution running this in production, it ONLY saves to disk what is in memory.
  2. var Gun = require('../gun'),
  3. fs = require('fs');
  4. Gun.on('opt', function(ctx){
  5. this.to.next(ctx);
  6. var opt = ctx.opt;
  7. if(ctx.once){ return }
  8. opt.file = String(opt.file || 'data.json');
  9. var graph = ctx.graph, acks = {}, count = 0, to;
  10. var disk = Gun.obj.ify((fs.existsSync || require('path').existsSync)(opt.file)?
  11. fs.readFileSync(opt.file).toString()
  12. : null) || {};
  13. ctx.on('put', function(at){
  14. this.to.next(at);
  15. Gun.graph.is(at.put, null, map);
  16. if(!at['@']){ acks[at['#']] = true; } // only ack non-acks.
  17. count += 1;
  18. if(count >= (opt.batch || 10000)){
  19. return flush();
  20. }
  21. if(to){ return }
  22. to = setTimeout(flush, opt.wait || 1);
  23. });
  24. ctx.on('get', function(at){
  25. this.to.next(at);
  26. var lex = at.get, soul, data, opt, u;
  27. //setTimeout(function(){
  28. if(!lex || !(soul = lex['#'])){ return }
  29. //if(0 >= at.cap){ return }
  30. var field = lex['.'];
  31. data = disk[soul] || u;
  32. if(data && field){
  33. data = Gun.state.to(data, field);
  34. }
  35. ctx.on('in', {'@': at['#'], put: Gun.graph.node(data)});
  36. //},11);
  37. });
  38. var map = function(val, key, node, soul){
  39. disk[soul] = Gun.state.to(node, key, disk[soul]);
  40. }
  41. var wait;
  42. var flush = function(){
  43. if(wait){ return }
  44. wait = true;
  45. clearTimeout(to);
  46. to = false;
  47. var ack = acks;
  48. acks = {};
  49. fs.writeFile(opt.file, JSON.stringify(disk, null, 2), function(err, ok){
  50. wait = false;
  51. var tmp = count;
  52. count = 0;
  53. Gun.obj.map(ack, function(yes, id){
  54. ctx.on('in', {
  55. '@': id,
  56. err: err,
  57. ok: 0 // memdisk should not be relied upon as permanent storage.
  58. });
  59. });
  60. if(1 < tmp){ flush() }
  61. });
  62. }
  63. });