1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.Query = void 0;
|
4 | var core_1 = require("./core");
|
5 | var cursor_1 = require("./cursor");
|
6 | var util_1 = require("./util");
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | var Query = (function () {
|
15 | function Query(criteria, options) {
|
16 | this.criteria = criteria;
|
17 | this.options = options;
|
18 | this.options = (0, core_1.makeOptions)(options);
|
19 | this.compiled = [];
|
20 | this.compile();
|
21 | }
|
22 | Query.prototype.compile = function () {
|
23 | (0, util_1.assert)((0, util_1.isObject)(this.criteria), "query criteria must be an object");
|
24 | var whereOperator;
|
25 | for (var _i = 0, _a = Object.entries(this.criteria); _i < _a.length; _i++) {
|
26 | var _b = _a[_i], field = _b[0], expr = _b[1];
|
27 | if ("$where" === field) {
|
28 | whereOperator = { field: field, expr: expr };
|
29 | }
|
30 | else if ((0, util_1.inArray)(["$and", "$or", "$nor", "$expr", "$jsonSchema"], field)) {
|
31 | this.processOperator(field, field, expr);
|
32 | }
|
33 | else {
|
34 |
|
35 | (0, util_1.assert)(!(0, util_1.isOperator)(field), "unknown top level operator: " + field);
|
36 | for (var _c = 0, _d = Object.entries((0, util_1.normalize)(expr)); _c < _d.length; _c++) {
|
37 | var _e = _d[_c], operator = _e[0], val = _e[1];
|
38 | this.processOperator(field, operator, val);
|
39 | }
|
40 | }
|
41 | if ((0, util_1.isObject)(whereOperator)) {
|
42 | this.processOperator(whereOperator.field, whereOperator.field, whereOperator.expr);
|
43 | }
|
44 | }
|
45 | };
|
46 | Query.prototype.processOperator = function (field, operator, value) {
|
47 | var call = (0, core_1.getOperator)(core_1.OperatorType.QUERY, operator);
|
48 | (0, util_1.assert)(!!call, "unknown operator " + operator);
|
49 | var fn = call(field, value, this.options);
|
50 | this.compiled.push(fn);
|
51 | };
|
52 | |
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | Query.prototype.test = function (obj) {
|
59 | for (var i = 0, len = this.compiled.length; i < len; i++) {
|
60 | if (!this.compiled[i](obj)) {
|
61 | return false;
|
62 | }
|
63 | }
|
64 | return true;
|
65 | };
|
66 | |
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | Query.prototype.find = function (collection, projection) {
|
74 | var _this = this;
|
75 | return new cursor_1.Cursor(collection, function (x) { return _this.test(x); }, projection || {}, this.options);
|
76 | };
|
77 | |
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 | Query.prototype.remove = function (collection) {
|
84 | var _this = this;
|
85 | return collection.reduce(function (acc, obj) {
|
86 | if (!_this.test(obj))
|
87 | acc.push(obj);
|
88 | return acc;
|
89 | }, []);
|
90 | };
|
91 | return Query;
|
92 | }());
|
93 | exports.Query = Query;
|