Class: Rhales::HydrationEndpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/rhales/hydration/hydration_endpoint.rb

Overview

Handles API endpoint responses for link-based hydration strategies

Provides JSON and ES module endpoints that serve hydration data separately from HTML templates, enabling better caching, parallel loading, and reduced HTML payload sizes.

Supported Response Formats

JSON Response (application/json)

json { "myData": { "user": "john", "theme": "dark" }, "config": { "apiUrl": "https://api.example.com" } }

ES Module Response (text/javascript)

javascript export default { "myData": { "user": "john", "theme": "dark" }, "config": { "apiUrl": "https://api.example.com" } };

Usage

```ruby endpoint = HydrationEndpoint.new(config, context)

JSON response

json_response = endpoint.render_json(‘template_name’)

ES Module response

module_response = endpoint.render_module(‘template_name’) ```

Constant Summary collapse

CALLBACK_NAME_PATTERN =

Valid JSONP callback names: a JS identifier or dotted member path (e.g. “handleData”, “app.callbacks.handleData”). Each dotted segment must be its own valid identifier, so malformed paths like “foo.”, “foo..bar” or “foo.1bar” are rejected rather than producing unusable JSONP. Anything outside this set could break out of the callback invocation and inject script.

/\A[a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*\z/

Instance Method Summary collapse

Constructor Details

#initialize(config, context = nil) ⇒ HydrationEndpoint

Returns a new instance of HydrationEndpoint.



53
54
55
56
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 53

def initialize(config, context = nil)
  @config = config
  @context = context
end

Instance Method Details

#cache_control_headerObject (private)



210
211
212
213
214
215
216
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 210

def cache_control_header
  if @config.hydration.api_cache_enabled
    "public, max-age=#{@config.hydration.api_cache_ttl || 300}"
  else
    "no-cache, no-store, must-revalidate"
  end
end

#calculate_etag(template_name, additional_context = {}) ⇒ Object

Get ETag for current template data



136
137
138
139
140
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 136

def calculate_etag(template_name, additional_context = {})
  merged_data = process_template_data(template_name, additional_context)
  # Simple ETag based on data hash
  Digest::MD5.hexdigest(JSONSerializer.dump(merged_data))
end

#cors_enabled?Boolean (private)

Returns:



218
219
220
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 218

def cors_enabled?
  @config.hydration.cors_enabled || false
end

#cors_headersObject (private)



222
223
224
225
226
227
228
229
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 222

def cors_headers
  {
    'Access-Control-Allow-Origin' => @config.hydration.cors_origin || '*',
    'Access-Control-Allow-Methods' => 'GET, HEAD, OPTIONS',
    'Access-Control-Allow-Headers' => 'Accept, Accept-Encoding, Authorization',
    'Access-Control-Max-Age' => '86400'
  }
end

#create_template_context(additional_context) ⇒ Object (private)



169
170
171
172
173
174
175
176
177
178
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 169

def create_template_context(additional_context)
  if @context
    # Merge additional context into existing context by reconstructing with merged props
    merged_props = @context.client.merge(additional_context)
    @context.class.for_view(@context.req, @context.locale, **merged_props)
  else
    # Create minimal context with just the additional data
    Context.minimal(client: additional_context)
  end
end

#data_changed?(template_name, etag, additional_context = {}) ⇒ Boolean

Check if template data has changed (for ETags)

Returns:



130
131
132
133
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 130

def data_changed?(template_name, etag, additional_context = {})
  current_etag = calculate_etag(template_name, additional_context)
  current_etag != etag
end

#json_headers(data) ⇒ Object (private)



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 180

def json_headers(data)
  headers = {
    'Content-Type' => 'application/json',
    'Cache-Control' => cache_control_header,
    'Vary' => 'Accept, Accept-Encoding'
  }

  # Add CORS headers if enabled
  if cors_enabled?
    headers.merge!(cors_headers)
  end

  # Add ETag for caching
  headers['ETag'] = %("#{Digest::MD5.hexdigest(JSONSerializer.dump(data))}")

  headers
end

#jsonp_headers(data) ⇒ Object (private)



204
205
206
207
208
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 204

def jsonp_headers(data)
  headers = json_headers(data)
  headers['Content-Type'] = 'application/javascript'
  headers
end

#module_headers(data) ⇒ Object (private)



198
199
200
201
202
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 198

def module_headers(data)
  headers = json_headers(data)
  headers['Content-Type'] = 'text/javascript'
  headers
end

#process_template_data(template_name, additional_context) ⇒ Object (private)



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 144

def process_template_data(template_name, additional_context)
  # Create a minimal context for data processing
  template_context = create_template_context(additional_context)

  # Process template to extract hydration data
  view = View.new(@context.req, client: {})
  aggregator = HydrationDataAggregator.new(template_context)

  # Build composition to get template dependencies
  composition = view.send(:build_view_composition, template_name)
  composition.resolve!

  # Aggregate data from all templates in the composition
  aggregator.aggregate(composition)
rescue StandardError => ex
  # Return error structure that can be serialized
  {
    error: {
      message: "Failed to process template data: #{ex.message}",
      template: template_name,
      timestamp: Time.now.iso8601,
    }
  }
end

#render_json(template_name, additional_context = {}) ⇒ Object

Render JSON response for API endpoints



59
60
61
62
63
64
65
66
67
68
69
70
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
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 59

def render_json(template_name, additional_context = {})
  merged_data = process_template_data(template_name, additional_context)

  {
    content: JSONSerializer.dump(merged_data),
    content_type: 'application/json',
    headers: json_headers(merged_data)
  }
rescue JSON::NestingError, JSON::GeneratorError, ArgumentError, Encoding::UndefinedConversionError => e
  # Handle JSON serialization errors and encoding issues
  error_data = {
    error: {
      message: "Failed to serialize data to JSON: #{e.message}",
      template: template_name,
      timestamp: Time.now.iso8601
    }
  }

  {
    content: JSONSerializer.dump(error_data),
    content_type: 'application/json',
    headers: json_headers(error_data)
  }
rescue StandardError => e
  # Handle any other unexpected errors during JSON generation
  error_data = {
    error: {
      message: "Unexpected error during JSON generation: #{e.message}",
      template: template_name,
      timestamp: Time.now.iso8601
    }
  }

  {
    content: JSONSerializer.dump(error_data),
    content_type: 'application/json',
    headers: json_headers(error_data)
  }
end

#render_jsonp(template_name, callback_name, additional_context = {}) ⇒ Object

Render JSONP response with callback

The callback name is reflected directly into the executable response body, so it must be validated before use. Without validation a caller supplying something like “alert(1)//” would inject arbitrary JavaScript.



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 115

def render_jsonp(template_name, callback_name, additional_context = {})
  unless callback_name.is_a?(String) && callback_name.match?(CALLBACK_NAME_PATTERN)
    raise ArgumentError, "Invalid callback: #{callback_name.inspect}"
  end

  merged_data = process_template_data(template_name, additional_context)

  {
    content: "#{callback_name}(#{JSONSerializer.dump_html_safe(merged_data)});",
    content_type: 'application/javascript',
    headers: jsonp_headers(merged_data),
  }
end

#render_module(template_name, additional_context = {}) ⇒ Object

Render ES module response for modulepreload strategy



100
101
102
103
104
105
106
107
108
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 100

def render_module(template_name, additional_context = {})
  merged_data = process_template_data(template_name, additional_context)

  {
    content: "export default #{JSONSerializer.dump_html_safe(merged_data)};",
    content_type: 'text/javascript',
    headers: module_headers(merged_data)
  }
end