Absinthe computed properties?

I’m not sure if computed properties is the right expression but I have a query regarding Absinthe that has me scratching my head a bit.

With some data that looks something like this:

defmodule ContrivedApp.Person do
  use Ecto.Schema

  schema "assets" do
    field :first_name, :string
    field :last_name, :string
    timestamps()
  end
end

I want to expose a computed value in what GraphQL sends to the client i.e. fullName

query getPeople {
  people {
    fullName
  }
}

Where would I go about putting this though? I’ve been hunting around and I can’t find an obvious answer. It seems like type definitions map to the schema, but I can’t spot a good opportunity to do something more than that with them. I’m sure I’m missing something.

So far it’s not a problem as everything has been quite simple to do on the Javascript end but I can’t help thinking there must be a better way.

1 Like

Fields can have their own resolve functions so you could try:

  object :person do
    field :full_name, :string do
      resolve fn person, _, _ ->
        {:ok, "#{person.first_name} #{person.last_name}"}
      end
    end
  end
query do
   field :people, type: list_of(:person) do
      resolve &PersonResolver.list/2
   end
end

docs for that:

https://hexdocs.pm/absinthe/Absinthe.Schema.Notation.html#resolve/1
3 artity function

Easy to miss, most of the examples I’ve seen use 2 artity resolve

1 Like

Awesome! Thank you, I’ll give that a go.

I did completely miss that hunting around the docs.

Ah yeah the 3 arity version could be better documented. We have some planned improvements on the guides after the book is out.

Probably the main thing to note is that there’s nothing special about the fields on the query object, they work exactly the same way as fields on any other object. We can add resolvers to top level fields on the query object but we can also add resolvers to any other field on any other object. In fact if you don’t add one there’s one added by default, which is the only reason they return any value at all.