Module: PostProxy::WebhookEvents

Defined in:
lib/postproxy/webhook_events.rb

Defined Under Namespace

Classes: CommentCreatedData, Event, ImportedProfile, MediaFailedData, PlatformPostData, PostImportedData, PostProcessedData, PostProcessedPlatform, ProfileEventData, ProfileStatsData

Constant Summary collapse

DATA_CLASSES =
{
  "post.processed" => PostProcessedData,
  "post.imported" => PostImportedData,
  "platform_post.published" => PlatformPostData,
  "platform_post.failed" => PlatformPostData,
  "platform_post.failed_waiting_for_retry" => PlatformPostData,
  "platform_post.insights" => PlatformPostData,
  "profile.connected" => ProfileEventData,
  "profile.disconnected" => ProfileEventData,
  "profile.stats" => ProfileStatsData,
  "media.failed" => MediaFailedData,
  "comment.created" => CommentCreatedData
}.freeze

Class Method Summary collapse

Class Method Details

.parse(body) ⇒ Object

Parse a webhook body and return a typed Event. ‘data` is parsed into the appropriate model based on `type`. Raises WebhookParseError on bad input.



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/postproxy/webhook_events.rb', line 90

def self.parse(body)
  parsed =
    case body
    when String then JSON.parse(body, symbolize_names: true)
    when Hash then body.transform_keys(&:to_sym)
    else raise WebhookParseError, "Webhook body must be a String or Hash"
    end
rescue JSON::ParserError => e
  raise WebhookParseError, "Invalid JSON: #{e.message}"
else
  type = parsed[:type].to_s
  raise WebhookParseError, "Unknown webhook event type: #{type.inspect}" unless DATA_CLASSES.key?(type)

  data_class = DATA_CLASSES[type]
  data_hash = (parsed[:data] || {}).transform_keys(&:to_sym)
  Event.new(
    id: parsed[:id],
    type: type,
    created_at: parsed[:created_at],
    data: data_class.new(**data_hash)
  )
end