我刚刚开始学习GraphQL,目前正在尝试创建Twitter的克隆。在下面的代码中,有没有办法我可以将81从id参数(例如user(id:81))自动传递给userId参数(例如tweets(userId:81))?
我已经在下面复制了我的代码
{
user(id: 81) {
username
email
tweets(userId: 81) {
content
}
}
}
user_type.rb
module Types
class UserType < Types::BaseObject
field :username, String, null: false
field :email, String, null: false
field :bio, String, null: true
field :tweets, [Types::TweetType], null: true do
argument :user_id, ID, required: true
end
def tweets(user_id:)
Tweet.where(user_id: user_id)
end
end
end
tweet_type.rb
module Types
class TweetType < Types::BaseObject
field :id, ID, null: false
field :content, String, null: false
field :userId, ID, null: false
field :createdAt, GraphQL::Types::ISO8601DateTime, null: false
field :user, Types::UserType, null: false
end
end
query_type.rb
module Types
class QueryType < Types::BaseObject
field :tweets,
[Types::TweetType],
null: false,
description: "Returns a list of all tweets"
field :user,
Types::UserType,
null: false,
description: "Returns a list of all users" do
argument :id, ID, required: true
end
def tweets
Tweet.all
end
def user(id:)
User.find(id)
end
end
end
答案 0 :(得分:0)
GraphQL具有一流的方法可将动态值从查询中分解出来,并将它们作为单独的字典(变量)传递。您将使用与下面类似的语法,并可以进一步了解here。
query User($id: Int) {
user(id: $id) {
username
email
tweets(userId: $id) {
content
}
}
}