shortn-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,333 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "time"
7
+ require "uri"
8
+
9
+ require_relative "errors"
10
+ require_relative "retry_options"
11
+ require_relative "version"
12
+ require_relative "transport"
13
+ require_relative "resources/base"
14
+ require_relative "resources/links"
15
+ require_relative "resources/analytics"
16
+ require_relative "resources/workspaces"
17
+ require_relative "resources/tags"
18
+ require_relative "resources/utm_templates"
19
+ require_relative "resources/destinations"
20
+ require_relative "resources/teams"
21
+ require_relative "resources/domains"
22
+ require_relative "resources/reports"
23
+ require_relative "resources/conversions"
24
+ require_relative "resources/public"
25
+
26
+ module Shortn
27
+ module SDK
28
+ # Client for the Shortn Link public API (`<base_url>/api/v1`).
29
+ #
30
+ # shortn = Shortn::SDK::Client.new(api_key: ENV.fetch("SHORTN_API_KEY"))
31
+ # shortn.links.list(limit: 10)
32
+ #
33
+ # Every method returns the decoded JSON response as plain Hashes and Arrays
34
+ # with string keys, so fields the API adds later are always reachable.
35
+ class Client
36
+ DEFAULT_BASE_URL = "https://app.shortn.link"
37
+ DEFAULT_TIMEOUT = 30
38
+ API_PREFIX = "/api/v1"
39
+
40
+ # Failures before a response that are worth retrying. Anything else a
41
+ # transport raises (ArgumentError, NoMethodError, ...) propagates as is.
42
+ TRANSIENT_NETWORK_ERRORS = [
43
+ Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout,
44
+ Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::EPIPE, Errno::ETIMEDOUT, Errno::EHOSTUNREACH,
45
+ EOFError, IOError, SocketError, OpenSSL::SSL::SSLError
46
+ ].freeze
47
+
48
+ # Top-level body keys whose numeric value is sent as a decimal String.
49
+ AMOUNT_KEYS = %w[amount].freeze
50
+
51
+ attr_reader :base_url, :timeout, :retry_options, :user_agent,
52
+ :links, :analytics, :workspaces, :tags, :utm_templates, :destinations,
53
+ :teams, :domains, :reports, :conversions, :public
54
+
55
+ # @param api_key [String, nil] secret API key (`sk_live_...`). Only the
56
+ # public helpers (`client.public`) work without one.
57
+ # @param base_url [String] app origin; `/api/v1` is appended. Must be
58
+ # an http or https URL with a host (ConfigurationError otherwise).
59
+ # @param timeout [Numeric] open/read/write timeout in seconds.
60
+ # @param retry_options [RetryOptions, Hash, false] retry policy;
61
+ # `false` turns retries off.
62
+ # @param user_agent [String, nil] appended to `shortn-sdk-ruby/<version>`.
63
+ # @param transport [#call, nil] HTTP transport, called as
64
+ # `call(method, url, headers, body, timeout)` and returning
65
+ # `[status, headers, body]`. Defaults to Net::HTTP.
66
+ # @param sleeper [#call, nil] called with the seconds to wait between
67
+ # retries. Defaults to Kernel#sleep.
68
+ def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT, retry_options: nil,
69
+ user_agent: nil, transport: nil, sleeper: nil)
70
+ @api_key = api_key.to_s.strip
71
+ @api_key = nil if @api_key.empty?
72
+ @base_url = normalize_base_url(base_url)
73
+ @timeout = timeout
74
+ @retry_options = build_retry_options(retry_options)
75
+ @user_agent = ["shortn-sdk-ruby/#{VERSION}", user_agent].compact.map(&:to_s).reject(&:empty?).join(" ")
76
+ @transport = transport || NetHTTPTransport.new
77
+ @sleeper = sleeper || ->(seconds) { sleep(seconds) }
78
+
79
+ @links = LinksResource.new(self)
80
+ @analytics = AnalyticsResource.new(self)
81
+ @workspaces = WorkspacesResource.new(self)
82
+ @tags = TagsResource.new(self)
83
+ @utm_templates = UTMTemplatesResource.new(self)
84
+ @destinations = DestinationsResource.new(self)
85
+ @teams = TeamsResource.new(self)
86
+ @domains = DomainsResource.new(self)
87
+ @reports = ReportsResource.new(self)
88
+ @conversions = ConversionsResource.new(self)
89
+ @public = PublicResource.new(self)
90
+ end
91
+
92
+ def inspect
93
+ "#<#{self.class.name} base_url=#{@base_url.inspect} api_key=#{@api_key ? '[set]' : 'nil'}>"
94
+ end
95
+
96
+ # Sends a request and returns the decoded JSON body (`{}` for an empty
97
+ # body). Resource methods call this; use it directly for endpoints the
98
+ # SDK does not wrap yet.
99
+ #
100
+ # @param method [String] HTTP method
101
+ # @param path [String] path below `/api/v1`, already escaped
102
+ # @param query [Hash, nil] query parameters; nil values are left out
103
+ # @param body [Hash, Array, nil] JSON body. Time and DateTime values are
104
+ # sent as UTC RFC 3339 ("2026-01-01T00:00:00Z"), Date as midnight UTC,
105
+ # BigDecimal and Rational as plain decimal Strings, and an Integer or
106
+ # Float under a top-level `amount` key as a
107
+ # decimal String too (the API's `amount` is a String such as "19.99").
108
+ # @param auth [Boolean] send the API key (raises ConfigurationError when
109
+ # none is configured)
110
+ # @param idempotent [Boolean, nil] whether a retry is safe; defaults to
111
+ # true for GET, PUT and DELETE
112
+ def request(method, path, query: nil, body: nil, auth: true, idempotent: nil)
113
+ response = perform(method, path, query: query, body: body, auth: auth, idempotent: idempotent,
114
+ accept: "application/json")
115
+ decode_json(response[:body])
116
+ end
117
+
118
+ # Like #request, but returns the raw response:
119
+ # `{status:, headers:, body:}` with lower-case header names.
120
+ def request_raw(method, path, query: nil, body: nil, auth: true, idempotent: nil, accept: "*/*")
121
+ perform(method, path, query: query, body: body, auth: auth, idempotent: idempotent, accept: accept)
122
+ end
123
+
124
+ # Percent-encodes one path segment (RFC 3986 unreserved characters stay).
125
+ def self.escape_path(value)
126
+ value.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |char| format("%%%02X", char.ord) }
127
+ end
128
+
129
+ private
130
+
131
+ def perform(method, path, query:, body:, auth:, idempotent:, accept:)
132
+ method = method.to_s.upcase
133
+ idempotent = %w[GET HEAD PUT DELETE].include?(method) if idempotent.nil?
134
+ url = build_url(path, query)
135
+ headers = build_headers(auth, accept)
136
+ payload = nil
137
+ unless body.nil?
138
+ payload = JSON.generate(json_body(body))
139
+ headers["Content-Type"] = "application/json"
140
+ end
141
+
142
+ attempt = 0
143
+ loop do
144
+ begin
145
+ status, response_headers, response_body = @transport.call(method, url, headers, payload, @timeout)
146
+ rescue *TRANSIENT_NETWORK_ERRORS => e
147
+ message = "Shortn request failed before a response arrived: #{e.class}: #{e.message}"
148
+ raise NetworkError, message if certificate_failure?(e) || !retry_allowed?(idempotent, attempt)
149
+
150
+ wait(@retry_options.backoff(attempt))
151
+ attempt += 1
152
+ next
153
+ end
154
+
155
+ status = status.to_i
156
+ response_headers = normalize_headers(response_headers)
157
+ response_body = response_body.to_s
158
+ if status.between?(200, 299)
159
+ return { status: status, headers: response_headers, body: response_body }
160
+ end
161
+
162
+ error = api_error(status, response_headers, response_body)
163
+ raise error unless [429, 503].include?(status) && retry_allowed?(idempotent, attempt)
164
+
165
+ delay = error.retry_after
166
+ raise error if delay && delay > @retry_options.max_retry_after.to_f
167
+
168
+ wait(delay || @retry_options.backoff(attempt))
169
+ attempt += 1
170
+ end
171
+ end
172
+
173
+ # A TLS certificate the client refuses won't verify on a retry either.
174
+ def certificate_failure?(error)
175
+ error.is_a?(OpenSSL::SSL::SSLError) &&
176
+ error.message.match?(/certificate verify failed|does not match the server certificate/i)
177
+ end
178
+
179
+ def retry_allowed?(idempotent, attempt)
180
+ idempotent && @retry_options.enabled? && attempt < @retry_options.max_retries.to_i
181
+ end
182
+
183
+ def wait(seconds)
184
+ @sleeper.call(seconds) if seconds.positive?
185
+ end
186
+
187
+ def build_url(path, query)
188
+ url = "#{@base_url}#{API_PREFIX}#{path}"
189
+ encoded = encode_query(query)
190
+ encoded.empty? ? url : "#{url}?#{encoded}"
191
+ end
192
+
193
+ def encode_query(query)
194
+ return "" if query.nil? || query.empty?
195
+
196
+ pairs = query.each_with_object([]) do |(key, value), list|
197
+ next if value.nil?
198
+
199
+ list << [key.to_s, query_value(value)]
200
+ end
201
+ URI.encode_www_form(pairs)
202
+ end
203
+
204
+ # Booleans go as "1"/"0", the form the API's flags (report_scope,
205
+ # include_total, ...) accept.
206
+ def query_value(value)
207
+ case value
208
+ when Array then value.map(&:to_s).join(",")
209
+ when true then "1"
210
+ when false then "0"
211
+ when Time then value.getutc.iso8601
212
+ when DateTime then value.to_time.getutc.iso8601
213
+ else value.to_s
214
+ end
215
+ end
216
+
217
+ # Copies the body with every value in a form the API parses; see #request.
218
+ def json_body(body)
219
+ return json_value(body) unless body.is_a?(Hash)
220
+
221
+ body.each_with_object({}) do |(key, value), result|
222
+ result[key] = AMOUNT_KEYS.include?(key.to_s) && value.is_a?(Numeric) ? decimal_string(value) : json_value(value)
223
+ end
224
+ end
225
+
226
+ def json_value(value)
227
+ case value
228
+ when Hash then value.each_with_object({}) { |(key, item), result| result[key] = json_value(item) }
229
+ when Array then value.map { |item| json_value(item) }
230
+ when Time then value.getutc.iso8601
231
+ when DateTime then value.to_time.getutc.iso8601
232
+ when Date then value.strftime("%Y-%m-%dT00:00:00Z")
233
+ when Rational then decimal_string(value)
234
+ else
235
+ defined?(::BigDecimal) && value.is_a?(::BigDecimal) ? decimal_string(value) : value
236
+ end
237
+ end
238
+
239
+ # A plain decimal String with no exponent and no trailing zeros:
240
+ # 19.99 => "19.99", 1.0e-05 => "0.00001", 20 => "20". A Float goes
241
+ # through its shortest decimal form, so 19.99 isn't sent as
242
+ # 19.989999999999998.
243
+ def decimal_string(number)
244
+ if number.is_a?(Float) || (defined?(::BigDecimal) && number.is_a?(::BigDecimal))
245
+ raise ArgumentError, "#{number} has no decimal form" unless number.finite?
246
+ end
247
+ rational = number.is_a?(Float) ? Rational(number.to_s) : number.to_r
248
+ scale = decimal_places(rational.denominator)
249
+ raise ArgumentError, "#{number} has no exact decimal form" if scale.nil?
250
+
251
+ digits = (rational.abs * (10**scale)).to_i.to_s.rjust(scale + 1, "0")
252
+ text = scale.zero? ? digits : "#{digits[0...-scale]}.#{digits[-scale..]}"
253
+ rational.negative? ? "-#{text}" : text
254
+ end
255
+
256
+ # Decimals needed to write 1/denominator exactly, or nil when it repeats.
257
+ def decimal_places(denominator)
258
+ twos = fives = 0
259
+ while (denominator % 2).zero?
260
+ denominator /= 2
261
+ twos += 1
262
+ end
263
+ while (denominator % 5).zero?
264
+ denominator /= 5
265
+ fives += 1
266
+ end
267
+ denominator == 1 ? [twos, fives].max : nil
268
+ end
269
+
270
+ def build_headers(auth, accept)
271
+ headers = { "Accept" => accept, "User-Agent" => @user_agent }
272
+ if auth
273
+ raise ConfigurationError, "This endpoint needs an API key: pass api_key: to Shortn::SDK::Client.new." if @api_key.nil?
274
+
275
+ headers["Authorization"] = "Bearer #{@api_key}"
276
+ end
277
+ headers
278
+ end
279
+
280
+ def normalize_headers(headers)
281
+ (headers || {}).each_with_object({}) do |(name, value), result|
282
+ result[name.to_s.downcase] = value.is_a?(Array) ? value.join(", ") : value.to_s
283
+ end
284
+ end
285
+
286
+ def decode_json(body)
287
+ return {} if body.nil? || body.strip.empty?
288
+
289
+ JSON.parse(body)
290
+ rescue JSON::ParserError
291
+ body
292
+ end
293
+
294
+ def api_error(status, headers, body)
295
+ data = nil
296
+ begin
297
+ data = JSON.parse(body) unless body.strip.empty?
298
+ rescue JSON::ParserError
299
+ data = nil
300
+ end
301
+ message = data.is_a?(Hash) ? (data["error"] || data["message"]).to_s.strip : ""
302
+ message = "Shortn API request failed with HTTP #{status}." if message.empty?
303
+ APIError.new(message, status: status, body: body, data: data, headers: headers)
304
+ end
305
+
306
+ def normalize_base_url(value)
307
+ url = value.to_s.strip
308
+ url = DEFAULT_BASE_URL if url.empty?
309
+ url = url.sub(%r{/+\z}, "").sub(%r{/api/v1\z}, "")
310
+ uri = begin
311
+ URI.parse(url)
312
+ rescue URI::InvalidURIError
313
+ nil
314
+ end
315
+ unless uri && %w[http https].include?(uri.scheme.to_s.downcase) && !uri.host.to_s.empty?
316
+ raise ConfigurationError, "base_url must be an http or https URL with a host, such as #{DEFAULT_BASE_URL}"
317
+ end
318
+
319
+ url
320
+ end
321
+
322
+ def build_retry_options(value)
323
+ case value
324
+ when nil then RetryOptions.new
325
+ when false then RetryOptions.none
326
+ when RetryOptions then value
327
+ when Hash then RetryOptions.new(**value.transform_keys(&:to_sym))
328
+ else raise ArgumentError, "retry_options must be a Shortn::SDK::RetryOptions, a Hash or false"
329
+ end
330
+ end
331
+ end
332
+ end
333
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Base class for every error the SDK raises.
6
+ class Error < StandardError; end
7
+
8
+ # The client is missing something it needs, such as an API key.
9
+ class ConfigurationError < Error; end
10
+
11
+ # The request failed before an HTTP response arrived (DNS, connection,
12
+ # TLS, timeout). The original exception is available as #cause.
13
+ class NetworkError < Error; end
14
+
15
+ # The API answered with a non-2xx status.
16
+ #
17
+ # Shortn errors look like:
18
+ # {"code": "...", "error": "...", "hint": "...", "details": {"field": "..."}}
19
+ # Plan-limit errors add top-level fields such as "feature" and
20
+ # "required_plan"; read them from #data. #code is nil only for an answer
21
+ # that didn't come from the API, such as a proxy's 502 page.
22
+ class APIError < Error
23
+ # @return [Integer] HTTP status code
24
+ attr_reader :status
25
+ # @return [String, nil] stable machine-readable code, when the API sends one
26
+ attr_reader :code
27
+ # @return [String, nil] the hint the API sends with some errors
28
+ attr_reader :hint
29
+ # @return [String, nil] the request field at fault (details.field)
30
+ attr_reader :field
31
+ # @return [Hash, nil] the details object
32
+ attr_reader :details
33
+ # @return [String, nil] request id sent by the conversion intake endpoints
34
+ attr_reader :request_id
35
+ # @return [Hash, Array, nil] the parsed JSON body, when the body is JSON
36
+ attr_reader :data
37
+ # @return [String] the raw response body
38
+ attr_reader :body
39
+ # @return [Hash{String => String}] response headers, lower-case names
40
+ attr_reader :headers
41
+
42
+ def initialize(message, status:, body: "", data: nil, headers: {})
43
+ super(message)
44
+ @status = status
45
+ @body = body.to_s
46
+ @data = data
47
+ @headers = headers || {}
48
+ envelope = data.is_a?(Hash) ? data : {}
49
+ @code = string_or_nil(envelope["code"])
50
+ @hint = string_or_nil(envelope["hint"])
51
+ @details = envelope["details"].is_a?(Hash) ? envelope["details"] : nil
52
+ @field = string_or_nil(@details && @details["field"]) || string_or_nil(envelope["field"])
53
+ @request_id = string_or_nil(envelope["request_id"]) || string_or_nil(@headers["shortn-request-id"])
54
+ end
55
+
56
+ # Seconds from the Retry-After header, when present.
57
+ def retry_after
58
+ Shortn::SDK.parse_retry_after(@headers["retry-after"])
59
+ end
60
+
61
+ private
62
+
63
+ def string_or_nil(value)
64
+ return nil if value.nil?
65
+
66
+ text = value.to_s
67
+ text.empty? ? nil : text
68
+ end
69
+ end
70
+
71
+ # Parses a Retry-After header value (delta seconds or an HTTP date) into
72
+ # seconds. Returns nil when the value is missing or unreadable.
73
+ def self.parse_retry_after(value)
74
+ text = value.to_s.strip
75
+ return nil if text.empty?
76
+ return [Float(text), 0.0].max if text.match?(/\A\d+(\.\d+)?\z/)
77
+
78
+ require "time"
79
+ [Time.httpdate(text) - Time.now, 0.0].max
80
+ rescue ArgumentError
81
+ nil
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Link analytics: `/analytics/links/{public_id}`.
6
+ class AnalyticsResource < Resource
7
+ # GET /analytics/links/{public_id}: `total_clicks`, `unique_clicks`,
8
+ # `clicks_by_country`. Counts toward the analytics rate limit.
9
+ # The endpoint reads no query parameters today; `query` is sent as given
10
+ # for forward compatibility and has no effect.
11
+ def link(id, query = {})
12
+ get_request("/analytics/links/#{segment(id, 'id')}", hash_param(query, "query"))
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Shared helpers for the resource groups.
6
+ class Resource
7
+ def initialize(client)
8
+ @client = client
9
+ end
10
+
11
+ def inspect
12
+ "#<#{self.class.name}>"
13
+ end
14
+
15
+ private
16
+
17
+ def get_request(path, query = nil, auth: true)
18
+ @client.request("GET", path, query: query, auth: auth)
19
+ end
20
+
21
+ def post_request(path, body = nil, idempotent: false)
22
+ @client.request("POST", path, body: body, idempotent: idempotent)
23
+ end
24
+
25
+ def put_request(path, body, query = nil)
26
+ @client.request("PUT", path, body: body, query: query)
27
+ end
28
+
29
+ def patch_request(path, body)
30
+ @client.request("PATCH", path, body: body)
31
+ end
32
+
33
+ def delete_request(path, query = nil)
34
+ @client.request("DELETE", path, query: query)
35
+ end
36
+
37
+ # Escapes one path segment and refuses an empty one, so a missing id
38
+ # can't turn `GET /links/{code}` into `GET /links/`.
39
+ def segment(value, name)
40
+ text = value.to_s
41
+ raise ArgumentError, "#{name} is required" if text.strip.empty?
42
+
43
+ Client.escape_path(text)
44
+ end
45
+
46
+ def hash_param(value, name)
47
+ return {} if value.nil?
48
+ raise ArgumentError, "#{name} must be a Hash" unless value.is_a?(Hash)
49
+
50
+ value
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Conversions: send leads, sales and refunds, validate them without
6
+ # recording, and read conversion reporting.
7
+ #
8
+ # Bodies are passed through as snake_case JSON; the API refuses unknown
9
+ # fields. `amount` is a String such as "19.99"; an Integer, Float or
10
+ # BigDecimal is converted to one. `occurred_at` may be a Time.
11
+ #
12
+ # A live write that carries `idempotency_key` is retried on 429, 503 and
13
+ # network errors, since the API records a live event once per key. A
14
+ # `test_mode: true` write is never retried: the API does not deduplicate
15
+ # test events, so a retry would record a second one.
16
+ class ConversionsResource < Resource
17
+ # POST /conversions/leads. Needs `click_id` and `idempotency_key`.
18
+ def track_lead(params)
19
+ intake("/conversions/leads", params)
20
+ end
21
+
22
+ # POST /conversions/leads/validations: same checks, records nothing.
23
+ def validate_lead(params)
24
+ intake("/conversions/leads/validations", params)
25
+ end
26
+
27
+ # POST /conversions/sales. Needs `click_id`, `currency`, and `invoice_id`
28
+ # or `idempotency_key`; amount as `amount_cents` or `amount`.
29
+ def track_sale(params)
30
+ intake("/conversions/sales", params)
31
+ end
32
+
33
+ # POST /conversions/sales/validations
34
+ def validate_sale(params)
35
+ intake("/conversions/sales/validations", params)
36
+ end
37
+
38
+ # POST /conversions/refunds. Needs `invoice_id`, `refund_id` and an
39
+ # amount (`amount_cents` or `amount`).
40
+ def track_refund(params)
41
+ intake("/conversions/refunds", params)
42
+ end
43
+
44
+ # POST /conversions/refunds/validations
45
+ def validate_refund(params)
46
+ intake("/conversions/refunds/validations", params)
47
+ end
48
+
49
+ # GET /conversions/summary: all-time live totals under `data`.
50
+ def summary(query = {})
51
+ get_request("/conversions/summary", hash_param(query, "query"))
52
+ end
53
+
54
+ # GET /conversions/attribution. Query: `from`, `to`, `environment`
55
+ # ("live"/"test"), `limit`.
56
+ def attribution(query = {})
57
+ get_request("/conversions/attribution", hash_param(query, "query"))
58
+ end
59
+
60
+ # GET /conversions/timeline. Query: `from`, `to`, `environment`,
61
+ # `interval` ("day", "week", "month").
62
+ def timeline(query = {})
63
+ get_request("/conversions/timeline", hash_param(query, "query"))
64
+ end
65
+
66
+ # GET /conversions/events. Query: `from`, `to`, `environment`, `limit`,
67
+ # `offset`, `event_type`, `lead_category`, `event_origin`, `link`,
68
+ # `event`, `q`.
69
+ def events(query = {})
70
+ get_request("/conversions/events", hash_param(query, "query"))
71
+ end
72
+
73
+ private
74
+
75
+ def intake(path, params)
76
+ body = hash_param(params, "params")
77
+ key = body[:idempotency_key] || body["idempotency_key"]
78
+ test_mode = body.key?(:test_mode) ? body[:test_mode] : body["test_mode"]
79
+ post_request(path, body, idempotent: !key.to_s.strip.empty? && !test_mode)
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Report destinations: `/workspaces/{public_id}/destinations`.
6
+ # These endpoints answer without a `data` wrapper; the list is an Array.
7
+ class DestinationsResource < Resource
8
+ # GET /workspaces/{workspace_id}/destinations
9
+ def list(workspace_id)
10
+ get_request(collection(workspace_id))
11
+ end
12
+
13
+ # POST /workspaces/{workspace_id}/destinations. Params: `name`, `type`
14
+ # (email, webhook, slack, discord, msteams), `config`, `team_public_ids`.
15
+ def create(workspace_id, params)
16
+ post_request(collection(workspace_id), hash_param(params, "params"))
17
+ end
18
+
19
+ # PUT /workspaces/{workspace_id}/destinations/{destination_id}.
20
+ # `name` and `type` are required every time.
21
+ def update(workspace_id, destination_id, params)
22
+ put_request("#{collection(workspace_id)}/#{segment(destination_id, 'destination_id')}", hash_param(params, "params"))
23
+ end
24
+
25
+ # DELETE /workspaces/{workspace_id}/destinations/{destination_id}
26
+ def delete(workspace_id, destination_id)
27
+ delete_request("#{collection(workspace_id)}/#{segment(destination_id, 'destination_id')}")
28
+ end
29
+
30
+ private
31
+
32
+ def collection(workspace_id)
33
+ "/workspaces/#{segment(workspace_id, 'workspace_id')}/destinations"
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Custom domains: `/domains`. Domains use a numeric `id`. Creating,
6
+ # verifying and deleting need an account-wide key.
7
+ class DomainsResource < Resource
8
+ # GET /domains. The domains are under `data`.
9
+ def list
10
+ get_request("/domains")
11
+ end
12
+
13
+ # POST /domains. Params: `domain`. The new domain is under `domain`.
14
+ def create(params)
15
+ params = { domain: params } if params.is_a?(String)
16
+ post_request("/domains", hash_param(params, "params"))
17
+ end
18
+
19
+ # POST /domains/{id}/verify: checks DNS now.
20
+ def verify(id)
21
+ post_request("/domains/#{segment(id, 'id')}/verify")
22
+ end
23
+
24
+ # DELETE /domains/{id}
25
+ def delete(id)
26
+ delete_request("/domains/#{segment(id, 'id')}")
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shortn
4
+ module SDK
5
+ # Links: `/links`. Refer to a link by its `public_id`.
6
+ class LinksResource < Resource
7
+ # GET /links. Query: `limit` (1-100), `offset`.
8
+ def list(query = {})
9
+ get_request("/links", hash_param(query, "query"))
10
+ end
11
+
12
+ # GET /links/{public_id}. The link is under `data`.
13
+ def get(public_id)
14
+ get_request("/links/#{segment(public_id, 'public_id')}")
15
+ end
16
+
17
+ # POST /links with the API key. `url` and `title` are required; see the
18
+ # API docs for every optional field (tags, UTM, schedule, targeting...).
19
+ def create(params)
20
+ post_request("/links", hash_param(params, "params"))
21
+ end
22
+
23
+ # PATCH /links/{public_id}. Fields: `title`, `description`, `url`,
24
+ # `short_code`, `domain`, `status`, `active`, `team_public_ids`.
25
+ def update(public_id, params)
26
+ patch_request("/links/#{segment(public_id, 'public_id')}", hash_param(params, "params"))
27
+ end
28
+
29
+ # DELETE /links/{public_id}: suspends the link (history is kept).
30
+ def delete(public_id)
31
+ delete_request("/links/#{segment(public_id, 'public_id')}")
32
+ end
33
+
34
+ # POST /links/{public_id}/enable: makes a suspended link active again.
35
+ def enable(public_id)
36
+ post_request("/links/#{segment(public_id, 'public_id')}/enable")
37
+ end
38
+
39
+ # POST /links/{public_id}/ab/winner. Params: `variant` (such as "B").
40
+ # A String is taken as the variant.
41
+ def set_ab_winner(public_id, params)
42
+ params = { variant: params } if params.is_a?(String)
43
+ post_request("/links/#{segment(public_id, 'public_id')}/ab/winner", hash_param(params, "params"))
44
+ end
45
+ end
46
+ end
47
+ end