Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In GraphQL/Rails how to pass arguments in the query_type?

So I'm trying to query on a single user within the database but end up getting:

"Field 'userSingle' doesn't accept argument 'first_name'"

I'm getting that in GraphiQL when I run the following query:

query GetSingleUser {
 userSingle(first_name: "Test"){
  first_name
  last_name
 }
} 

In my query_type.rb I have the following:

field :userSingle, !types[Types::UserType] do
 resolve -> (obj, args, ctx) {
 argument :first_name, !types.String
 argument :id, types.ID
 User.find(id: args[:id])}
end

Originally I had:

field :userSingle, !types[Types::UserType] do
  resolve -> (obj, args, ctx) {User.find(id: args[:id])}
end

Same issue. If I take out the id: same issue. Also the same issue with:

  field :userSingle, !types[Types::UserType] do
    resolve -> (obj, args, ctx) {
    argument :first_name, !types.String
    argument :id, types.ID
      user = User.find_by(
        id: args[:id],
        first_name: args[:first_name])
    }
  end
like image 985
Jake Avatar asked Mar 05 '23 23:03

Jake


1 Answers

You could create a user_type.rb file with the following:

class Types::UserType < Types::BaseObject
  description "A user object"

  field :id, Integer, null: false
  field :first_name, String, null: false
end

Then have the following in query_type.rb file:

module Types
  class QueryType < Types::BaseObject
    ...

    # User query
    field :user, UserType, null: true do
      description "Find a user by first_name"
      argument :first_name, String, required: true
    end
    def user(first_name:)
      User.find_by(first_name: first_name)
    end
  end
end

With all this in place, the query should then look like this:

{
  user(first_name: "name") {
    id
    firstName: first_name
  }
}

like image 146
ProfessorJigsaw Avatar answered Apr 28 '23 18:04

ProfessorJigsaw