file.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // This was written by the wonderful Forrest Tait
  2. // modified by Mark to be part of core for convenience
  3. // twas not designed for production use
  4. // only simple local development.
  5. var Gun = require('../gun'),
  6. fs = require('fs');
  7. Gun.on('create', function(root){
  8. this.to.next(root);
  9. var opt = root.opt;
  10. if(true !== opt.localStorage){ return }
  11. if(false === opt.localStorage){ return }
  12. //if(process.env.RAD_ENV){ return }
  13. //if(process.env.AWS_S3_BUCKET){ return }
  14. opt.file = String(opt.file || 'data.json');
  15. var graph = root.graph, acks = {}, count = 0, to;
  16. var disk = Gun.obj.ify((fs.existsSync || require('path').existsSync)(opt.file)?
  17. fs.readFileSync(opt.file).toString()
  18. : null) || {};
  19. Gun.log.once(
  20. 'file-warning',
  21. 'WARNING! This `file.js` module for gun is ' +
  22. 'intended for local development testing only!'
  23. );
  24. root.on('put', function(at){
  25. this.to.next(at);
  26. Gun.graph.is(at.put, null, map);
  27. if(!at['@']){ acks[at['#']] = true; } // only ack non-acks.
  28. count += 1;
  29. if(count >= (opt.batch || 10000)){
  30. return flush();
  31. }
  32. if(to){ return }
  33. to = setTimeout(flush, opt.wait || 1);
  34. });
  35. root.on('get', function(at){
  36. this.to.next(at);
  37. var lex = at.get, soul, data, opt, u;
  38. //setTimeout(function(){
  39. if(!lex || !(soul = lex['#'])){ return }
  40. //if(0 >= at.cap){ return }
  41. if(Gun.obj.is(soul)){ return match(at) }
  42. var field = lex['.'];
  43. data = disk[soul] || u;
  44. if(data && field){
  45. data = Gun.state.to(data, field);
  46. }
  47. root.on('in', {'@': at['#'], put: Gun.graph.node(data)});
  48. //},11);
  49. });
  50. var map = function(val, key, node, soul){
  51. disk[soul] = Gun.state.to(node, key, disk[soul]);
  52. }
  53. var wait, u;
  54. var flush = function(){
  55. if(wait){ return }
  56. clearTimeout(to);
  57. to = false;
  58. var ack = acks;
  59. acks = {};
  60. fs.writeFile(opt.file, JSON.stringify(disk), function(err, ok){
  61. wait = false;
  62. var tmp = count;
  63. count = 0;
  64. Gun.obj.map(ack, function(yes, id){
  65. root.on('in', {
  66. '@': id,
  67. err: err,
  68. ok: err? u : 1
  69. });
  70. });
  71. if(1 < tmp){ flush() }
  72. });
  73. }
  74. function match(at){
  75. var rgx = at.get['#'], has = at.get['.'];
  76. Gun.obj.map(disk, function(node, soul, put){
  77. if(!Gun.text.match(soul, rgx)){ return }
  78. if(has){ node = Gun.state.to(node, has) }
  79. (put = {})[soul] = node;
  80. root.on('in', {put: put, '@': at['#']});
  81. });
  82. }
  83. });