Skip to content

Instantly share code, notes, and snippets.

@steven-tey
Created July 29, 2024 23:00
Show Gist options
  • Save steven-tey/efb18503e3125b2d1524fd2579ff92e9 to your computer and use it in GitHub Desktop.
Save steven-tey/efb18503e3125b2d1524fd2579ff92e9 to your computer and use it in GitHub Desktop.
Retrieving `dclid` cookie in newsletter subscription and tracking a lead event with `dub`
# app/controllers/graphql_controller.rb
class GraphqlController < ApplicationController
def execute
# Reading the `dclid` cookie
dclid = cookies[:dclid]
# Handle the GraphQL query
variables = ensure_hash(params[:variables])
context = {
dclid: dclid, # pass dclid to the context
# other context variables
}
result = MySchema.execute(params[:query], variables: variables, context: context, operation_name: params[:operationName])
render json: result
end
private
def ensure_hash(ambiguous_param)
case ambiguous_param
when String
if ambiguous_param.present?
ensure_hash(JSON.parse(ambiguous_param))
else
{}
end
when Hash, ActionController::Parameters
ambiguous_param
when nil
{}
else
raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
end
end
end
# app/graphql/resolvers/newsletter_preferences_user_settings_update.rb
module Resolvers
class NewsletterPreferencesUserSettingsUpdate < BaseResolver
argument :input, Types::NewsletterPreferencesInputType, required: true
type Types::NewsletterPreferencesUserSettingsUpdateType
def resolve(input:)
dclid = context[:dclid]
# Initialize Dub client
s = ::OpenApiSDK::Dub.new
s.config_security(
::OpenApiSDK::Shared::Security.new(
token: "DUB_API_KEY",
)
)
# Create TrackLead request
req = ::OpenApiSDK::Operations::TrackLeadRequestBody.new(
click_id: dclid,
event_name: "Sign up",
customer_id: context[:current_user].id.to_s, # Assuming you have current_user in the context
)
# Track the lead
res = s.track.lead(req)
if res.object.nil?
raise GraphQL::ExecutionError, "Failed to track lead"
end
# Process the input and update the newsletter preferences
user = context[:current_user]
user.update!(input.to_h)
{ user: user }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment