-
Notifications
You must be signed in to change notification settings - Fork 2
/
find.js
103 lines (82 loc) · 2.6 KB
/
find.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var currentFilters = {};
function queryBuilder (filters) {
var self = this;
var query = {};
var fieldsInQuery = {};
for (filter in filters) {
if (!filters.hasOwnProperty(filter)) continue;
var cFilter = filters[filter];
if (!cFilter.disabled && self.config.operators[cFilter.operator]) {
var expression = {};
var value = cFilter.value;
var operator = self.config.operators[cFilter.operator];
// handle operators
if (operator[0]) {
expression[cFilter.field] = {};
expression[cFilter.field][operator[0]] = value;
} else {
expression[cFilter.field] = value;
}
// handle or
if (fieldsInQuery[cFilter.field]) {
// create or array and move the existing expression to the array
if (!query.$or) {
query.$or = [{}];
query.$or[0][cFilter.field] = query[cFilter.field];
delete query[cFilter.field];
}
query.$or.push(expression);
} else {
query[cFilter.field] = expression[cFilter.field];
}
fieldsInQuery[cFilter.field] = 1;
}
}
return {
t: self.template,
q: query,
o: self.options
};
}
function find (all, callback) {
var self = this;
// callback must be a function
callback = callback || function () {};
if (!self.template) {
var err = new Error('NO_TEMPLATE_SELECTED');
callback (err);
return self.emit('result', err);
}
if (self.crudFindBusy) {
var err = new Error('FILTER_IS_BUSY');
callback (err);
return self.emit('result', err);
}
self.crudFindBusy = true;
// build queries
self.query = all ? {} : queryBuilder.call(self, self.filters);
if (!self.query) {
if (self.wasEmpty) {
self.crudFindBusy = false;
var err = new Error('NO_FILTERS_SELECTED');
callback (err);
return self.emit('result', err);
}
self.wasEmpty = true;
self.query = {};
} else {
self.wasEmpty = false;
}
// get data with crud module
return self.emit('find', self.query, function (err, data) {
self.crudFindBusy = false;
if (err) {
err = err.message || err;
callback (err);
return console.error(err);
}
callback (err, data);
self.emit('result', err, data);
});
}
module.exports = find;