FQL Fauna Function - Query Indexed Document Data Given Conditions

148 Views Asked by At

I have a collection of shifts for employees, data (trimmed out some details, but this is the structure for start/end times) looks like this:

{
  "ref": Ref(Collection("shifts"), "123451234512345123"),
  "ts": 1234567891012345,
  "data": {
    "id": 1,
    "start": {
      "time": 1659279600000
    },
    "end": {
      "time": 1659283200000
    },
    "location": "12341234-abcd-1234-cdef-123412341234"
  }
}

I have an index that will query return an array of shifts_by_location in this format: ["id", "startTime", "endTime"] ...

Now I want to create a user-defined-function to filter these results "start" and "end" times to fall in between given dayStart and dayEnd times to get shifts by date, hoping to get some FQL assistance here, thanks!

Here's my broken attempt:

Query(
  Lambda(
    ["location_id", "dayStart", "dayEnd"], // example: ["124-abd-134", 165996000, 165922000]
    Map(
      Paginate(Match(Index("shifts_by_location"), Var("location_id"))),
      Lambda(["id", "startTime", "endTime"],
        If(
          And(
            GTE(Var("startTime"), Var("dayStart")), // GOAL -> shift starts after 8am on given day
            LTE(Var("endTime"), Var("dayEnd")) // GOAL -> shift ends before 5pm on given day
          ),
          Get(Var("shift")) // GOAL -> return shift for given day
        )
      )
    )
  )
)
1

There are 1 best solutions below

0
RADesai On

Found a working solution with this query, the biggest fix was really just to use a filter over the map, which seems obvious in hindsight:

Query(
  Lambda(
    ["location_id", "dayStart", "dayEnd"],
    Filter(
      Paginate(Match(Index("shifts_by_location"), Var("location_id"))),
      Lambda(
        ["start", "end", "id"],
        And(GTE(Var("start"), Var("dayStart")), LTE(Var("end"), Var("dayEnd")))
      )
    )
  )
)