Module: Webhooks::Utilities::ClassMethods

Included in:
Webhooks::Utilities
Defined in:
lib/webhooks/utilities.rb,
app/models/webhooks/utilities.rb

Instance Method Summary collapse

Instance Method Details

#fetch_events(subscription) ⇒ Object



72
73
74
75
76
# File 'lib/webhooks/utilities.rb', line 72

def fetch_events(subscription)
  subscription['subscriptions'].map do |e|
    e['event']
  end.uniq
end

#record_notifications(consumer_id:, consumer_name:, event:, api_guid:, msg:) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/models/webhooks/utilities.rb', line 25

def record_notifications(consumer_id:, consumer_name:, event:, api_guid:, msg:)
  api_name = Webhooks::Utilities.event_to_api_name[event]
  webhook_urls = Webhooks::Subscription.get_notification_urls(
    api_name:, consumer_id:, event:, api_guid:
  )
  return [] unless webhook_urls.size.positive?

  notifications = []
  webhook_urls.each do |url|
    wh_notify = Webhooks::Notification.new
    wh_notify.api_name = api_name
    wh_notify.consumer_id = consumer_id
    wh_notify.consumer_name = consumer_name
    wh_notify.api_guid = api_guid
    wh_notify.event = event
    wh_notify.callback_url = url
    wh_notify.msg = msg
    notifications << wh_notify
  end
  ActiveRecord::Base.transaction { notifications.each(&:save!) }
  notifications
end

#register_events(*event, **keyword_args, &block) ⇒ Object

Raises:

  • (ArgumentError)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/webhooks/utilities.rb', line 54

def register_events(*event, **keyword_args, &block)
  raise ArgumentError, 'Block required to yield next execution time!' unless block_given?
  raise ArgumentError, 'api_name argument required' unless keyword_args.key? :api_name

  api_name = keyword_args[:api_name]
  max_retries = keyword_args[:max_retries]
  if Webhooks::Utilities.api_registered?(api_name)
    raise ArgumentError, "api name: #{api_name} previously registered!"
  end

  event.each do |e|
    Webhooks::Utilities.register_event(e)
    Webhooks::Utilities.register_name_to_event(api_name, e)
    Webhooks::Utilities.register_name_to_retries(api_name, max_retries)
    Webhooks::Utilities.register_name_to_time_block(api_name, block)
  end
end

#register_webhook(consumer_id, consumer_name, subscription, api_guid) ⇒ Object

We assume the subscription parameter has already been through validate_subscription()



12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/models/webhooks/utilities.rb', line 12

def register_webhook(consumer_id, consumer_name, subscription, api_guid)
  event = subscription['subscriptions'].first['event']
  api_name = Webhooks::Utilities.event_to_api_name[event]
  wh = Webhooks::Subscription.new
  wh.api_name = api_name
  wh.consumer_id = consumer_id
  wh.consumer_name = consumer_name
  wh.events = subscription
  wh.api_guid = api_guid if api_guid
  wh.save!
  wh
end