gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中设置 GraphQL Relay API

转载 作者:行者123 更新时间:2023-12-03 22:55:53 27 4
gpt4 key购买 nike

我正在尝试围绕 GraphQL/Relay 进行思考,但我发现很难开始了解如何使用 Ruby on Rails 正确设置符合 Relay 的 GraphQL API。

我找到了多个关于如何做到这一点的教程:

https://medium.com/react-weekly/relay-facebook-on-rails-8b4af2057152#.gd8p6tbwi

https://medium.com/@gauravtiwari/graphql-and-relay-on-rails-getting-started-955a49d251de#.m05xjvi82

但他们都指的是graphql-relay目前似乎不可用的 gem :https://github.com/rmosolgo/graphql-relay-ruby
grahql-ruby gem 在文档中有一个特定于 relay 的部分,但我发现很难理解将其设置为由中继客户端使用需要什么。

在 Rails 中为 Relay 客户端实现 GraphQL API 需要什么?

最佳答案

我只是想把我的发现留给那些在 future 遇到这个问题并希望指出更好方向的人。

一、graphql-ruby gem 包含实现 Relay 兼容的 GraphQL API 所需的一切。包含之前在 graphql-relay 中的所有内容 gem 。

您需要在 Schema 中提供 2 项内容,以使 Relay 重新获取功能正常工作,即 id_from_object将域中的对象转换为全局 ID 和 object_from_id 的方法将全局 id 解码为应用程序中的对象的方法:

ApplicationSchema = GraphQL::Schema.define do
/* Create IDs by joining the type name & ID, then base64-encoding it */
id_from_object ->(object, type_definition, query_ctx) {
GraphQL::Schema::UniqueWithinType.encode(type_definition.name, object.id)
}

object_from_id ->(id, query_ctx) {
type_name, object_id = GraphQL::Schema::UniqueWithinType.decode(id)
# Now, based on `type_name` and `id`
# find an object in your application
# This will give the user access to all records in your db
# so you might want to restrict this properly
Object.const_get(type_name).find(object_id)
}
end

此外,您的所有类型都应实现 NodeInterface由 ruby​​ gem 提供,并暴露一个 global_id_field而不是 ID 类型:
PostType = GraphQL::ObjectType.define do
name "Post"
# Implements the "Node" interface for Relay
interfaces [GraphQL::Relay::Node.interface]
# exposes the global id
global_id_field :id
field :name, types.String
end

这将允许 Relay 重新获取数据,如下所示:
query {
node(id: "RmFjdGlvbjox") {
id
... on Post {
name
}
}
}

中继也使用 babel-relay-plugin这需要生成一个 schema.json 并可供客户端使用,如果您正在构建一个没有 View 渲染的隔离 API,那么要走的方法是让客户端获取架构而不是在服务器中执行该工作,像 apollo-codegen能行得通。但是,如果您正在构建一个 rails 应用程序并且需要在同一个应用程序中使用架构,那么您可以运行自省(introspection)查询并使用 rake 任务将结果保存到 json 文件中:
Schema.execute GraphQL::Introspection::INTROSPECTION_QUERY

最后,您需要了解 Relay 表示与连接的一对多关系:
PostType = GraphQL::ObjectType.define do
# default connection
# obj.comments by default
connection :comments, CommentType.connection_type

# custom connection
connection :featured_comments, CommentType.connection_type do
resolve ->(post, args, ctx) {
comments = post.comments.featured

if args[:since]
comments = comments.where("created_at >= ?", since)
end

comments
}
end
end

连接支持一些开箱即用的参数,您可以使用 first , last , beforeafter在您的连接查询中:
query {
posts(first: 5) {
edges {
node {
name
}
}
}
}

所有这些都记录在 Relay documentation 中。所以请确保您阅读了它以及 graphql-ruby文档。

关于ruby-on-rails - 如何在 Rails 中设置 GraphQL Relay API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com