Module: Manceps::SSEParser

Defined in:
lib/manceps/sse_parser.rb

Overview

Parser for Server-Sent Events streams.

Class Method Summary collapse

Class Method Details

.extract_json(body) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/manceps/sse_parser.rb', line 10

def extract_json(body)
  return nil if body.nil? || body.strip.empty?

  data_lines = body.each_line.filter_map do |line|
    line.strip.start_with?('data:') ? line.strip.sub(/\Adata:\s?/, '') : nil
  end

  return nil if data_lines.empty?

  JSON.parse(data_lines.join)
end

.parse_events(body) ⇒ Object



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
# File 'lib/manceps/sse_parser.rb', line 22

def parse_events(body)
  return [] if body.nil? || body.strip.empty?

  events = []
  current = { id: nil, event: nil, data: [] }

  body.each_line do |raw_line|
    line = raw_line.chomp

    if line.empty?
      unless current[:data].empty?
        events << {
          id: current[:id],
          event: current[:event],
          data: current[:data].join("\n")
        }
      end
      current = { id: nil, event: nil, data: [] }
      next
    end

    if line.start_with?('id:')
      current[:id] = line.sub(/\Aid:\s?/, '')
    elsif line.start_with?('event:')
      current[:event] = line.sub(/\Aevent:\s?/, '')
    elsif line.start_with?('data:')
      current[:data] << line.sub(/\Adata:\s?/, '')
    end
  end

  # Flush any trailing event without a final blank line
  unless current[:data].empty?
    events << {
      id: current[:id],
      event: current[:event],
      data: current[:data].join("\n")
    }
  end

  events
end