Class: WebhookSystem::Job

Inherits:
ActiveJob::Base
  • Object
show all
Defined in:
lib/webhook_system/job.rb

Overview

This is the ActiveJob in charge of actually sending each event

Defined Under Namespace

Classes: RequestFailed

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build_client ⇒ Object



46
47
48
49
50
51
# File 'lib/webhook_system/job.rb', line 46

def self.build_client
  Faraday.new do |faraday|
    faraday.response :logger if ENV['WEBHOOK_DEBUG']
    faraday.adapter Faraday.default_adapter
  end
end

.build_request(client, subscription, event) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/webhook_system/job.rb', line 33

def self.build_request(client, subscription, event)
  payload = Encoder.encode(subscription.secret, event)
  client.build_request(:post) do |req|
    req.url subscription.url
    req.headers['Content-Type'] = 'application/json; base64+aes256'
    req.body = payload.to_s
  end
end

.ensure_success(response) ⇒ Object



26
27
28
29
30
31
# File 'lib/webhook_system/job.rb', line 26

def self.ensure_success(response)
  status = response.status
  unless status == 200
    raise RequestFailed.new("request failed with code: #{status}", status)
  end
end

.log_response(subscription, event, request, response) ⇒ Object



42
43
44
# File 'lib/webhook_system/job.rb', line 42

def self.log_response(subscription, event, request, response)
  EventLog.construct(subscription, event, request, response).save!
end

.post(subscription, event) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/webhook_system/job.rb', line 18

def self.post(subscription, event)
  client = build_client
  request = build_request(client, subscription, event)
  response = client.builder.build_response(client, request)
  log_response(subscription, event, request, response)
  ensure_success(response)
end

Instance Method Details

#perform(subscription, event) ⇒ Object



14
15
16
# File 'lib/webhook_system/job.rb', line 14

def perform(subscription, event)
  self.class.post(subscription, event)
end