我已经读完了在 Elixir 中使用 Absinthe (Pragprog) 制作的 Craft GraphQL APIs,我正在尝试扩展 item_controller.ex 以允许“菜单项”编辑。
我在控制器中做了这些功能:
@graphql """
query ($id: ID!) {
menu_item(id: $id) @put {
name
description
}
}
"""
def edit(conn, %{data: %{menu_item: item}}) do
render(conn, "edit.html", item: item)
end
@graphql """
mutation UpdateMenuItem($id: ID!, $input: MenuItemInput!) {
updatedMenuItem: updateMenuItem(id: $id, input: $input) {
errors { key message }
menuItem {
name
description
price
}
}
}
"""
def update(conn, %{data: %{menu_item: _}}) do
conn
|> redirect(to: "/admin/items")
end
def update(conn, %{errors: errors}) do
conn
|> put_flash(:info, Enum.reduce(errors, "", fn e, a -> a <> e.message end))
|> redirect(to: "/admin/items")
end
这是我的edit.html.eex:
<%= render "form.html",
Map.put(assigns, :action,
Routes.item_path(@conn, :update, @item)) %>
这是我的 form.html.eex:
<%= form_for @conn, @action, [method: :put, as: :input], fn f -> %>
<div class="form-group">
<label for="description">Description</label>
<input type="string" id="description" as="description" name="description" value="<%= @item.description %>"/>
<label for="price">price</label>
<input type="string" id="price" name="price" value="<%= @item.price %>"/>
<label for="name">name</label>
<input type="string" id="name" name="name" value="<%= @item.name %>"/>
<label for="category">category</label>
<input type="string" id="category" name="categoryId" value="<%= @item.category_id %>"/>
</div>
<%= submit "Update", class: "btn btn-primary" %>
<% end %>
但是当我提交表单时出现错误。这是错误:
In argument "input": Expected type "MenuItemInput!", found null.
Variable "input": Expected non-null, found null.
对于我,这说得通。例如,我可以将 form.html.eex 中任何输入元素的 name 属性更改为“input”,然后我会得到一个不同的错误:
Argument "input" has invalid value $input.
再说一次,这对我来说很有意义。$input 参数不是 MenuItemInput 变量。
所以我希望通过两种可能的方式来解决这个问题:
在 form.html.eex 中,我创建了一个“表单中的表单”,以便它有一个“输入”字段,而该字段又包含多个字段。也许是“输入组”?
在 item_controller 中,我将变量传递给 @graphql 模块属性。我根本不知道该怎么做。我尝试了很多奇怪的语法,因为我什至找不到内联变量的 SDL 示例。
非常欢迎任何建议/批评/想法。我确信其他人已经这样做了,因为在完成这本书之后尝试似乎是一件很自然的事情。