module HTTPX::Plugins::ServerSentEvents::StreamResponseMethods

  1. lib/httpx/plugins/server_sent_events.rb

Methods

Public Instance

  1. each_message

Public Instance methods

each_message(&block)

yields each event Message as the server emits them.

[show source]
    # File lib/httpx/plugins/server_sent_events.rb
 72 def each_message(&block)
 73   return enum_for(__method__) unless block
 74 
 75   payload = {}
 76 
 77   each_line do |line|
 78     if line.empty?
 79       if payload[:comment]
 80         payload.clear
 81         next
 82       end
 83 
 84       next if payload.empty?
 85 
 86       message = Message.new(**payload)
 87 
 88       payload.clear
 89 
 90       @request.last_server_sent_message = message
 91 
 92       yield message
 93     else
 94       type, value = line.split(": ", 2)
 95 
 96       case type
 97       when "data"
 98         type = type.to_sym
 99         if payload.key?(type)
100           payload[type] << "\n" << value
101         else
102           payload[type] = value
103         end
104       when "id", "event", "retry"
105         type = type.to_sym
106         raise_format_error(line) if payload.key?(type) || value.empty?
107 
108         type = :retry_after if type == :retry # avoid using keyword
109 
110         payload[type] = value
111       else
112         # skip if it's a comment
113         if line.start_with?(":")
114           payload[:comment] = true
115           next
116         end
117 
118         raise_format_error(line)
119       end
120     end
121   end
122 end