0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GraphQLでカスタムタイプの作り方

Last updated at Posted at 2020-04-02

はじめに

graphql-rubyでデフォルトであるタイプでは足りず、自作タイプを作りたいとき。
(英語含めて)これといった記事がなかったため書きました。
なお我流なので、正しいやり方を知っている人がいれば教えてください。
今回はTimeTypeを作ります。

custom_types/time.rbの作成

わかりやすいようにcustom_typesでディレクトリを切っています。
実装は本家を参考にしました。

module CustomTypes
  class Time < GraphQL::Schema::Scalar
    description "An ISO 8601-encoded time without timezone"

    # @param value [DateTime]
    # @return [String]
    def self.coerce_result(value, _ctx)
      value.strftime("%H:%M:%S")
    end

    # @param str_value [String]
    # @return [DateTime]
    def self.coerce_input(str_value, _ctx)
      ::Time.zone.parse(str_value)
    rescue ArgumentError
      # Invalid input
      nil
    end
  end
end

これでMutationとかから呼べます。

class Mutations::CreateHoge < Mutations::BaseMutation
  graphql_name 'CreateHoge'
  argument :start, CustomTypes::Time, required: true

  field :errors, [String], null: false

  def resolve(**args)
    p args[:start]
    {
      errors: []
    }
  end
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?