Class: Rhales::HydrationEndpoint
- Inherits:
-
Object
- Object
- Rhales::HydrationEndpoint
- 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’) ```
Instance Method Summary collapse
-
#cache_control_header ⇒ Object
private
-
#calculate_etag(template_name, additional_context = {}) ⇒ Object
Get ETag for current template data.
-
#cors_enabled? ⇒ Boolean
private
-
#cors_headers ⇒ Object
private
-
#create_template_context(additional_context) ⇒ Object
private
-
#data_changed?(template_name, etag, additional_context = {}) ⇒ Boolean
Check if template data has changed (for ETags).
-
#initialize(config, context = nil) ⇒ HydrationEndpoint
constructor
A new instance of HydrationEndpoint.
-
#json_headers(data) ⇒ Object
private
-
#jsonp_headers(data) ⇒ Object
private
-
#module_headers(data) ⇒ Object
private
-
#process_template_data(template_name, additional_context) ⇒ Object
private
-
#render_json(template_name, additional_context = {}) ⇒ Object
Render JSON response for API endpoints.
-
#render_jsonp(template_name, callback_name, additional_context = {}) ⇒ Object
Render JSONP response with callback.
-
#render_module(template_name, additional_context = {}) ⇒ Object
Render ES module response for modulepreload strategy.
Constructor Details
#initialize(config, context = nil) ⇒ HydrationEndpoint
Returns a new instance of HydrationEndpoint.
45 46 47 48 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 45 def initialize(config, context = nil) @config = config @context = context end |
Instance Method Details
#cache_control_header ⇒ Object (private)
194 195 196 197 198 199 200 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 194 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
120 121 122 123 124 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 120 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)
202 203 204 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 202 def cors_enabled? @config.hydration.cors_enabled || false end |
#cors_headers ⇒ Object (private)
206 207 208 209 210 211 212 213 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 206 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)
153 154 155 156 157 158 159 160 161 162 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 153 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)
114 115 116 117 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 114 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)
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 164 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)
188 189 190 191 192 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 188 def jsonp_headers(data) headers = json_headers(data) headers['Content-Type'] = 'application/javascript' headers end |
#module_headers(data) ⇒ Object (private)
182 183 184 185 186 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 182 def module_headers(data) headers = json_headers(data) headers['Content-Type'] = 'text/javascript' headers end |
#process_template_data(template_name, additional_context) ⇒ Object (private)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 128 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.}", template: template_name, timestamp: Time.now.iso8601, } } end |
#render_json(template_name, additional_context = {}) ⇒ Object
Render JSON response for API endpoints
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 86 87 88 89 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 51 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.}", 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.}", 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
103 104 105 106 107 108 109 110 111 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 103 def render_jsonp(template_name, callback_name, additional_context = {}) merged_data = process_template_data(template_name, additional_context) { content: "#{callback_name}(#{JSONSerializer.dump(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
92 93 94 95 96 97 98 99 100 |
# File 'lib/rhales/hydration/hydration_endpoint.rb', line 92 def render_module(template_name, additional_context = {}) merged_data = process_template_data(template_name, additional_context) { content: "export default #{JSONSerializer.dump(merged_data)};", content_type: 'text/javascript', headers: module_headers(merged_data) } end |