简体   繁体   中英

How do I return custom object in a mutation?

I'd like my GraphQL mutation to return field that is not defined in the Type Object

I am using the Ruby GraphQL gem with Rails 6. I have described a UserType with the fields username , email and password . In my login mutation, I'd like to return a jwt token as the response. Here's what I have so far;

The user type:

module Types
  class UserType < BaseObject
    field :id, ID, null: false
    field :email, String, null: false
    field :username, String, null: false
  end
end

The mutation:

module Mutations
  UserMutation = GraphQL::ObjectType.define do
   field :login, Types::UserType do
     argument :username, !types.String
     argument :password, !types.String

     resolve ->(_obj, args, _ctx) do
       # perform the authentication and return a jwt token.
     end
   end
  end
end

I expect to get a response like:

{
  "data" : {
    "token": "my_generated_token"
  }
}

or an error message of the same shape.

Update : Here's the solution that worked for me. I created a new type LoginType that defines token and user fields and made the mutation respond to it instead of the UserType

module Types
  class LoginType < BaseObject
    field :token, String, null: false
    field :user, Types::UserType, null: false
  end
end

Thanks to @rmosolgo for the help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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