UNPKG

2.99 kBJavaScriptView Raw
1/*!
2 * A MongoDB inspired ES6 Map() query language. - Copyright (c) 2017 Louis T. (https://lou.ist/)
3 * Licensed under the MIT license https://raw.githubusercontent.com/LouisT/MapQL/master/LICENSE
4 */
5'use strict';
6const Helpers = require('./Helpers');
7
8class ChainManager {
9 constructor (MapQL) {
10 // Save a link to MapQL for `execute()`.
11 this.MapQL = MapQL;
12
13 // Place holder for chained queries.
14 this._chains = {};
15
16 // Place holder for chainable functions.
17 this._chainables = {};
18
19 // Generate the chainable functions.
20 // {Instance}.gt(<Key / Value>[, <Value>]).lt(<Key / Value>[, <Value>]).execute([<Projections>)
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 * Return the chains for query object if not empty otherwise false.
43 */
44 get query () {
45 return !!Object.keys(this._chains).length ? this._chains : false;
46 }
47
48 /*
49 * Execute the chained commands.
50 */
51 execute (projections = {}, one = false) {
52 return this.MapQL[one ? 'findOne' : 'find'](this.query, projections);
53 }
54
55 /*
56 * Generate a chainable object.
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 * Builed the chain operator and logical object with all the queries.
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 * Export the chain manager for use!
80 */
81module.exports = ChainManager;