Module: HTTPX::Plugins::ServerSentEvents::StreamResponseMethods

Defined in:
lib/httpx/plugins/server_sent_events.rb

Instance Method Summary collapse

Instance Method Details

#each_message(&block) ⇒ Object

yields each event Message as the server emits them.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/httpx/plugins/server_sent_events.rb', line 71

def each_message(&block)
  return enum_for(__method__) unless block

  payload = {}

  each_line do |line|
    if line.empty?
      if payload[:comment]
        payload.clear
        next
      end

      next if payload.empty?

      message = Message.new(**payload)

      payload.clear

      @request.last_server_sent_message = message

      yield message
    else
      type, value = line.split(": ", 2)

      case type
      when "data"
        type = type.to_sym
        if payload.key?(type)
          payload[type] << "\n" << value
        else
          payload[type] = value
        end
      when "id", "event", "retry"
        type = type.to_sym
        raise_format_error(line) if payload.key?(type) || value.empty?

        type = :retry_after if type == :retry # avoid using keyword

        payload[type] = value
      else
        # skip if it's a comment
        if line.start_with?(":")
          payload[:comment] = true
          next
        end

        raise_format_error(line)
      end
    end
  end
end