Francesco
How to handle Absinthe object data that's spread over multiple ecto schemas
Hello!
What’s the recommended best practice for dealing with the situation where the graphql object you want to return requires data that is spread over multiple DB tables and therefore schemas?
One option is just to get all the data I need from an ecto query, create a custom map and return that. However I found that sometimes returning structs and other times returning maps from my context methods makes downstream logic a little more cumbersome. For example I have the following absinthe object:
object :block do
field(:public_id, non_null(:string), name: "id")
field(:content, non_null(:json))
field :author, :user do
resolve(&ScribeWeb.Resolvers.Accounts.get_user/3)
end
end
The get_user resolver then pattern matches on the parent fields. If the parent had a user_id than I will fetch that user, otherwise I will fetch the user in the resolution context:
def get_user(%_{user_id: id}, _args, %{context: %{current_user: user}}) do
if user.id == id do
{:ok, user}
else
{:ok, Accounts.get_user(id)}
end
end
This pattern matches on a struct of any kind, but if I start returning maps than I need to account for that too by creating another function.
The other way I was thinking was to add an embedded schema and that I can use instead of a plain map. I don’t have any particular need for casting or validating this data though so it kind of feels like I’m using a struct for no real reason.
How has everyone else dealt with this?
First Post!
dimitarvp
If you just make this change:
- def get_user(%_{user_id: id}, _args, %{context: %{current_user: user}}) do
+ def get_user(%{user_id: id}, _args, %{context: %{current_user: user}}) do
Then your code will work just fine with both structs and arbitrary maps.
As for your original question I see no way out but use SQL JOINs (Ecto assocs). Embedded schema would work as well but it seriously depends if you want to do queries on those models or not. If you do, they shouldn’t be embedded (most of the time).
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









