Repository navigation
Expand file tree
/
Copy pathbuildWhere.js
More file actions
53 lines (48 loc) · 1.47 KB
/
Copy pathbuildWhere.js
File metadata and controls
53 lines (48 loc) · 1.47 KB
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
'use strict';
module.exports = BuildWhere;
/**
* BuildWhere
* @param {Array} fields
* @param {String} matchType
* 'any' match any of the specified words. DEFAULT OPTION
* 'all' : match each and every word but may be separate
* 'full' : match the whole term without splitting words
* @param {Array} terms
* @return {Object} compatible with Sequelize's Model.findAll or Model.findAndCountAll
*/
function BuildWhere(fields, matchType, terms) {
var matchStrategies = {
'any': defaultConditions,
'full': defaultConditions,
'all': allInAnyFields
// 'all' used to be like this: (see https://github.com/tincho/customsearch/issues/5)
// function allInSameField() {
// return defaultConditions('$and');
// }
}
return matchStrategies[matchType]();
function defaultConditions(conditionType) {
conditionType = conditionType || '$or';
return {
'$or' : fields.map(field => ({
[field]: { [conditionType]: terms.map(term => ({'$like': term.wrap('%')})) }
}))
}
}
function allInAnyFields() {
return {
'$and': terms.map(term => ({
'$or': fields.map(field => ({
[field]: {'$like': term.wrap('%')}
}) )
}) )
}
}
}
/**
* wraps string with given chars if not already wrapped
*/
String.prototype.wrap = function(begin, end) {
end = end || begin;
return begin + this + end;
};