6
6
require 'sms77/endpoint'
7
7
8
8
module Sms77
9
- class Base
9
+ class Resource
10
+ attr_reader :api_key , :endpoint , :sent_with , :http_methods , :request_methods , :builder , :conn
11
+
10
12
BASE_PATH = '/api/'
11
- CONN = Faraday . new ( "https://gateway.sms77.io#{ BASE_PATH } " )
12
- HTTP_GET = CONN . method ( :get ) . freeze
13
- HTTP_POST = CONN . method ( :post ) . freeze
14
- CONN . freeze
15
- HTTP_METHODS = [ HTTP_GET , HTTP_POST ] . freeze
16
- BUILDER = CONN . builder
17
13
18
14
def initialize ( api_key , sent_with = 'ruby' )
19
15
raise 'missing api_key in config' if api_key . to_s . empty?
20
16
raise 'missing sent_with in config' if sent_with . to_s . empty?
21
17
22
18
@api_key = api_key
23
19
@sent_with = sent_with
24
-
25
- HTTP_METHODS . each do |method |
26
- define_singleton_method ( method . name ) { |*args | request ( method , *args ) }
27
- end
20
+ @endpoint = self . class . get_endpoint
21
+ @http_methods = self . class . get_http_methods
22
+ @conn = Faraday . new ( "https://gateway.sms77.io#{ BASE_PATH } " )
28
23
end
29
24
30
- attr_reader :api_key , :sent_with
31
-
32
25
protected
33
26
34
- def request ( method , path , payload = { } )
35
- if !payload . empty? && HTTP_GET == method
36
- path = "#{ path } ?#{ URI . encode_www_form ( payload ) } "
27
+ def request ( payload = { } , query = { } )
28
+ path = @endpoint
29
+ http_method = @http_methods [ caller_locations . first . label . to_sym ]
30
+
31
+ if :get == http_method
32
+ query = payload
37
33
38
34
payload = { }
39
35
end
40
36
41
- method = method . name
37
+ query . each do |key , val |
38
+ query . store ( key , Sms77 ::Util ::to_numbered_bool ( val ) )
39
+ end
40
+
41
+ payload . each do |key , val |
42
+ payload . store ( key , Sms77 ::Util ::to_numbered_bool ( val ) )
43
+ end
44
+
45
+ unless query . empty?
46
+ path = "#{ path } ?#{ URI . encode_www_form ( query ) } "
47
+ end
48
+
42
49
headers = Hash [
43
50
Faraday ::Request ::Authorization ::KEY , "Bearer #{ @api_key } " ,
44
51
'sentWith' , @sent_with
45
52
]
46
53
47
- res = CONN . run_request ( method , path , payload , headers )
54
+ res = @conn . run_request ( http_method , path , payload , headers )
48
55
49
56
puts JSON . pretty_generate ( res . to_hash . merge ( {
50
- :method => method ,
57
+ :method => http_method ,
51
58
:path => path ,
52
59
:payload => payload ,
53
- :req_headers => headers
60
+ :req_headers => headers ,
61
+ :query => query ,
54
62
} ) . compact ) if ENV [ 'SMS77_DEBUG' ]
55
63
56
64
raise "Error requesting (#{ self . class . name } ) with code #{ res . status } " unless 200 == res . status
@@ -71,5 +79,15 @@ def request(method, path, payload = {})
71
79
72
80
body
73
81
end
82
+
83
+ class << self
84
+ def get_http_methods
85
+ @http_methods
86
+ end
87
+
88
+ def get_endpoint
89
+ @endpoint
90
+ end
91
+ end
74
92
end
75
93
end
0 commit comments