query.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const filterMetadata = (o) => {
  2. const copy = {...o};
  3. delete copy._;
  4. return copy;
  5. };
  6. const flatten = (arr) => {
  7. return arr.reduce((c,v) => {
  8. if(Array.isArray(v)){
  9. return c.concat(flatten(v));
  10. }
  11. return c.concat(v);
  12. }, []);
  13. };
  14. function Query(db) {
  15. if(!(this instanceof Query)) {
  16. return new Query(db);
  17. }
  18. this.db = db;
  19. this.nodes = [];
  20. this.cursor = 0;
  21. this.ctx = void 0;
  22. }
  23. Query.prototype.add = function add(node) {
  24. this.cursor += 1;
  25. this.nodes.push(node);
  26. this.ctx = this.nodes[this.nodes.length - 1];
  27. };
  28. Query.prototype.getSet = function getSet() {
  29. const n = this.ctx.then(v => {
  30. if(Array.isArray(v)) {
  31. return v.map(filterMetadata);
  32. }
  33. return filterMetadata(v);
  34. })
  35. .then(r => {
  36. const getValues = (node) => {
  37. return Promise.all(Object.keys(node).map(k => this.db.get(k).then()));
  38. };
  39. if(Array.isArray(r)) {
  40. return Promise.all(r.map(getValues)).then(flatten);
  41. }
  42. return getValues(r);
  43. })
  44. this.add(n);
  45. return this;
  46. }
  47. Query.prototype.get = function get(path) {
  48. if(this.cursor === 0) {
  49. const node = this.db.get(path).then();
  50. this.add(node);
  51. return this;
  52. }
  53. const prev = this.nodes[this.cursor - 1];
  54. const pNode = prev.then(r => {
  55. if(Array.isArray(r)) {
  56. const nodes = r.map(v => {
  57. if(v[path] && v[path]["#"]) {
  58. return this.db.get(v[path]["#"]).then();
  59. }
  60. return v[path] ? Promise.resolve(v[path]) : "";
  61. });
  62. return Promise.all(nodes.filter(v => v));
  63. }
  64. if(r[path] && r[path]["#"]) {
  65. return this.db.get(r[path]["#"]).then();
  66. }
  67. return r[path] ? Promise.resolve(r[path]) : "";
  68. });
  69. this.add(pNode);
  70. return this;
  71. };
  72. Query.prototype.data = function data(cb) {
  73. return this.ctx.then(v => {
  74. if(Array.isArray(v)) {
  75. return Promise.all(v);
  76. }
  77. return v;
  78. });
  79. };
  80. export {Query}