summaryrefslogtreecommitdiff
path: root/lib/gitlab/graphql/variables.rb
blob: b13ea37c21ff3e28e70efea29b4247f1a97c59f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

module Gitlab
  module Graphql
    class Variables
      Invalid = Class.new(Gitlab::Graphql::StandardGraphqlError)

      def initialize(param)
        @param = param
      end

      def to_h
        ensure_hash(@param)
      end

      private

      # Handle form data, JSON body, or a blank value
      def ensure_hash(ambiguous_param)
        case ambiguous_param
        when String
          if ambiguous_param.present?
            ensure_hash(JSON.parse(ambiguous_param))
          else
            {}
          end
        when Hash, ActionController::Parameters
          ambiguous_param
        when nil
          {}
        else
          raise Invalid, "Unexpected parameter: #{ambiguous_param}"
        end
      rescue JSON::ParserError => e
        raise Invalid.new(e)
      end
    end
  end
end