scinote-web/app/services/webhook_service.rb

54 lines
1 KiB
Ruby
Raw Normal View History

2021-06-17 20:54:30 +08:00
# frozen_string_literal: true
class WebhookService
class InactiveWebhookSendException < StandardError; end
class RequestFailureException < StandardError; end
2021-06-17 20:54:30 +08:00
def initialize(webhook, payload)
@webhook = webhook
@payload = payload
end
def send_webhook
unless @webhook.active?
raise(
InactiveWebhookSendException,
2021-06-30 19:15:08 +08:00
'Refused to send inactive webhook.'
2021-06-17 20:54:30 +08:00
)
end
2021-06-18 04:00:13 +08:00
response = HTTParty.public_send(
2021-06-17 20:54:30 +08:00
@webhook.http_method,
@webhook.url,
{
headers: { 'Content-Type' => 'application/json' },
body: @payload.to_json
2021-06-17 20:54:30 +08:00
}
)
unless response.success?
error_description = "#{response.code}: #{response.message}"
log_error!(error_description)
raise(
RequestFailureException,
error_description
)
end
2021-06-17 20:54:30 +08:00
response
2021-06-18 04:00:13 +08:00
rescue Net::ReadTimeout, Net::OpenTimeout, SocketError => e
log_error!(e)
raise e
2021-06-17 20:54:30 +08:00
end
private
def log_error!(message)
@webhook.update!(
2021-06-17 20:54:30 +08:00
last_error: message
)
end
end