File: base.rb

package info (click to toggle)
ruby-app-store-connect 0.38.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 516 kB
  • sloc: ruby: 1,193; makefile: 4
file content (83 lines) | stat: -rw-r--r-- 2,332 bytes parent folder | download
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true

module AppStoreConnect
  class Base
    def initialize(**kwargs)
      @options = Client::Options.new(kwargs)
      @authorization = Client::Authorization.new(@options.slice(*Client::Authorization::OPTIONS))
      @registry = Client::Registry.new(@options.slice(*Client::Registry::OPTIONS))
    end

    def respond_to_missing?(method_name, include_private = false)
      web_service_endpoint_aliases.include?(method_name) || super
    end

    def method_missing(method_name, **kwargs)
      super unless web_service_endpoint_aliases.include?(method_name)

      web_service_endpoint = web_service_endpoint_by(method_name)

      call(web_service_endpoint, **kwargs)
    end

    # :nocov:
    def inspect
      "#<#{self.class.name}:#{object_id}>"
    end
    # :nocov:

    def web_service_endpoint_aliases
      @registry.keys
    end

    private

    def call(web_service_endpoint, **kwargs)
      raise "invalid http method: #{web_service_endpoint.http_method}" unless %i[get delete post patch].include?(web_service_endpoint.http_method)

      request = build_request(web_service_endpoint, **kwargs)

      response = request.execute

      Client::Utils.decode(response.body, response.content_type) if response.body
    end

    def build_uri(web_service_endpoint, **kwargs)
      URI(web_service_endpoint
        .url
        .gsub(/(\{(\w+)\})/) { kwargs.fetch(Regexp.last_match(2).to_sym) })
    end

    def web_service_endpoint_by(alias_sym)
      @registry[alias_sym]
    end

    def http_body(web_service_endpoint, **kwargs)
      Client::Utils.encode("AppStoreConnect::#{web_service_endpoint.http_body_type}"
        .constantize
        .new(**kwargs)
        .to_h)
    end

    def build_request(web_service_endpoint, **kwargs)
      options = {
        kwargs: kwargs,
        web_service_endpoint: web_service_endpoint,
        http_method: web_service_endpoint.http_method,
        uri: build_uri(web_service_endpoint, **kwargs),
        headers: headers
      }

      options[:http_body] = http_body(web_service_endpoint, **kwargs) if web_service_endpoint.http_body_type.present?

      Request.new(**options)
    end

    def headers
      {
        'Authorization' => "Bearer #{@authorization.token}",
        'Content-Type' => 'application/json'
      }
    end
  end
end