ASP.NET Core中使用GraphQL - 第七章 Mutation

ASP.NET Core中使用GraphQL - 目錄html


在前面幾篇中,咱們已經介紹瞭如何使用GraphQL中的query字段獲取數據。那麼如何使用GraphQL進行數據的添加,刪除,修改操做呢?這裏咱們須要引入GraphQL中的mutationgit

咱們繼續編寫新代碼以前,咱們須要先整理一下當前的項目代碼。這裏咱們將HelloWorldQuery類更名爲InventoryQuery類, 並將HelloWorldSchema類更名爲InventorySchema。而後咱們將hellohowdy兩個字段移除掉。github

在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。其代碼以下:c#

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的方法簽名,在添加完成以後,咱們將添加成功的貨物記錄返回了。所以咱們能夠查詢新添加對象的內嵌字段async

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.函數

和查詢同樣,若是mutation字段返回一個對象類型,你就能夠查詢它的內嵌字段。這對於獲取一個更新後對象的新狀態很是有用。fetch

在咱們運行程序以前,咱們還如要在控制反轉容器中註冊ItemInputTypeInventoryMutation3d

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
  }
}

這段代碼的意思是,咱們將調用createItemmutation, 將item保存到數據庫,並會返回新增item的titlebarcode屬性。

固然你也能夠把添加的item對象放到Query Variables窗口中, 獲得的結果是同樣的

本文源代碼: https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20VII

相關文章
相關標籤/搜索