GraphQL Preload 使用教程
项目介绍
GraphQL Preload 是一个为 graphql
gem 提供的 DSL,允许在 GraphQL 字段定义中预加载 ActiveRecord 关联。这个项目基于 @theorygeek 的一个 gist 开发,旨在提高性能并简化 GraphQL 查询的数据加载过程。
项目快速启动
安装
首先,将以下内容添加到你的应用的 Gemfile 中:
gem 'graphql-preload'
然后执行:
bundle install
或者手动安装:
gem install graphql-preload
配置
在你的 GraphQL 模式中启用预加载:
class MySchema < GraphQL::Schema
use GraphQL::Batch
enable_preloading
end
在定义字段时调用 preload
:
class PostType < GraphQL::Schema::Object
field :comments, [CommentType], null: false do
preload :comments
preload [:comments, :authors]
preload [:comments, { authors: [:followers, :posts] }]
end
def comments
object.comments
end
end
应用案例和最佳实践
预加载关联
假设你有一个 Post
模型,它有一个 comments
关联。你可以通过预加载来避免 N+1 查询问题:
class PostType < GraphQL::Schema::Object
field :comments, [CommentType], null: false do
preload :comments
end
def comments
object.comments
end
end
使用 preload_scope
从 Rails 4.1 开始,你可以通过传递一个有效的范围来限定预加载的记录,从而提高性能并帮助处理某些业务逻辑(例如,只返回未被软删除的记录):
class PostType < GraphQL::Schema::Object
field :comments, [CommentType], null: false do
preload :comments
preload_scope ->(args, ctx) { Comment.where(deleted_at: nil) }
end
def comments
object.comments
end
end
典型生态项目
GraphQL Preload 通常与其他 GraphQL 相关的 gem 一起使用,例如:
graphql
:GraphQL 的 Ruby 实现。graphql-batch
:一个用于批量加载数据的库,与 GraphQL Preload 配合使用可以进一步提高性能。activerecord
:Ruby on Rails 的 ORM,用于数据库交互。
这些项目共同构成了一个强大的生态系统,帮助开发者构建高效、可扩展的 GraphQL API。