简体   繁体   English

在graphQL查询中传递参数

[英]passing arguments in graphQL queries

I'm just starting to learn GraphQL and I'm currently trying to create a clone of twitter. 我刚开始学习GraphQL,目前正在尝试创建Twitter的克隆。 In the code below, is there a way I can pass the 81 from the id argument (eg user(id: 81)) automatically to the userId argument (eg tweets(userId: 81))? 在下面的代码中,有没有一种方法可以将81从id参数(例如user(id:81))自动传递给userId参数(例如tweets(userId:81))?

I've copied my code below 我已经在下面复制了我的代码

{
  user(id: 81) {
    username
    email
    tweets(userId: 81) {
      content
    }
  }
}

user_type.rb 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 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 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

GraphQL has a first-class way to factor dynamic values out of the query, and pass them as a separate dictionary (variables). GraphQL具有一流的方法可将动态值从查询中分解出来,并将它们作为单独的字典(变量)传递。 You would use syntax similar to that below, and can read more about it here . 您将使用与下面类似的语法,并且可以在此处阅读有关它的更多信息。

  query User($id: Int) {
    user(id: $id) {
        username
        email
        tweets(userId: $id) {
          content
        }
     }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM