0

The server gets an array of query terms from a frontend ajax call:

req.query.filterTerms=['black', 'white', 'green']

I need to chain each ofthese filters to the bodybuilder query which is:

var body=bodybuilder()
.query('match', 'searchable', req.query.querytext)
.from(i)
.build();

How do i dynamically chain .filter() method/function for each of the query terms in the array to the bodybuilder instance?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
Zee
  • 13
  • 7

2 Answers2

1

You might be able to use reduce:

    const filterTerms = ['red', 'green', 'black'];
    const body = bodybuilder();
    body.query('match', 'searchable', 'foobar');
    const chainedFilter = filterTerms.reduce((filterBody, term) => {
        return filterBody.filter('match', 'term', term)
    }, body);
    console.log(JSON.stringify(body.build(), null, 2))
<script src="https://rawgit.com/danpaz/bodybuilder/master/browser/bodybuilder.min.js"></script>

This is the functional equivalent of chaining the commands together.

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
0

for anyone with a similar problem, try console.log the body object created with the build method on the bodybuilder instance, after manually inserting a filter method on the instance with the parameters typed by you manually.It will show the structure that you can use to append to the bodybuilder filter clauses.

Zee
  • 13
  • 7