|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module ReactOnRailsPro |
| 4 | + class RscController < ApplicationController |
| 5 | + include ReactOnRails::Helper |
| 6 | + |
| 7 | + def render_rsc |
| 8 | + props = params[:props] || {} |
| 9 | + props_js = props_string(props).gsub("\u2028", '\u2028').gsub("\u2029", '\u2029') |
| 10 | + |
| 11 | + render_options = ReactOnRails::ReactComponent::RenderOptions.new( |
| 12 | + react_component_name: params[:componentName], |
| 13 | + options: { |
| 14 | + trace: true, |
| 15 | + replay_console: true, |
| 16 | + raise_on_prerender_error: true |
| 17 | + } |
| 18 | + ) |
| 19 | + |
| 20 | + ReactOnRails::ServerRenderingPool.reset_pool_if_server_bundle_was_modified |
| 21 | + |
| 22 | + js_code = |
| 23 | + <<-JS |
| 24 | + (function() { |
| 25 | + #{ReactOnRailsPro.configuration.ssr_pre_hook_js || ''} |
| 26 | + #{initialize_redux_stores} |
| 27 | + return ReactOnRails.renderReactServerComponent({ |
| 28 | + name: '#{params[:componentName]}', |
| 29 | + props: #{props_js}, |
| 30 | + throwJsErrors: #{ReactOnRailsPro.configuration.throw_js_errors}, |
| 31 | + renderingReturnsPromises: #{ReactOnRailsPro.configuration.rendering_returns_promises}, |
| 32 | + }); |
| 33 | + })() |
| 34 | + JS |
| 35 | + |
| 36 | + begin |
| 37 | + result = ReactOnRails::ServerRenderingPool.server_render_js_with_console_logging(js_code, render_options) |
| 38 | + rescue StandardError => e |
| 39 | + # This error came from the renderer |
| 40 | + raise ReactOnRails::PrerenderError.new(component_name: params[:componentName], |
| 41 | + # Sanitize as this might be browser logged |
| 42 | + props: sanitized_props_string(props), |
| 43 | + err: e, |
| 44 | + js_code: js_code) |
| 45 | + end |
| 46 | + |
| 47 | + if result["hasErrors"] && render_options.raise_on_prerender_error |
| 48 | + # We caught this exception on our backtrace handler |
| 49 | + raise ReactOnRails::PrerenderError.new(component_name: params[:componentName], |
| 50 | + # Sanitize as this might be browser logged |
| 51 | + props: sanitized_props_string(props), |
| 52 | + err: nil, |
| 53 | + js_code: js_code, |
| 54 | + console_messages: result["consoleReplayScript"]) |
| 55 | + |
| 56 | + end |
| 57 | + |
| 58 | + render plain: result["html"] |
| 59 | + end |
| 60 | + end |
| 61 | +end |
0 commit comments