tywalch / electrodb

A DynamoDB library to ease the use of modeling complex hierarchical relationships and implementing a Single Table Design while keeping your query code readable.
MIT License
1.03k stars 66 forks source link

Conditional `where` operations #443

Closed raryanpur closed 3 weeks ago

raryanpur commented 3 weeks ago

Thanks again for building and supporting ElectroDB - it's awesome!

Is there a supported way to write conditional where operations? Currently, I just have the where operation return an empty string if the filter expression shouldn't be applied. e.g.

    const { data } = await entity.query
      .byIndex({ entityId: id })
      .where((attr, { eq }) =>
        someValue == null
          ? ""
          : eq(attr.someValue, someValue),
      )
      .go()

This works in practice (and is particularly helpful when using Electro to query in response to a GET request with optional query string parameters [e.g. my.rest.api/entity/<id>?someValue=x]), and the source for where looks like this is explicitly supported and not unhandled behavior, but wanted to confirm to be sure.

tywalch commented 3 weeks ago

Thanks @raryanpur 👋

You are correct that this fully supported behavior! The cool thing about using where is that the string returned from that query is actually the string that gets used in the FilterExpression. This is intentional so folks can have even more control over how their filter expressions are written. You could even do something like this:

 const { data } = await entity.query
      .byIndex({ entityId: id })
      .where((a, { value }) =>
        someValue == null
          ? ""
          : `somevalue = ${value(a.someValue, someValue)}`,
      )
      .go()
raryanpur commented 3 weeks ago

Great, thanks @tywalch !