Skip to content

Instantly share code, notes, and snippets.

@lemuelbarango
Last active June 12, 2020 19:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lemuelbarango/1ba2535f5f620e5758eb201c018d709a to your computer and use it in GitHub Desktop.
Save lemuelbarango/1ba2535f5f620e5758eb201c018d709a to your computer and use it in GitHub Desktop.
GraphQL Ruby Webhook Subscriptions Implementation
require 'graphql'
require 'securerandom'
require 'httparty'
class WebhookSubscriptions < GraphQL::Subscriptions
def initialize(**args)
super
# Using concurrent maps to persist events and subscription information
# This can be switched for a DATABASE table/columns
@events = Concurrent::Map.new { |h, event_id| h[event_id] = [] }
@subscriptions = Concurrent::Map.new { |h, subscription_id| h[subscription_id] = {} }
end
def each_subscription_id(event)
@events[event.name].each_with_index do |subscription_id|
yield(subscription_id)
end
end
def read_subscription(subscription_id)
query = @subscriptions[subscription_id][:query]
{
query_string: query.query_string,
variables: query.provided_variables,
context: query.context,
operation_name: query.operation_name,
}
end
def deliver(subscription_id, result)
payload = { result: result.to_h, more: true }
# Webhook callback could be dynamic, based on the subscription id.
HTTParty.post(
{{WEBHOOK_CALLBACK_URL}},
headers: {
"Content-Type" => "application/json",
},
body: payload
)
end
def write_subscription(query, events)
events.each do |ev|
subscription_id = SecureRandom.uuid
@events[ev.name] << subscription_id
@subscriptions[subscription_id] = { query: query }
end
end
end
@lemuelbarango
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment