How To GraphQL 实战:使用 graphql-ruby 在 Rails 中实现 Mutations(CreateLink 篇)

原创2026-09-24 18:22:541,680 阅读

How To GraphQL 实战:使用 graphql-ruby 在 Rails 中实现 Mutations(CreateLink 篇)

本篇文章聚焦 How To GraphQL 仓库 中 Ruby / Rails 后端教程的 Mutations 章节,讲解如何在 graphql-ruby 中实现写操作。教程目标是用 Ruby on Rails 搭建一个 Hackernews 克隆的后端(显示链接列表、用户注册登录、创建链接、投票),其中"创建链接"正是你将要实现的第一个 Mutation。读完本文,你将掌握 Mutation 根类型的结构、GraphQL::Schema::Mutation 类的编写方法、带参数的 Resolver 实现、在 GraphiQL Playground 中验证以及用 Rails 单元测试守护 Resolver 的全套流程。

从查询到变更:认识 Mutation 根类型

在 GraphQL 中,读操作(queries)和写操作(mutations)是分开定义的。查询从根类型 Query 开始,而所有变更则从一个根类型 Mutation 开始——这是 GraphQL 规范约定好的执行入口。

设置 Mutation 的过程和设置查询几乎一样简单:定义类型 → 实现 resolver(解析函数)→ 注册到 schema。

当你执行 rails generate graphql:install 时,graphql-ruby 会自动生成根类型文件 app/graphql/types/mutation_type.rb,初始内容是一个占位实现:

module Types
  class MutationType < BaseObject
    # TODO: remove me
    field :test_field, String, null: false,
      description: "An example field added by the generator"
    def test_field
      "Hello World"
    end
  end
end

这个 MutationType 是所有 GraphQL mutation 的占位容器。生成器特意内置了一个名为 testField 的假字段,目的是保证项目首次启动时 schema 不会为空、避免运行报错。一旦你添加了自己的 mutation,就可以安全地删除它。

注意命名习惯:Ruby 源码中的 test_field 在 GraphQL schema 中会自动 camelCase 化为 testField,create_link 则对应 createLink。graphql-ruby 默认启用这一命名转换,前端调用时无需关心下划线命名。

在 Schema 中暴露 Mutation 类型

MutationType 会被自动挂载到应用的 schema 中。教程的 app/graphql/graphql_tutorial_schema.rb 展示了这一点:

class GraphqlTutorialSchema < GraphQL::Schema
  mutation Types::MutationType
  query Types::QueryType
end

GraphQL::Schema 同时声明了 mutation 与 query 两个根类型,这意味着前端发送的任何 mutation 请求都会路由到 MutationType 下定义的字段,而查询请求则路由到 QueryType(对应教程前一章实现的 allLinks 查询,参见 Queries 章节)。

用 Mutation 类编写带参数的 Resolver

在 graphql-ruby 1.x 中,官方推荐的 mutation 实现方式是使用 Mutation class(继承自 GraphQL::Schema::Mutation)。它把参数声明、返回类型和 resolve 逻辑封装在一个类里,便于复用与单元测试。

第一步:创建 BaseMutation 基类

新建文件 app/graphql/mutations/base_mutation.rb,作为所有 mutation 的父类,集中放置公共工具:

module Mutations
  # This class is used as a parent for all mutations, and it is the place to have common utilities
  class BaseMutation < GraphQL::Schema::Mutation
    null false
  end
end

null false 表示该 mutation 的返回结果不可为空(即执行失败时不应返回 null,通常配合返回类型使用)。后续教程中的 CreateUser、SignInUser(见 Authentication 章节)都会继承这个基类。

第二步:实现 CreateLink mutation

新建文件 app/graphql/mutations/create_link.rb:

module Mutations
  class CreateLink < BaseMutation
    # arguments passed to the `resolve` method
    argument :description, String, required: true
    argument :url, String, required: true

    # return type from the mutation
    type Types::LinkType

    def resolve(description: nil, url: nil)
      Link.create!(
        description: description,
        url: url,
      )
    end
  end
end

逐行拆解这段核心代码:

  • argument :description, String, required: true:声明 mutation 的输入参数。:description 和 :url 都是必填的字符串参数。若客户端未传参,graphql-ruby 会在执行前直接返回参数校验错误,而不进入 resolve。
  • type Types::LinkType:声明 mutation 的返回类型。这里返回的是教程 Queries 章节 中生成的 LinkType(包含 id、url、description 三个非空字段),因此客户端可以在 mutation 请求中嵌套选择要返回的字段。
  • def resolve(description: nil, url: nil):mutation 的核心逻辑,即 resolver。argument 声明的参数会以 Ruby 关键字参数的形式注入 resolve。
  • Link.create!:使用带 ! 的 ActiveRecord 方法创建记录。与 Link.create 不同,create! 在数据校验失败时会抛出异常(如 ActiveRecord::RecordInvalid),便于后续错误处理。

从源码结构看,CreateLink 是典型的"薄 resolver":它不包含业务规则,只负责把参数透传给模型层。这正是教程提倡的 schema-driven 开发——schema 是前后端契约,resolver 只做数据搬移。

第三步:把 mutation 注册到 MutationType

打开 app/graphql/types/mutation_type.rb,删掉占位的 test_field,替换为:

module Types
  class MutationType < BaseObject
    field :create_link, mutation: Mutations::CreateLink
  end
end

