DRY Absinthe fields - is there an idiomatic way to reduce duplication?

I’m working with a legacy database that has a LOT of columns. In many cases I have a large object:

object :company do
  field :id, non_null(:id)
  field :name, non_null(:string)
  ... lots of optional fields ...
  field :created_at, :naive_datetime
  field :updated_at, :naive_datetime
  field :deleted_at, :naive_datetime
end

And then both a create and update input object:

input_object :create_company_params do
  field :name, non_null(:string)
  ... lots of optional fields ...
end

input_object :update_company_params do
  field :name, :string
  ... the rest of the optional fields ...
end

Is there an idiomatic way to reduce all this duplication? It feels even worse since the Ecto models for these look almost identical as well. My macro skills aren’t great but I was thinking I could generate most of this just based on some lists of @required and @optional. But as these fields are already a DSL it’s a bit over my head. Is that even the way to go?
Am I better off “just dealing with it” ?

You could absolutely code-gen this stuff, but you need to ask yourself if you should.

In my experience, the end result of my graphql schema is nearly never a mirror of my relational database schema.

If you do go the code-gen route, build in an easy to access escape hatch. You’ll need it.

1 Like

Thanks! With most code, especially elixir, I tend to assume I’m doing something wrong if there’s a lot of code duplication. Some re-assurance this is fine / my best-bet is pretty much all I was looking for.

1 Like

I really want to +1 @factoryd here, there’s a great quote by Sandi Metz, “duplication is cheaper than the wrong abstraction.”

I’m also a big believer in modeling your domain, not your database in GraphQL. My team gives schema design guidance to dozens of other teams within our company and that’s one of the first things we talk about.

So, in summary, +1 to not fearing duplication (you can always unify later!) and +1 to not tying your schema to the way your data is modeled in your database! Do what’s best for for the API

4 Likes

Very well put. I also think that this SE Daily podcast with a github dev talking graphql api design is a must to start someone down the path of asking the right questions.

1 Like