Home > Back-end >  A way to conditionally chain functions?
A way to conditionally chain functions?

Time:07-15

What im trying to do is to write a universal function for retrieving items from database using redis-om-node. It uses this chain of methods to specify what items we want to retrieve

const items = await repositoryObject
.search()
.where("property1")
.match(query)
.or("property2")
.match(query)
.or("property3")
.match(query)
.return.all();

Is there a way I could loop through array of properties to make this chain write itself like:

const items = await repositoryObject
.search()[loop outputed chain].return.all();

Im aware that I can just run raw search but I want to know am I missing something about javascript objects

CodePudding user response:

Sure, you could create an array of objects which contain the properties and corresponding queries that you want to use, and then loop through it like this:

const queries = [{ property: "property1", query: query1 }, { property: "property2", query: query2 }, { property: "property3", query: query3 }]; // etc

let result = repositoryObject.search();

for (const { property, query } of queries) {
  result = result.where(property).match(query);
}

return result.return.all();

You could get more fancy and use reduce if you wanted to:

// queries is as above

return queries.reduce((object, { property, query }) => object.property(property).match(query), repositoryObject.search()).return.all();

or use the forEach method on the array to loop. Basically you can loop all the ways you have in normal Javascript - you just have to use it to construct a property chain of the form you showed us.

  • Related