Hello, everyone, I have some code like this:
def update_package(_, %{input: params}, _) do
p = Repo.get(Core.Package, params.id)
case p do
%Core.Package{} = p ->
with {:ok, package} <- Core.update_package(p, params) do
{:ok, %{package: package}}
end
_ ->
{:error, "Package by id #{params.id} do not exist."}
end
end
def delete_package(_, %{input: params}, _) do
p = Repo.get(Core.Package, params.id)
case p do
%Core.Package{} = p ->
with {:ok, package} <- Core.delete_package(p) do
{:ok, %{package: package}}
end
_ ->
{:error, "Package by id #{params.id} do not exist."}
end
end
I have some entity: package, card and others, every time when I write a mutation resolver function, I have to write
_ ->
{:error, "Package by id #{params.id} do not exist."}
end
I hate this duplicated.
How do I use Absinthe.Middleware
to do the same things like phoenix’s action_fallback
to catch the not_found error
I have read the craft-graphql book, the middleware example shows how to convert errors, I got that, but I don’t know to use it to catch exception.
I expect I can use a middleware to wrap the mutation, then I can write code like:
def update_package(_, %{input: params}, _) do
p = Repo.get!(Core.Package, params.id) # use get! to raise a exception
with {:ok, package} <- Core.update_package(p, params) do
{:ok, %{package: package}}
end
end
Do you have some idea? Thanks!