# all files / keystone/lib/list/ addSearchToQuery.js

19.05% Statements 8/42
0% Branches 0/18
0% Functions 0/6
20.51% Lines 8/39

    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
    611×
    1×

    1×
    1×

    1×

    1×

    1×

    1×
     var assign = require('object-assign');
    var utils = require('keystone-utils');

    function trim (i) { return i.trim(); }
    function truthy (i) { return i; }

    function getNameFilter (field, searchString) {
    	var searchWords = searchString.split(' ').map(trim).filter(truthy).map(utils.escapeRegExp);
    	var nameSearchRegExp = new RegExp(searchWords.join('|'), 'i');
    	var first = {};
    	first[field.paths.first] = nameSearchRegExp;
    	var last = {};
    	last[field.paths.last] = nameSearchRegExp;
    	return {
    		$or: [first, last],
    	};
    }

    function getStringFilter (path, searchRegExp) {
    	var filter = {};
    	filter[path] = searchRegExp;
    	return filter;
    }

    function addSearchToQuery (searchString, query) {
    	searchString = String(searchString || '').trim();
    	query = query || {};
    	if (!searchString) return query;

    	var searchRegExp = new RegExp(utils.escapeRegExp(searchString), 'i');
    	var searchFilters = this.searchFields.map(function (i) {
    		if (i.field && i.field.type === 'name') {
    			return getNameFilter(i.field, searchString);
    		} else {
    			return getStringFilter(i.path, searchRegExp);
    		}
    	}, this);

    	if (this.autokey) {
    		var autokeyFilter = {};
    		autokeyFilter[this.autokey.path] = searchRegExp;
    		searchFilters.push(autokeyFilter);
    	}

    	if (utils.isValidObjectId(searchString)) {
    		var idFilter = {};
    		idFilter._id = searchString;
    		searchFilters.push(idFilter);
    	}

    	if (searchFilters.length > 1) {
    		query.$or = searchFilters;
    	} else if (searchFilters.length) {
    		assign(query, searchFilters[0]);
    	}

    	return query;
    }

    module.exports = addSearchToQuery;