Skip to content

Latest commit

 

History

History
163 lines (118 loc) · 3.04 KB

hh.ex.md

File metadata and controls

163 lines (118 loc) · 3.04 KB
title theme revealOptions
Luke
black
controls transition
false
slide

Luke

Render React Elements with Cowboy and Plug

or how to make cowboy take milliseconds to respond


Plug in Baby

  • `Plug.Adapter` for the cowboy web server
  • Convient `child_spec` for being supervised
  • `Plug.Router` entrypoint

The Router

Plug bundles different plugs and macros

  • `Plug.Static`
  • `Plug.Logger`
  • `:match` and `:dispatch`

Route Splitting

  forward "/api", to: Luke.ApiRouter
  forward "/", to: Luke.ReactRouter

The API

defmodule Luke.ApiRouter do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    conn |> send_resp(200, "soon to be api resp")
  end
 
  match _ do
    conn |> send_resp(501, "Not implemented")
  end
end

Rendering

  • Rendering: Fork of `react-stdio`
  • Routing: `react-router@4`
  • Communicating: `StdJsonIo`

Workings

  Conn
    |> Plug.Router
    |> Luke.ReactRouter
    |> StdJsonIo(component, props)
    --- nodejs ---
    JSONStream |> React.renderToString() |> JSONStream
    --- nodejs ---
    |> Luke.ReactRouter
    |> send_resp

react_router.ex

%{"html" => html, "context" => context} = 
  StdJsonIo.json_call!(
    %{
      "component" => "priv/react-router.js",
      "props" => %{
        "location" => location
      }
    }
  )

react-router.js

const context = {}

const Router = ({ location }) => (
  <StaticRouter location={location} context={context}>
    <App />
  </StaticRouter>
)

Router.context = context
module.exports = Router

Routing and ctx

const App = () => (
  <Switch>
    ...
    <Route component={NotFound} />
  </Switch>
)
const NotFound = ({ staticContext = {} }) => {
  staticContext.status = 404

  return <h3>Sorry, we took a wrong turn.</h3>
}

TIL

  • Foundations: No Phoenix
  • Supervisors and child specs
  • Power and simplicty of Plug

TBC

  • Database
  • Async data fetching during render
  • Having @mjackson merge my PR