1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 | const Helpers = require('./Helpers');
|
7 |
|
8 | class ChainManager {
|
9 | constructor (MapQL) {
|
10 |
|
11 | this.MapQL = MapQL;
|
12 |
|
13 |
|
14 | this._chains = {};
|
15 |
|
16 |
|
17 | this._chainables = {};
|
18 |
|
19 |
|
20 |
|
21 | Object.keys(this.MapQL.queryOperators).forEach((qo) => {
|
22 | let qoName = qo.replace(/^\$/,'');
|
23 | this[qoName] = (key, val = Helpers._null, getChain = false) => {
|
24 | return (!getChain ? this._addChain : this._getOperatorChain).call(this, key, val, `${qo}`);
|
25 | };
|
26 | this._chainables[qoName] = (key, val) => {
|
27 | return this[qoName].call(this, key, val, true);
|
28 | };
|
29 | });
|
30 | Object.keys(this.MapQL.logicalOperators).forEach((lo) => {
|
31 | let loName = lo.replace(/^\$/,'');
|
32 | this[loName] = (fn = () => { return [] }, getChain = false) => {
|
33 | return (!getChain ? this._addChain : this._getLogicalChain).call(this, Helpers._null, fn, `${lo}`, true);
|
34 | };
|
35 | this._chainables[loName] = (fn = () => { return [] }) => {
|
36 | return this[loName].call(this, fn, `${lo}`, true);
|
37 | };
|
38 | });
|
39 | }
|
40 |
|
41 | |
42 |
|
43 |
|
44 | get query () {
|
45 | return !!Object.keys(this._chains).length ? this._chains : false;
|
46 | }
|
47 |
|
48 | |
49 |
|
50 |
|
51 | execute (projections = {}, one = false) {
|
52 | return this.MapQL[one ? 'findOne' : 'find'](this.query, projections);
|
53 | }
|
54 |
|
55 | |
56 |
|
57 |
|
58 | _getOperatorChain (key, val = Helpers._null, $qo = '$eq') {
|
59 | try {
|
60 | return this.MapQL.constructor.queryOperators[$qo].chain(key, val, $qo);
|
61 | } catch (error) {
|
62 | return val !== Helpers._null ? { [key] : { [$qo]: val } } : { [$qo]: key };
|
63 | }
|
64 | }
|
65 | _getLogicalChain (undf, fn = () => { return [] }, $lo = '$and') {
|
66 | return { [$lo] : fn.call(this, this._chainables) };
|
67 | }
|
68 |
|
69 | |
70 |
|
71 |
|
72 | _addChain (key, val, $type = '$eq', logical = false) {
|
73 | Object.assign(this._chains, (!logical ? this._getOperatorChain : this._getLogicalChain).call(this, key, val, $type));
|
74 | return this;
|
75 | }
|
76 | }
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | module.exports = ChainManager;
|