在前面几篇中, 我们已经介绍了如何使用 GraphQL 中的 query 字段获取数据. 那么如何使用 GraphQL 进行数据的添加, 删除, 修改操作呢? 这里我们需要引入 GraphQL 中的 mutation.
我们继续编写新代码之前, 我们需要先整理一下当前的项目代码. 这里我们将 HelloWorldQuery 类改名为 InventoryQuery 类, 并将 HelloWorldSchema 类改名为 InventorySchema. 然后我们将 hello 和 howdy 两个字段移除掉.
在 GraphQL 中, 一个 Mutation 类型也是继承自 ObjectGraphType 类. 在以下代码中, createItem 字段在服务器端创建了一个货物并返回了它的内容.
- InventoryMutation
- public class InventoryMutation : ObjectGraphType
- {
- public InventoryMutation(IDataStore dataStore)
- {
- Field<ItemType>(
- "createItem",
- arguments: new QueryArguments(
- new QueryArgument<NonNullGraphType<ItemInputType>> { Name = "item" }
- ),
- resolve: context =>
- {
- var item = context.GetArgument<Item>("item");
- return dataStore.AddItem(item);
- });
- }
- }
以上代码中我们引入了一个新的 ItemInputType 类作为查询参数. 在第五章中, 我们已经创建过一个标量类型的参数. 但是针对复杂类型, 我们使用不同的方式. 因此, 这里我们创建了一个新的类 ItemInputType. 其代码如下:
- ItemInputType
- public class ItemInputType : InputObjectGraphType
- {
- public ItemInputType()
- {
- Name = "ItemInput";
- Field<NonNullGraphType<StringGraphType>>("barcode");
- Field<NonNullGraphType<StringGraphType>>("title");
- Field<NonNullGraphType<DecimalGraphType>>("sellingPrice");
- }
- }
为了将新的货物记录添加到数据库, 我们还需要修改 IDataStore 接口, 添加一个 AddItem 的方法, 并在 DataStore 类中实现它.
- IDataStore
- public interface IDataStore
- {
- IEnumerable<Item> GetItems();
- Item GetItemByBarcode(string barcode);
- Task<Item> AddItem(Item item);
- }
- DataStore
- public async Task<Item> AddItem(Item item)
- {
- var addedItem = await _context.Items.AddAsync(item);
- await _context.SaveChangesAsync();
- return addedItem.Entity;
- }
这里请注意 AddItem 的方法签名, 在添加完成之后, 我们将添加成功的货物记录返回了. 因此我们可以查询新添加对象的内嵌字段
Just like in queries, if the mutation field returns an object type, you can ask for nested fields. This can be useful for fetching the new state of an object after an update. - GraphQl Org. http://graphql.org/learn/queries/#mutations
和查询一样, 如果 mutation 字段返回一个对象类型, 你就可以查询它的内嵌字段. 这对于获取一个更新后对象的新状态非常有用.
在我们运行程序之前, 我们还如要在控制反转容器中注册 ItemInputType 和 InventoryMutation.
- Startup
- services.AddScoped<ItemInputType>();
- services.AddScoped<InventoryMutation>();
最后我们需要在 InventorySchema 的构造函数中, 注入 InventoryMutation
- InventorySchame
- public class InventorySchema : Schema
- {
- public InventorySchema(InventoryQuery query, InventoryMutation mutation)
- {
- Query = query;
- Mutation = mutation;
- }
- }
现在你可以运行程序了, 这里我们运行如下的 mutation
- mutation {
- createItem(item: {title: "GPU", barcode: "112", sellingPrice: 100}) {
- title
- barcode
- }
- }
这段代码的意思是, 我们将调用 createItem 的 mutation, 将 item 保存到数据库, 并会返回新增 item 的 title 和 barcode 属性.
当然你也可以把添加的 item 对象放到 Query Variables 窗口中, 得到的结果是一样的
本文源代码: https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part VII
来源: https://www.cnblogs.com/lwqlun/p/9943372.html