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上的链接
传送门

目录
相关文章
|
3月前
|
API 开发者 网络架构
从REST到GraphQL:探究GraphQL的概念与实践
RESTful API曾经是互联网应用程序的主流,但它也存在着一些限制。随着GraphQL的出现,开发者们可以更加自由地定义和查询API,提高了应用程序的灵活性和可扩展性。本文将深入探讨GraphQL的概念和实践,并介绍如何在应用程序中使用GraphQL。
22 6
|
9月前
|
JSON 前端开发 API
如何使用GraphQL进行前端数据交互
如何使用GraphQL进行前端数据交互
|
4月前
|
API
GraphQL
GraphQL
31 0
|
7月前
|
JavaScript Go
搭建GraphQL服务
搭建GraphQL服务
41 0
|
8月前
|
存储 Java API
大厂都在实践的GraphQL,你了解吗?
大厂都在实践的GraphQL,你了解吗?
127 0
GraphQL 是干什么的?底层原理是什么?
GraphQL 是干什么的?底层原理是什么?
329 0
|
SQL 前端开发 JavaScript
关于graphql快速入门
关于graphql快速入门
151 0
|
JSON 前端开发 NoSQL
GraphQL 从入门到实践
本文首先介绍了 GraphQL,再通过 MongoDB + graphql + graph-pack 的组合实战应用 GraphQL,详细阐述如何使用 GraphQL 来进行增删改查和数据订阅推送,并附有使用示例,边用边学印象深刻~ 如果希望将 GraphQL 应用到前后端分离的生产环境,请期待后续文章。 本文实例代码:Github 感兴趣的同学可以加文末的微信群,一起讨论吧~
GraphQL 从入门到实践
|
JavaScript 前端开发 API
|
JSON Unix API
graphql学习(五)
今天给之前的demo增加登录验证. 现在验证流行使用JWT(JSON web tokens),我们也选择用github.com/dgrijalva/jwt-go. 还是从models开始,增加user.
1129 0
graphql学习(五)