Class: Rhales::HydrationEndpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/rhales/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’) ```

Instance Method Summary collapse

Constructor Details

#initialize(config, context = nil) ⇒ HydrationEndpoint

Returns a new instance of HydrationEndpoint.



41
42
43
44
# File 'lib/rhales/hydration_endpoint.rb', line 41

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

Instance Method Details

#cache_control_headerObject (private)



190
191
192
193
194
195
196
# File 'lib/rhales/hydration_endpoint.rb', line 190

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



116
117
118
119
120
# File 'lib/rhales/hydration_endpoint.rb', line 116

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(JSON.generate(merged_data))
end

#cors_enabled?Boolean (private)

Returns:

  • (Boolean)


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

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

#cors_headersObject (private)



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

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)



149
150
151
152
153
154
155
156
157
158
# File 'lib/rhales/hydration_endpoint.rb', line 149

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

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

Check if template data has changed (for ETags)

Returns:

  • (Boolean)


110
111
112
113
# File 'lib/rhales/hydration_endpoint.rb', line 110

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)



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/rhales/hydration_endpoint.rb', line 160

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(JSON.generate(data))}")

  headers
end

#jsonp_headers(data) ⇒ Object (private)



184
185
186
187
188
# File 'lib/rhales/hydration_endpoint.rb', line 184

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

#module_headers(data) ⇒ Object (private)



178
179
180
181
182
# File 'lib/rhales/hydration_endpoint.rb', line 178

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

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



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/rhales/hydration_endpoint.rb', line 124

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, @context.sess, @context.cust, @context.locale, props: {})
  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



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
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rhales/hydration_endpoint.rb', line 47

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

  {
    content: JSON.generate(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: JSON.generate(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: JSON.generate(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



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

def render_jsonp(template_name, callback_name, additional_context = {})
  merged_data = process_template_data(template_name, additional_context)

  {
    content: "#{callback_name}(#{JSON.generate(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



88
89
90
91
92
93
94
95
96
# File 'lib/rhales/hydration_endpoint.rb', line 88

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

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