absinthe-graphql / absinthe_ecto

DEPRECATED: Use dataloader
MIT License
130 stars 36 forks source link

Implements query fun #11

Closed tlvenn closed 7 years ago

tlvenn commented 7 years ago

This implements assoc/2 so that you can pass an optional function to further filter / order the query:

field :comments, list_of(:comment) do
  arg :starting_from, :number
  resolve: assoc(:comments, fn query, args, ctx ->
      query
      |> where([c], c.created_at > Map.get(args, :starting_from))
      |> order_by([desc: :popularity])
    end)
end

ctx is the Absinthe context, i find it useful to map on to the logged user id and the like to contextualize some fields for the current user:

field :my_comments, list_of(:comment) do
  resolve: assoc(:comments, fn query, _args, %{user_id: user_id} ->
      query
      |> where(author_id: ^user_id)
      |> order_by([desc: :popularity])
    end)
end

@benwilson512 let me know if this looks ok, I will need some guidance on how to best deal with default value for the query_fun and the macro/fun assoc.

I also need to add proper documentation.

tlvenn commented 7 years ago

@benwilson512 friendly reminder I need your inputs to continue on this PR. Many thanks in advance.

tlvenn commented 7 years ago

@benwilson512 any chance you can jumpn in plz ?

benwilson512 commented 7 years ago

This is really great, thank you!

ssomnoremac commented 7 years ago

a bit of an ecto noob here but I'm trying to join to filter on an associated table field sm.state_id working with this PR. It doesn't seem to work though

field :applications, list_of(:application), resolve: assoc(:applications, fn query, _, _ ->
          query
          |> join(:inner, [app], sm in assoc(app, :sm))
          |> where([_, sm], sm.state_id < 2800)
        end)

I get this

web/schema/types.ex:109: undefined function app/0
benwilson512 commented 7 years ago

did you import Ecto.Query earlier in that module?

ssomnoremac commented 7 years ago

Ah, that was it! I was doing only importing join and where. Thanks yet again!