How to represent an embedded schema in AshGraphql

moxley
2023-02-21

moxley:

I have an existing Ecto schema that has an embedded_field, which itself is backed by an Ecto schema. How do I use the attributes DSL to expose this field in my AshGraphql query?

Here’s the field in Ecto: embeds_one :details, Details

I tried this in the Ash attributes: attribute :details, :map , but the GraphQL response had this error: Field "details" must not have a selection since type "JsonString" has no subfields.

ZachDaniel:

Ash has embedded resources, that function in much the same way

ZachDaniel:

defmodule Foo do
  use Ash.Resource,
    data_layer: :embedded,
    extensions: [AshGraphql.Resource]

  graphql do
    type :foo
  end

  attributes do
    attribute :stuff, :string
  end
end

ZachDaniel:

That will derive a type for your embedded resource, and when you use that in a resource, i.e

attribute :detauls, Foo

it will assume the proper type

moxley:

Ah, okay. Thank you.

How do I know when to use attribute for this case, and not has_one ?

moxley:

In Ecto, it would be an embeds_one

moxley:

Does Ash use attribute in the cases where Ecto uses embeds_* ?

ZachDaniel:

Yes, in ash there is no embeds concept

ZachDaniel:

Just resources that can behave the same as a type

ZachDaniel:

so data_layer: :embedded just means “this is an Ash.Type resource”

ZachDaniel:

and so you can use it in attributes

moxley:

Perfect, thanks!