Class: RailsReactSSR::ServerRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_react_ssr/server_runner.rb

Overview

Executes the ReactJS package using NodeJS that was built using webpacker

Constant Summary collapse

CONSOLE_POLYFILL =

Redirect console output to be logged by an array

<<-CONSOLE_POLYFILL
const stdout = console.log;
const stderr = console.error;

const recordedLogs = [];

['log', 'info', 'debug', 'warn', 'error'].forEach(level => {
console[level] = (...args) => {
    recordedLogs.push({ level: level, args: args });
}
});
CONSOLE_POLYFILL

Class Method Summary collapse

Class Method Details

.exec!(bundle, props: {}, outputTemp: false, max_tries: 10, delay: 1000) ⇒ Object

Execute the bundled package

:props - The properties to pass to the server JS code :outputTemp - If true, output the compiled bundle to the tmp/ssr directory, pass a string to specify the

output file

:max_tries - The number of tries when getting the bundle from the webpack dev server :delay - The delay in ms between tries



35
36
37
38
39
40
41
42
43
44
45
46
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
# File 'lib/rails_react_ssr/server_runner.rb', line 35

def self.exec!(bundle, props: {}, outputTemp: false, max_tries: 10, delay: 1000)
  bundle_file = RailsReactSSR::WebpackerUtils.open_bundle bundle, max_tries: max_tries, delay: delay

  status = 0
  output = nil

  begin
    js = Tempfile.new [File.basename(bundle_file, '.*'), File.extname(bundle_file)]

    begin
      write_console_polyfill js
      write_props_polyfill js, props
      write_bundle js, bundle_file

      js.flush

      if outputTemp
        outputTemp = Rails.root.join('tmp/ssr/', bundle) if outputTemp.is_a? TrueClass

        Rails.logger.debug "Coping server bundle to #{outputTemp}"
        IO.copy_stream js.path, outputTemp
      end

      status, output = exec_contents js
    ensure
      js.unlink
    end
  rescue => e
    Rails.logger.error "Unable to execute the bundle '#{bundle}': #{e.message}"
    raise RailsReactSSR::ExecutionError.new(bundle, "Unable to run the bundle '#{bundle}'")
  ensure
    bundle_file.close
  end

  raise RailsReactSSR::ExecutionError.new(bundle,"Unable to execute the server bundle #{bundle}") unless status.zero?

  output
end