summaryrefslogtreecommitdiff
path: root/lib/pager_duty/webhook_payload_parser.rb
blob: c17e3df1a724e04b9cb0004072de21294359173d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true

module PagerDuty
  class WebhookPayloadParser
    SCHEMA_PATH = Rails.root.join('lib', 'pager_duty', 'validator', 'schemas', 'message.json')

    def initialize(payload)
      @payload = payload
    end

    def self.call(payload)
      new(payload).call
    end

    def call
      Array(payload['messages']).map { |msg| parse_message(msg) }.reject(&:empty?)
    end

    private

    attr_reader :payload

    def parse_message(message)
      return {} unless valid_message?(message)

      {
        'event' => message['event'],
        'incident' => parse_incident(message['incident'])
      }
    end

    def parse_incident(incident)
      {
        'url' => incident['html_url'],
        'incident_number' => incident['incident_number'],
        'title' => incident['title'],
        'status' => incident['status'],
        'created_at' => incident['created_at'],
        'urgency' => incident['urgency'],
        'incident_key' => incident['incident_key'],
        'assignees' => reject_empty(parse_assignees(incident)),
        'impacted_services' => reject_empty(parse_impacted_services(incident))
      }
    end

    def parse_assignees(incident)
      Array(incident['assignments']).map do |a|
        {
          'summary' => a.dig('assignee', 'summary'),
          'url' => a.dig('assignee', 'html_url')
        }
      end
    end

    def parse_impacted_services(incident)
      Array(incident['impacted_services']).map do |is|
        {
          'summary' => is['summary'],
          'url' => is['html_url']
        }
      end
    end

    def reject_empty(entities)
      Array(entities).reject { |e| e['summary'].blank? && e['url'].blank? }
    end

    def valid_message?(message)
      ::JSONSchemer.schema(SCHEMA_PATH).valid?(message)
    end
  end
end