graphql学习(三)

简介:

GraphQL中有三种操作类型,分别是query、mutation、subscription:

  • query: 获取数据,对应CRUD里的R;
  • mutation: 操作数据,对应CRUD里的CUD(创建,更新,删除);
  • subscription: 消息订阅,数据更改时进行消息推送.

之前已经学习了query, 这一篇重点学习mutation.

首先,修改models/article.go文件,增加相应的CUD函数:

// Create a new article with the title and content provided
func CreateNewArticle(title, content string) (*Article, error) {
    // Set the ID of a new article to one more than the number of articles
    a := Article{ID: len(articleList) + 1, Title: title, Content: content}

    // Add the article to the list of articles
    articleList = append(articleList, a)

    return &a, nil
}

// Update a article
func UpdateArticle(id int, title, content string) (*Article, error) {
    a, err := GetArticleByID(id)
    if err != nil {
        return nil, err
    }

    if title != "" {
        a.Title = title
    }
    if content != "" {
        a.Content = content
    }

    return a, nil
}

// Delete a article
func DeleteArticle(id int) error {
    for k, a := range articleList {
        if a.ID == id {
            articleList = append(articleList[:k], articleList[k+1:]...)
            return nil
        }
    }
    return errors.New("Article not found")
}

然后是修改schema/article.go,增加相应的mutation:

// 定义mutation,增删改操作
// add
var addArticle = graphql.Field{
    Name:        "新文章",
    Description: "增加新文章",
    Type:        articleType,
    Args: graphql.FieldConfigArgument{
        "title": &graphql.ArgumentConfig{
            Type: graphql.String,
        },
        "content": &graphql.ArgumentConfig{
            Type: graphql.String,
        },
    },
    Resolve: func(p graphql.ResolveParams) (result interface{}, err error) {
        title, _ := p.Args["title"].(string)
        content, _ := p.Args["content"].(string)

        result, err = models.CreateNewArticle(title, content)
        if err != nil {
            return nil, err
        }

        return result, nil
    },
}

// update
var updateArticle = graphql.Field{
    Name:        "编辑文章",
    Description: "编辑文章",
    Type:        articleType,
    Args: graphql.FieldConfigArgument{
        "id": &graphql.ArgumentConfig{
            Type: graphql.Int,
        },
        "title": &graphql.ArgumentConfig{
            Type: graphql.String,
        },
        "content": &graphql.ArgumentConfig{
            Type: graphql.String,
        },
    },
    Resolve: func(p graphql.ResolveParams) (result interface{}, err error) {
        id, _ := p.Args["id"].(int)
        title, _ := p.Args["title"].(string)
        content, _ := p.Args["content"].(string)

        result, err = models.UpdateArticle(id, title, content)
        if err != nil {
            return nil, err
        }

        return result, nil
    },
}

// delete
var deleteArticle = graphql.Field{
    Name:        "删除文章",
    Description: "删除指定Id的文章",
    Type:        articleType,
    Args: graphql.FieldConfigArgument{
        "id": &graphql.ArgumentConfig{
            Type: graphql.Int,
        },
    },
    Resolve: func(p graphql.ResolveParams) (result interface{}, err error) {
        id, _ := p.Args["id"].(int)

        // 查找文章是否存在
        result, err = models.GetArticleByID(id)
        if err != nil {
            return nil, err
        }

        if err = models.DeleteArticle(id); err != nil {
            return nil, err
        }

        return result, nil
    },
}

// 定义增删改方法
var mutationType = graphql.NewObject(graphql.ObjectConfig{
    Name:        "mutation",
    Description: "增删改",
    Fields: graphql.Fields{
        "add":    &addArticle,
        "update": &updateArticle,
        "delete": &deleteArticle,
    },
})

// 定义Schema用于http handler处理
var Schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query:    rootQuery,
    Mutation: mutationType,   // 这里不能是nil了,对应前面的定义
})

测试结果话不多说,上图:
新增文章:
image

编辑文章
image

删除文章
image

代码在github上的链接
传送门

目录
相关文章
|
8月前
|
前端开发 数据管理 API
探究GraphQL在前端开发中的实际应用
在如今越来越复杂的前端应用程序中,数据管理变得更加困难,因此GraphQL成为了越来越受欢迎的解决方案。本文将介绍GraphQL在前端开发中的应用,以及它对开发过程所带来的好处。
|
1月前
|
缓存 API C#
C# 一分钟浅谈:GraphQL 与 REST 比较
本文对比了REST和GraphQL两种流行的API设计风格,从概念、优缺点及C#实现角度进行了详细分析,并提供了代码示例。REST以其简单易懂和无状态特性著称,而GraphQL则通过精确获取和单次请求的优势,提高了数据获取效率。文章还讨论了常见问题与解决策略,帮助开发者根据实际需求选择合适的API设计风格。
61 10
|
8月前
|
SQL 前端开发 API
前端需要学GraphQL 吗?
前端需要学GraphQL 吗?
80 2
|
JSON 前端开发 API
如何使用GraphQL进行前端数据交互
如何使用GraphQL进行前端数据交互
|
8月前
|
API 开发者 网络架构
从REST到GraphQL:探究GraphQL的概念与实践
RESTful API曾经是互联网应用程序的主流,但它也存在着一些限制。随着GraphQL的出现,开发者们可以更加自由地定义和查询API,提高了应用程序的灵活性和可扩展性。本文将深入探讨GraphQL的概念和实践,并介绍如何在应用程序中使用GraphQL。
49 6
|
8月前
|
前端开发 API UED
深入浅出GraphQL:理解与实践
本文将以清晰易懂的方式介绍GraphQL的概念及其实际应用。通过对比RESTful API和GraphQL的特点,阐述GraphQL在数据查询和交互方面的优势。同时,将探讨GraphQL在现代软件开发中的实际应用,并提供一些最佳实践指南。无论您是初学者还是有经验的开发者,都能从本文中获得有益的启发和指导。
|
API
GraphQL
GraphQL
73 0
|
JavaScript Go
搭建GraphQL服务
搭建GraphQL服务
94 0
|
存储 Java API
大厂都在实践的GraphQL,你了解吗?
大厂都在实践的GraphQL,你了解吗?
197 0
GraphQL 是干什么的?底层原理是什么?
GraphQL 是干什么的?底层原理是什么?
428 0