0

I'd like a client side app to send a request to a back end that then does a get query to a cloud database. The tricky part I don't know how to do, is to build a chain of .where() methods on the query based on input data.

A successfully build method chain may look like this:

db
  .collection('cities')
  .get()
  .where('storeId', '==', '1029')
  .where('state', '==', 'CA')
  .where('population, '<=', '100000')
  .where('district', '==', 'purple');


// example of how I'd pass data to a wrapper method to build the above.

instance.getSome('1029', "cities", { 
  state : ["==", "CA"]
  , population : ["<=", "100000"]
  , district : ["==", "purple"]  
})

Is it possible to do this? I only have this so far, I'm not sure how to convert a string or similar into a method chain

async getSome(storeId, collection, whereClauses) {

}

Update

Based on an answer below this is a step by step work in progress:


  public async getSome(collection: string, whereClauses: object): Promise<object> {
    const baseQuery = db
      .collection(collection)
      .get()
      .where("storeId", "==", this.shopDomain);

    const whereClause2dArray = Object.entries(whereClauses);

    const stitchedQuery = whereClause2dArray
      .reduce((accumulatorQuery, [column, [operation, value]]) => {
        return accumulatorQuery.where(column, operation, value);
      }, baseQuery);

    return await stitchedQuery();
  }
Sean D
  • 3,810
  • 11
  • 45
  • 90

1 Answers1

2

You can do something like this:

async getSome(storeId, collection, whereClauses) {
  let query = db
  .collection(collection)
  .get()
  .where('storeId', '==', storeId);

  query = Object.entries(whereClauses).reduce(
    (query, [key, [operation, value]]) => query.where(key, operation, value)
  , query);

  return await query;
}
Titus
  • 22,031
  • 1
  • 23
  • 33
  • Looking into `Object.entries()` now, thank you. Once I test this I'll upvote and mark as best answer. – Sean D Jan 13 '20 at 08:13
  • Looks like copy/pasting this inside an empty class in jsbin.com, I get a SyntaxError on `return await query;` do you know why? – Sean D Jan 13 '20 at 20:27
  • 1
    @SeanDezoysa because as it is, the `getSome` should be inside a class body, to declare it as is, you need to use `async function getSome(....){....}` but it won't work as is because there is no `db`. – Titus Jan 13 '20 at 20:30
  • A few more questions if I may: 1. Does my step by step example (above) look correct? 2. Does your and my example run a non-usable database call on the 3rd line, where the base query is defined? 3. I added () onto your final line to actually invoke the call with the appended query, was this correct? – Sean D Jan 13 '20 at 22:11
  • @SeanDezoysa I don't know because I don't know what `db` is, I don't think you need the `()`, try removing that and the `await`, try using just `return stitchedQuery;` – Titus Jan 14 '20 at 09:09