I’ve been looking at the Absinthe documentation and there is an example for creating resources (https://hexdocs.pm/absinthe/complex-arguments.html#content) but I’d like to see an example of updating only a specific column on a resource.
Using the example from the docs (on this page: https://hexdocs.pm/absinthe/mutations.html#content) the code is as follows:
# schema
mutation do
@desc "Create a post"
field :create_post, type: :post do
arg :title, non_null(:string)
arg :body, non_null(:string)
arg :published_at, :naive_datetime
resolve &Resolvers.Content.create_post/3
end
end
# resolvers
def create_post(_parent, args, %{context: %{current_user: user}}) do
Blog.Content.create_post(user, args)
end
Creating the update I think would be fairly straightforward. Something like:
@desc "Update a post"
field :update_post, type: :post do
arg :id, :id
arg :title, non_null(:string)
arg :body, non_null(:string)
arg :published_at, :naive_datetime
resolve &Resolvers.Content.update_post/3
end
def update_post(_parent, %{id: post_id} = args, %{context: %{current_user: user}}) do
post = Blog.Content.get_post!(post_id)
Blog.Content.update_post(post, args)
end
The issue I have run into is that GraphQL expects all the fields to be sent. So I’d have to send title
, body
, and published_at
even though I may only want to update the title
.
What’s the idiomatic Absinthe way to address this?
Thank you
(Please keep in mind this is just the example from the guides so I haven’t tested that it works. The code I’m working with is larger/more distracting so I thought I’d go with what’s in the guides.)
Update:
I made a few modifications and the following seems to work:
@desc "Update a post"
field :update_post, type: :post do
arg :id, :id
arg :post, :post_input
resolve &Resolvers.Content.update_post/3
end
input_object :post_input do
field :title, :string
field :body, :string
field :published_at, :naive_datetime
end
def update_post(_parent, args, %{context: %{current_user: _current_user}}) do
post_params = args.post
post_id = args.id
post = Blog.Content.get_post!(post_id)
Blog.Content.update_post(post, post_params)
end
Is this correct?