这里用 field :create_link, mutation: Mutations::CreateLink 把 mutation 类挂载为 MutationType 上的一个字段。字段名 :create_link 会在 schema 中暴露为 createLink。以后每新增一个 mutation(如 create_user、signin_user),都按同样的方式追加一行 field 声明即可。

在 GraphiQL Playground 中验证 Mutation

配置好之后,重启 Rails 服务器(新增了 gem 或 schema 变更后建议重启),然后打开浏览器访问 http://localhost:3000/graphiql(GraphiQL 已在 rails generate graphql:install 时集成,需在 app/assets/config/manifest.js 中加入 //= link graphiql/rails/application.css 与 //= link graphiql/rails/application.js 完成资产预编译)。

在左侧编辑器中输入:

mutation {
  createLink(
    description: "The Best Query Language"
    url: "http://graphql.org/"
  ) {
    id
    url
    description
  }
}

点击 Play 按钮,右侧会返回类似下面的结果:

{
  "data": {
    "createLink": {
      "id": "1",
      "url": "http://graphql.org/",
      "description": "The Best Query Language"
    }
  }
}

此时用 Queries 章节的 allLinks 查询,即可看到刚创建的链接出现在列表中,说明数据已成功写入数据库。教程 meta/structure/ruby.md 中给出的完整 Mutation schema 也印证了这一点——createLink(description: String!, url: String!, postedById: ID): Link 正是这里实现字段在完整 schema 中的最终形态。

用单元测试守护 Resolver

教程强调:在 Ruby 中为 resolver 对象编写单元测试是一种良好实践。由于 mutation 是独立类,测试起来非常直接。新建文件 test/graphql/mutations/create_link_test.rb:

require 'test_helper'

class Mutations::CreateLinkTest < ActiveSupport::TestCase
  def perform(user: nil, **args)
    Mutations::CreateLink.new(object: nil, field: nil, context: {}).resolve(**args)
  end

  test 'create a new link' do
    link = perform(
      url: 'http://example.com',
      description: 'description',
    )

    assert link.persisted?
    assert_equal link.description, 'description'
    assert_equal link.url, 'http://example.com'
  end
end

测试的关键技巧:

  • 直接实例化 mutation 类:Mutations::CreateLink.new(object: nil, field: nil, context: {}) 绕过了 HTTP 层,把 mutation 当作普通 Ruby 对象调用 resolve,速度快且不依赖网络。
  • perform 辅助方法:封装"构造实例 + 传参 + 调用 resolve"的重复流程,让每个测试用例只关注业务断言。
  • 断言三连:link.persisted? 验证记录确实写入数据库,assert_equal 验证写入的字段值与入参一致。

运行测试:

bundle exec rails test

教程后续章节对 CreateUser、SignInUser 的测试(见 Authentication 章节)采用了完全相同的模式,包括失败分支(无凭据、邮箱错误、密码错误返回 nil)的断言,可见这套"实例化 resolver + 断言"的测试范式贯穿整个教程。

纵深:Mutation 的演进与最佳实践

CreateLink 只是第一个 mutation,教程后续章节在它的基础上展示了 mutation 的三种典型演进,这正是理解本节的延伸价值:

  1. 通过 context 访问请求级数据:在 Authentication 章节 中,GraphqlController 会把 current_user 塞进 context,CreateLink 的 resolve 相应升级为 user: context[:current_user],把每条链接关联到发帖用户。这解释了 BaseMutation 的 null false 与 context 机制的实际用途——mutation 不是孤立的,它可以感知"谁在发请求"。

  2. 复用输入类型:CreateUser 在 mutation 类内部嵌套定义了 AuthProviderSignupData 输入类型,并复用了外部的 AuthProviderCredentialsInput,展示了当参数变复杂时如何组织 schema,而不是无限堆叠 argument。

  3. 错误处理:在 Error Handling 章节 中,模型层加上 validates :url, presence: true, length: { minimum: 5 } 后,CreateLink 的 resolve 用 rescue ActiveRecord::RecordInvalid 捕获校验异常并转为 GraphQL::ExecutionError,把错误以 GraphQL 标准错误格式返回给客户端——完整的 create_link.rb 最终形态如下:

module Mutations
  class CreateLink < BaseMutation
    argument :description, String, required: true
    argument :url, String, required: true

    type Types::LinkType

    def resolve(description: nil, url: nil)
      Link.create!(
        description: description,
        url: url,
        user: context[:current_user]
      )
    rescue ActiveRecord::RecordInvalid => e
      GraphQL::ExecutionError.new("Invalid input: #{e.record.errors.full_messages.join(', ')}")
    end
  end
end

可见,一个看似简单的 CreateLink,在完整的教程体系中逐步长出了参数校验、身份关联与错误处理能力,这正是 schema-driven 开发"以小步迭代驱动演进"的体现。

小结

在 graphql-ruby 中实现 mutation 的完整套路可以概括为四步:用 GraphQL::Schema::Mutation 子类声明参数与返回类型、在 resolve 中写数据访问逻辑、在 MutationType 中通过 field :xxx, mutation: Xxx 注册、最后用 GraphiQL 与单元测试双重验证。掌握 CreateLink 之后,教程中的 CreateUser、SignInUser 乃至投票类 mutation 都是同一模式的复用。你可以继续阅读 Authentication 章节 学习 mutation 与用户体系、context 的结合,或通过 仓库首页 对照其他后端技术栈(如 graphql-go、graphql-python)中同一 mutation 的不同实现方式。

登录后查看全文
howtographql