Skip to content

Commit

Permalink
added fq() for passing in an object or multiple filters (#241)
Browse files Browse the repository at this point in the history
Co-authored-by: Niklas Donath <niklas.donath@lv.de>
  • Loading branch information
ni-do and Niklas Donath committed Apr 28, 2021
1 parent 960aa53 commit e74e486
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,34 @@ Query.prototype.matchFilter = function (field, value) {
return self;
};

/**
* wrapper function for matchFilter, accepting either an object with `field` and `value` properties
* or an array containing such objects to be mapped on matchFilter
*
* @param {Object|Array} filters - Object or an array of objects with `field` and `value` properties
*
* @return {Query}
*
* @throws {Error}
* @api public
*
* @example
* var query = client.createQuery();
* query.q({ '*' : '*' }).fq({field: 'id', value: 100})
* query.q({ '*' : '*' }).fq([{field: 'id', value: 100}, {field: 'name', value: 'John'}])
*/
Query.prototype.fq = function (filters) {
const self = this
if (Array.isArray(filters)) {
filters.map(f => this.matchFilter(f.field, f.value))
return self
}
if (filters instanceof Object) return this.matchFilter(filters.field, filters.value)
else {
throw new Error('unknown type for filter in fq()')
}
}

/**
* Specify a set of fields to return.
*
Expand Down
38 changes: 38 additions & 0 deletions test/core-query-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,5 +266,43 @@ describe('Client#createQuery', function () {
done();
});
});

it('query with multiple match-filters', function (done) {
const query = client
.createQuery()
.q('*:*')
.fq([{field: 'id', value: '19700506.173.85'}, {field: 'title', value: 'testvalue'}])
.debugQuery();

client.search(query, function (err, data) {
sassert.ok(err, data);
assert.deepEqual(data.responseHeader.params, {
debugQuery: 'true',
q: '*:*',
fq: ['id:19700506.173.85', 'title:testvalue'],
wt: 'json',
});
done();
});
});

it('query with object match-filter', function (done) {
const query = client
.createQuery()
.q('*:*')
.fq({field: 'id', value: '19700506.173.85'})
.debugQuery();

client.search(query, function (err, data) {
sassert.ok(err, data);
assert.deepEqual(data.responseHeader.params, {
debugQuery: 'true',
q: '*:*',
fq: 'id:19700506.173.85',
wt: 'json',
});
done();
});
});
});
});

0 comments on commit e74e486

Please sign in to comment.