Last active
June 12, 2020 19:47
-
-
Save lemuelbarango/1ba2535f5f620e5758eb201c018d709a to your computer and use it in GitHub Desktop.
GraphQL Ruby Webhook Subscriptions Implementation
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GraphQL Ruby: Subscriptions Transport — Webhooks