Last active
November 12, 2024 15:45
-
-
Save Sdy603/cd1d4761be12f245c4120dc2bec817fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/services/dx_event_sender.rb | |
require 'net/http' | |
require 'uri' | |
require 'json' | |
class DxEventSender | |
DX_API_URL = 'https://api.getdx.com/events.track' | |
def initialize(event_name, user_email, timestamp = Time.now.to_i) | |
@event_name = event_name | |
@user_email = user_email | |
@timestamp = timestamp | |
end | |
def call | |
uri = URI.parse(DX_API_URL) | |
request = Net::HTTP::Post.new(uri) | |
request.content_type = 'application/json' | |
request['Authorization'] = "Bearer #{ENV['DX_API_KEY']}" | |
request.body = { | |
name: @event_name, | |
email: @user_email, | |
timestamp: @timestamp | |
}.to_json | |
send_request(uri, request) | |
end | |
private | |
def send_request(uri, request) | |
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| | |
http.request(request) | |
end | |
log_response(response) | |
response | |
rescue StandardError => e | |
Rails.logger.error("Failed to send event to DX: #{e.message}") | |
nil | |
end | |
def log_response(response) | |
if response.is_a?(Net::HTTPSuccess) | |
Rails.logger.info("Event sent successfully: #{@event_name}") | |
else | |
Rails.logger.warn("Failed to send event: #{response.code} #{response.message}") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment