File: request.rb

package info (click to toggle)
ruby-app-store-connect 0.37.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 444 kB
  • sloc: ruby: 856; makefile: 4
file content (93 lines) | stat: -rw-r--r-- 1,909 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
84
85
86
87
88
89
90
91
92
93
# frozen_string_literal: true

require 'net/http'

module AppStoreConnect
  class Request
    class UnsupportedHTTPMethod < ArgumentError
      def initialize(http_method)
        super "Unsupported HTTP Method: #{http_method}"
      end
    end

    def initialize(**options)
      @uri = options.fetch(:uri)
      @options = options
    end

    def execute
      Net::HTTP.start(uri.host, uri.port, net_http_options) do |http|
        http.request(request)
      end
    end

    private

    def web_service_endpoint
      @options.fetch(:web_service_endpoint)
    end

    def query
      return unless http_method == :get

      names = url_parameter_names(web_service_endpoint)

      kwargs
        .reject { |n| names.include?(n) }
        .deep_transform_keys { |k| k.to_s.camelize(:lower) }
        .to_query
    end

    def http_method
      @options.fetch(:http_method).to_sym
    end

    def net_http_options
      { use_ssl: uri.scheme == 'https' }
    end

    def kwargs
      @options.fetch(:kwargs, {})
    end

    def uri
      @options.fetch(:uri).tap do |uri|
        uri.query = query if http_method == :get
      end
    end

    def headers
      @options.fetch(:headers, {})
    end

    def body
      return if http_method == :get

      @options.fetch(:http_body)
    end

    def url_parameter_names(web_service_endpoint)
      web_service_endpoint
        .url
        .scan(/(\{(\w+)\})/)
        .map { |_, n| n.to_sym }
    end

    def net_http_request_class
      case http_method
      when :get then Net::HTTP::Get
      when :post then Net::HTTP::Post
      when :delete then Net::HTTP::Delete
      when :patch then Net::HTTP::Patch
      else
        raise UnsupportedHTTPMethod, http_method
      end
    end

    def request
      net_http_request_class
        .new(uri, headers)
        .tap { |r| r.body = body if r.request_body_permitted? }
    end
  end
end