What's the effective way to get current field in the resolver function?

This is my ecto schema:

  schema "card_comments" do
    field :content, :string
    field :status, :integer, default: 1

    belongs_to(:card, OmcService.Core.Card)
    belongs_to(:from_user, OmcService.Accounts.User, foreign_key: :from_user_id)
    belongs_to(:to_user, OmcService.Accounts.User, foreign_key: :to_user_id)


I have to fetch user dependent on field(:from_user or :to_user) and %CardComment{}, So I write this object:

  object :card_comment do
    field :content, :string

    field :to_user, :user do
      resolve &Learning.user_for_comment/3

    field :from_user, :user do
      resolve &Learning.user_for_comment/3

and this resolver function:

  def user_for_comment(comment, _, info) do
    field = info.definition.schema_node.identifier

    case field do
      :to_user ->
        user_id = Map.get(comment, :to_user_id)
        {:ok, OmcService.Repo.get!(User, user_id)}

      :from_user ->
        user_id = Map.get(comment, :from_user_id)
        {:ok, OmcService.Repo.get!(User, user_id)}

      _ ->
        {:ok, nil}

Is there a more effective way to do this except info.definition.schema_node.identifier

Is there another way to do that?

I would use 2 resolver functions instead of 1.



Aside from that I suggest you take a look at https://hex.pm/packages/dataloader which might speeds things up a bit.

1 Like

You could also hook it up to Dataloader and then it’ll just use the ecto associations. Plus that way it’ll be batch loaded.

1 Like

Ok,thanks,I will try dataloader later. But why not have a function that get current field just like get child with https://hexdocs.pm/absinthe/Absinthe.Resolution.html#project/2

PR welcome :slight_smile: