<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roman Chvanikov on Medium]]></title>
        <description><![CDATA[Stories by Roman Chvanikov on Medium]]></description>
        <link>https://medium.com/@chvanikoff?source=rss-b729aa603207------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j8E_KuLeCWdf5Mfr.png</url>
            <title>Stories by Roman Chvanikov on Medium</title>
            <link>https://medium.com/@chvanikoff?source=rss-b729aa603207------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:29:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chvanikoff/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RePh: React + Phoenix app scaffolding made easy]]></title>
            <link>https://medium.com/@chvanikoff/reph-react-phoenix-app-scaffolding-made-easy-346cddc76838?source=rss-b729aa603207------2</link>
            <guid isPermaLink="false">https://medium.com/p/346cddc76838</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Roman Chvanikov]]></dc:creator>
            <pubDate>Tue, 20 Jun 2017 09:53:10 GMT</pubDate>
            <atom:updated>2017-06-20T09:53:10.103Z</atom:updated>
            <content:encoded><![CDATA[<p>Long ago I wrote couple of articles about building RePh-stack based apps. It could be not that simple to follow due to dependencies became obsolete, backward-incompatible and many other reasons. I love RePh stack and pretty much sure it’s something everyone should consider when developing an app which interacts a lot with user on client side and I’ve created a lot of such apps, but often there was so much of boilerplate I had to copy-paste from previous apps... Finally I got tired of it and decided to create a mix reph.new generator which will act same way as mix phx.new but add all the boilerplate I need for React to integrate. The project repo can be found here: <a href="https://github.com/reph-stack/reph">https://github.com/reph-stack/reph</a>. In future I’ll probably add ability to generate simple commonly-used pieces of apps like authentication and admin page, but today I’m going to tell you about what mix reph.new task already have.</p><p>Primary components RePh stack includes are:</p><ul><li>Phoenix 1.3</li><li>React</li><li>React Server-side rendering (SSR)</li><li>Less</li><li>Webpack 2</li></ul><h3>mix reph.new</h3><p>This task is very similar to mix phx.new, it is based on Phoenix 1.3-rc installer and support all it’s arguments except for --no-brunch, --no-html, --dev and --ecto. To use the task, it have to be first installed. It can be achieved in a few ways, but the simplest is following:</p><pre>mix archive.install github reph-stack/reph</pre><p>Now you have reph.new task globally available and can use it wherever you want. Let’s generate a demo app and see what’s going on in there:</p><pre>mix reph.new demo_app --module=DA<br>cd demo_app</pre><p>First, you can run tests to compile the app for test environment and to ensure everything is fine. test/test_helper.exs file have instructions to recompile JS assets every time you run tests, so as soon as you run mix test, webpack will compile your assets and since we have server-side rendering (SSR), we can even test against what JS will produce for different requests in our Elixir tests. Unfortunately it costs a few seconds and bigger your app gets, more time it takes to compile so you can choose to either remove code for recompilation, or add your desired logic to cache compiled files between test runs. Some day I’ll probably try to resolve this.</p><p>Next, you can run mix phx.server as for regular Phoenix application and check out you’ve got React code rendered into your page at <a href="http://localhost:4000/">http://localhost:4000</a>.</p><h3>Webpack</h3><p>In assets/ directory there’s a webpack.config.js file responsible for assembling your assets. It consists of 2 configs: one for client-side bundle assembling and another for server-side. If you are not new to Webpack, feel free to update it, otherwise I think defaults should be good to start with.</p><h3>Styles</h3><p>In Phoenix you had a few .css files generated by default, in RePh you can use either .css or .less; also you can update webpack.config.js to include another (say SASS) styles processor and use it. This is why we have assets/styles directory in RePh rather than assets/css. By default, RePh app will include 3 style files: styles/index.less, which includesstyles/app.less and styles/phoenix.css. phoenix.css is default Phoenix styles based on Bootstrap and app.less is for your custom styles, feel free to create more and include it to styles/index.less. Bootstrap was moved out of assets in favour of CDN version (I believe it’s a better approach) however you can easily embed it into your project by adding bootstrap contents into assets/bootstrap.css and then include it into assets/index.less with <a href="http://twitter.com/import">@import</a> &quot;app.less&quot;;</p><h3>JS</h3><p>assets/js directory is the hearth of our React app. index.js is entrypoint for client-side bundle while server-side bundle have containers/index.js as the one. Application have 1 pre-set reducer reducers/ws.js which is responsible for websocket connection and channels management and 1 pre-set action actions/ws.js responsible for logic of working with the reducer. In the actions/ws.js you can connect to channels you need when page loads:</p><pre>const actions = {<br>  init: () =&gt; {<br>    return (dispatch, getState) =&gt; {<br>      dispatch(actions.socket_connect());<br>      const blog_params = {};<br>      dispatch(actions.channel_join(<br>        &quot;blog:no_category&quot;,<br>        &quot;blog&quot;,<br>        blog_params));<br>    }<br>  }<br>  //...<br>};</pre><p>As you can see, actions.channel_join takes 3 arguments. First is channel “address” — the one you use to connect to it, second is name — this is how you call it on client side, and the last is params to be passed to channel init function. Also, you can define callbacks in setupHandlers function. For example:</p><pre>const setupHandlers = (name, channel, dispatch, getState) =&gt; {<br>  switch (name) {<br>    // &quot;blog&quot; is channel name defined in call to &quot;channel_join&quot;<br>    case &quot;blog&quot;:<br>      channel.on(&quot;post_new&quot;, (data) =&gt; {<br>        // do something with data<br>      });<br>      break;<br>    default:<br>      break;<br>  }<br>};</pre><p>Application also have 2 basic components — components/Main and components/Header and 1 wrapper around it — containers/App. All three creates UI for the Phoenix default page you see at <a href="http://localhost:4000/">http://localhost:4000</a>. Store located in store/index.js is a key component of React app responsible for SSR working properly and in most cases you wouldn’t need to change it unless you’ve got serious and that way you obviously know what and how to do.</p><p>Now you can start writing your RePh apps with much less efforts :)</p><h3>P.S.</h3><p>If you like the project or feel like there should be something else in it, feel free to drop me a message or open an issue in the project repo. I hope you will love RePh stack as much as I do :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=346cddc76838" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s refactor: std_json_io.]]></title>
            <link>https://medium.com/@chvanikoff/lets-refactor-std-json-io-e444b6f2c580?source=rss-b729aa603207------2</link>
            <guid isPermaLink="false">https://medium.com/p/e444b6f2c580</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Roman Chvanikov]]></dc:creator>
            <pubDate>Sun, 07 May 2017 13:31:52 GMT</pubDate>
            <atom:updated>2017-05-16T12:51:39.880Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I finished refactoring of <a href="https://github.com/hassox/std_json_io">std_json_io</a> library (the fork can be found at <a href="https://github.com/chvanikoff/std_json_io">https://github.com/chvanikoff/std_json_io</a> with all the commits mentioned in the article in place, Pull request to the original library is <a href="https://github.com/hassox/std_json_io/pull/13">here</a>) and would like to share experience of “how it was”.<br>std_json_io is a nice library for Elixir which is responsible for requesting external scripts which read JSON-input from STDIN and write JSON-output to STDOUT. The library is oftenly used for communication with <a href="https://github.com/mjackson/react-stdio">react-stdio</a> to achieve server-side rendering of React JS code. Usage is following: call StdJsonIo.json_call(%{component: &quot;my/server/js/component.js&quot;, props: %{}}), StdJsonIo encodes data to JSON and send it (via <a href="https://github.com/alco/porcelain">Porcelain</a> library) to react-stdio’s STDIN, it returns compiled html to STDOUT, StdJsonIo gets the output (via Porcelain) and returns it to caller.<br>What’s wrong with the original version?</p><ol><li>Ability to handle response from react-stdio larger than 64KB: if response is &gt;64KB, it is sent to StdJsonIo in chunks which it can’t handle.</li><li>Requirement to create additional module in your app to use the library: of course it can be necessary in many cases, but as we’ll see later, StdJsonIo is not the one.</li><li>Requirement to add StdJsonIo supervisor to your app supervision tree — I think such kind of apps should be designed as OTP Applications and have it’s own supervision tree.</li><li>Outdated dependencies: it is usually bad to depend on outdated libraries, but who knows if we can painlessly upgrade the deps if…</li><li>…Tests are absent. This one is the most important. It is impossible for software to not become legacy if it have no tests. I can’t even update dependencies and make sure everything works as before or figure out what got broken after update. I can’t be sure library is functional in the way it is supposed to be. I have to test every change manually and deal with a lot of assumptions which of course slows down development process significantly.</li><li>Elixir compiler shows up some warnings in compile time and it’s a good idea to fix that.</li><li>StdJsonIo.Reloader is useless. Since primary target for std_json_io is <em>react-stdio,</em> it is aimed to restart connections with a script when (server-side) js is updated. But there’s no point since we send a file path to react-stdio and it will return us a new response as soon as file changed despite using old connections, so the Reloader does nothing good but confusing library users. Restarting connections with a script may only be useful when the script itself changes, which is controversially. So, I’m going to remove Reloader at all.</li><li>And there’s always more being found during refactoring :)</li></ol><p>Now when problems are determined, it’s time to fork the project, clone it, checkout to <em>refactoring </em>branch, install deps (<strong>cd std_json_io &amp;&amp; mix deps.get</strong>) and start with the most important: problem#5, tests. But even before start working on the problem, it appears that <strong>mix.lock</strong> have outdated format. Let’s commit a new one:</p><pre>git add mix.lock &amp;&amp; git commit -m &#39;Updated mix.lock format&#39;</pre><p>We will not start with the most wanted problem#6 and even more — we will leave it to the end because many of warnings can disappear to that moment. Instead, we will start with tests. Without it we can’t modify any single line of code or remove anything (problem#7) and be sure that it will not impact the application API in any way, so let’s go:</p><h4>SETTING UP TEST ENVIRONMENT</h4><p>First, we need some external app which can read input from STDIN and write output to STDOUT to test against. Of course, <em>react-stdio </em>is the first coming on mind, but that means we will have to setup whole JS infrastructure: react, compiler, react-stdio etc.. Instead, I’m going to create a simple echo-like script in Python 2 under <strong>test/fixtures/echo.py</strong>:</p><pre>#!/usr/bin/env python<br>import sys<br>for line in iter(sys.stdin.readline, &#39;&#39;):<br>  line = line.rstrip(&#39;\n&#39;)<br>  sys.stdout.write(&#39;{&quot;response&quot;: &#39;+ line + &#39;}&#39;),</pre><p>change permissions to the script chmod +x test/fixtures/echo.py and verify it’s working by running echo &quot;{}&quot; | test/fixtures/echo.py, the result is expected: {&quot;response&quot;: {}}<br>Next, we need to create a module which will use StdJsonIo (problem#2), let’s do it in <strong>test/test_helper.exs</strong> so it will look like</p><pre>ExUnit.start()</pre><pre>defmodule StdJsonIoMock do<br>  use StdJsonIo, otp_app: :std_json_io, script: &quot;python -u test/fixtures/echo.py&quot;<br>end</pre><p>We use <strong>python -u test/fixtures/echo.py</strong> as a script because by default Python buffers its output and to avoid this we have to pass <strong>-u</strong> flag to it.<br>Next let’s update <strong>test/std_json_io_test.exs</strong>: we must start StdJsonIo supervisor before requesting it so define a simple setup function:</p><pre>setup do<br>  {:ok, _} = StdJsonIoMock.start_link([])<br>  {:ok, %{}}<br>end</pre><p>Test environment have been set up and it’s time to commit changes made:</p><pre>git add test &amp;&amp; git commit -m &#39;Setup test environment&#39;</pre><h4>Writing first tests</h4><p>Test environment have been set up and now it’s time to actually write the first tests for StdJsonIo.json_call and StdJsonIo.json_call!. Here it goes:</p><pre>test &quot;Call to json_call returns correct value&quot; do<br>  message = %{&quot;hello&quot; =&gt; &quot;world&quot;}<br>  expected = {:ok, %{&quot;response&quot; =&gt; message}}<br>  assert StdJsonIoMock.json_call(message) == expected<br>end</pre><pre>test &quot;Call to json_call! returns correct value&quot; do<br>  message = %{&quot;hello&quot; =&gt; &quot;world&quot;}<br>  expected = %{&quot;response&quot; =&gt; message}<br>  assert StdJsonIoMock.json_call!(message) == expected<br>end</pre><p>Done! Running mix test and… 2 similar errors saying that</p><blockquote>** (ArgumentError) expected :name option to be one of:</blockquote><blockquote>* nil<br> * atom<br> * {:global, term}<br> * {:via, module, term}</blockquote><blockquote>Got: {:local, StdJsonIoMock}</blockquote><blockquote>stacktrace:<br> (elixir) lib/supervisor.ex:332: Supervisor.start_link/3<br> test/std_json_io_test.exs:6: StdJsonIoTest.__ex_unit_setup_0/1<br> test/std_json_io_test.exs:1: StdJsonIoTest.__ex_unit__/2</blockquote><p>Ok, Supervisor is trying to start with a name of {:local, StdJsonIoMock} and while it’s ok for Erlang to start supervisor in such a manner, Elixir for some reason denies this form. That’s weird since the app was definitely working with this type of registration before so out of curiosity I googled a bit and found that this change was introduced in this PR <a href="https://github.com/elixir-lang/elixir/pull/5027">https://github.com/elixir-lang/elixir/pull/5027</a>. It appears Elixir does convert atom_name to {:local, atom_name} automatically since that PR and doesn’t allow to use {local, atom_name} form anymore. It means our update will be painless, no logic is changed and new way of starting a supervisor is completely backward-compatible: just replace Supervisor.start_link(__MODULE__, :ok, name: {:local, __MODULE__}) with Supervisor.start_link(__MODULE__, :ok, name: __MODULE__) in <strong>lib/std_json_io.ex</strong>. Once done, it’s a good idea to commit the change:</p><pre>git add lib/std_json_io.ex &amp;&amp; git commit -m &#39;Updated call to Supervisor.start_link by passing :atom instead of {:local, :atom} as a name&#39;</pre><p>Now run mix test again. After waiting about 20s, another 2 similar errors are showing up:</p><blockquote>1) test Call to json_call returns correct value (StdJsonIoTest)<br> test/std_json_io_test.exs:10<br> ** (exit) exited in: GenServer.call(#PID&lt;0.189.0&gt;, {:json, %{“hello” =&gt; “world”}}, 10000)<br> ** (EXIT) time out<br> stacktrace:<br> (elixir) lib/gen_server.ex:737: GenServer.call/3<br> src/poolboy.erl:76: :poolboy.transaction/3<br> test/test_helper.exs:4: StdJsonIoMock.json_call/2<br> test/std_json_io_test.exs:12: (test)</blockquote><p>Here we can see that Porcelain didn’t send a response to StdJsonIo in 10s which should be more than enough. So what’s wrong and why it didn’t send a response? The obvious reason here is that because it didn’t get one from a program. But we tested it with a bash command! Let’s return to our script to check what could go wrong. The <em>echo.py</em> reads line-by-line from STDIN and writes line-by-line to STDOUT, but it seems StdJsonIo sends data to it (via Porcelain) with no newline character so echo.py just not aware of input end and keep waiting for \n character to come. Let’s check this assumption by updating worker module <strong>lib/std_json_io/worker.ex</strong> — add trailing \n to json we are sending to Porcelain: Proc.send_input(state.js_proc, json &lt;&gt; &quot;\n&quot;)<br>Now run mix test and… Hooray, it’s all green now, the test have passed! We had to update logic a bit by adding \n to data sent to a program, but that’s completely fine since many programs expect it and ones not relying on it (like <em>react-stdio</em>) will just ignore it, so we just solved a problem we didn’t encounter yet. It’s time to commit our changes: the trailing newline and the first test:</p><pre>git add lib/std_json_io/worker.ex &amp;&amp; git commit -m &#39;Updated StdJsonIo.Worker to append trailing newline to data sent to external program&#39;</pre><pre>git add test &amp;&amp; git commit -m &#39;Added test for StdJsonIo.json_call and StdJsonIo.json_call!&#39;</pre><h4>Keep on testing</h4><p>Now it’s time for the next test to test handling of big response. We expect there will be an error (problem#1) but we need the test to start working on the problem.</p><pre>test &quot;Can handle big response&quot; do<br>  message = %{&quot;thisishuge&quot; =&gt; String.duplicate(&quot;Lorem Ipsum Dolor Sit Amet&quot;, 10000)}<br>  expected = {:ok, %{&quot;response&quot; =&gt; message}}<br>  assert StdJsonIoMock.json_call(message) == expected<br>end</pre><p>Running mix test we’ll get an error</p><blockquote>..</blockquote><blockquote>1) test Can handle big response (StdJsonIoTest)<br> test/std_json_io_test.exs:22<br> ** (MatchError) no match of right hand side value: {:error, :invalid}<br> stacktrace:<br> test/test_helper.exs:4: StdJsonIoMock.json_call/2<br> test/std_json_io_test.exs:25: (test)</blockquote><blockquote>Finished in 0.4 seconds<br>3 tests, 1 failure</blockquote><blockquote>Randomized with seed 50902</blockquote><blockquote>18:00:59.512 [error] GenServer #PID&lt;0.215.0&gt; terminating<br>** (FunctionClauseError) no function clause matching in StdJsonIo.Worker.handle_info/2<br> (std_json_io) lib/std_json_io/worker.ex:33: StdJsonIo.Worker.handle_info({#PID&lt;0.216.0&gt;, :data, :out, “lor Sit Amet&lt;…&gt;Lorem Ipsum Dolor Sit AmetLo (truncated)</blockquote><p>(I removed some part of the real output since it’s useless but kept what really matters)<br>It’s time to get this fixed. To write a fix we must understand why this happens. Let’s look at test error stacktrace: we can see that <strong>StdJsonIo.Worker.handle_info/2</strong> was unable to match against message it have got: {#PID&lt;0.200.0&gt;, :data, :out, &quot;lor Sit Amet&lt;...&gt;&quot;}, but if we open lib/std_json_io/worker.ex we’ll quickly find out that such a data is expected in a receive instruction of handle_call/3 method and not handle_info/2. Our worker sends data to <em>Porcelain</em>, it handles communication with the external program (<em>echo.py</em>) and passes response from a program back to worker via process message. This response is then decoded from JSON and returned to caller (test suite in our case). But we can find another detail in the error we’ve got: StdJsonIoMock returned {:error, :invalid}, which seems like there was a JSON decoding error. So according to these 2 facts, it seems response was sent in more than one chunk from <em>Porcelain</em> and after 1st chunk came to receive instruction, second was handled by handle_info/2. And since 1st chunk is not a complete JSON, Poison couldn’t decode it and returned an error. Simplest solution is following: replace currentreceive block with function receiving chunks and concating them in loop till valid JSON is received:</p><pre>receiver = fn f, data -&gt;<br>  receive do<br>    {_pid, :data, :out, msg} -&gt;<br>      new_data = data &lt;&gt; msg<br>      case Poison.decode(new_data) do<br>        {:error, _} -&gt;<br>          # Couldn&#39;t decode JSON, there are more chunks<br>          # to receive and concat with<br>          f.(f, new_data)<br>        {:ok, _} -&gt;<br>          # All chunks received<br>          {:reply, {:ok, new_data}, state}<br>      end<br>    other -&gt;<br>      {:reply, {:error, other}, state}<br>  end<br>end<br>Proc.send_input(state.js_proc, json &lt;&gt; &quot;\n&quot;)<br>receiver.(receiver, &quot;&quot;)</pre><p>As soon as the change is applied, mix test shows all 3 tests passed. Time to commit, this time no need to split files into different commits since test and logic changed are closely related to 1 problem:</p><pre>git add . &amp;&amp; git commit -m &#39;Fixed processing big response&#39;</pre><h4>Removing StdJsonIo.Reloader</h4><p>Now when we have tests in place, we can remove StdJsonIo.Reloader and be sure nothing got broken. First, rm lib/std_json_io/reloader.ex. Next is to remove calls to the module. To find all the places it was mentioned, I used grep -rnw &#39;./lib&#39; -e &#39;Reloader&#39; and got only <strong>lib/std_json_io.ex</strong>, so that’s the only place where I have to remove logic related to Reloader:</p><pre>-        files = Keyword.get(<a href="http://twitter.com/options">@options</a>, :watch_files)<br>-<br>-        if files &amp;&amp; length(files) &gt; 0 do<br>-          Application.ensure_started(:fs, :permanent)<br>-<br>-          reloader_spec = worker(<br>-            StdJsonIo.Reloader,<br>-            [__MODULE__, Enum.map(files, &amp;Path.expand/1)],<br>-            []<br>-          )<br>-<br>-          children = [reloader_spec | children]<br>-        end</pre><p>Also, as we know, Reloader was used to run StdJsonIo.restart_io_workers!/0 function which is useless as we already determined, so let’s remove it as well:</p><pre>-      def restart_io_workers! do<br>-        case Process.whereis(<a href="http://twitter.com/pool_name">@pool_name</a>) do<br>-          nil -&gt;<br>-            Supervisor.restart_child(__MODULE__, <a href="http://twitter.com/pool_name">@pool_name</a>)<br>-          _pid -&gt;<br>-            Supervisor.terminate_child(__MODULE__, <a href="http://twitter.com/pool_name">@pool_name</a>)<br>-            Supervisor.restart_child(__MODULE__, <a href="http://twitter.com/pool_name">@pool_name</a>)<br>-        end<br>-      end</pre><p>Dependency fs is also no longer needed:</p><pre>-      applications: [:logger, :porcelain],<br>-      included_applications: [:fs]<br>+      applications: [:logger, :porcelain]<br>...<br>-      {:poison, &quot;~&gt; 1.5.0&quot;},<br>-      {:fs, &quot;~&gt; 0.9.1&quot;},<br>+      {:poison, &quot;~&gt; 1.5.0&quot;}</pre><p>Final step is to clean up our deps: mix do deps.unlock fs, deps.clean fs. Now run mix test and confirm we are all good. Time to commit:</p><pre>git add . &amp;&amp; git commit -m &#39;Removed Reloader module and fs dependency&#39;</pre><h4>Getting rid of unnecessary module</h4><p>StdJsonIo library requires end user to define a new module in a way of</p><pre>defmodule Myapp.StdJsonIo do<br>  use StdJsonIo, otp_app: :myapp<br>end</pre><p>however after quick inspection of <strong>lib/std_json_io.ex</strong> it appears that the macro is doing nothing special at all, and in fact just allows you to call Myapp.StdJsonIo.json_call/1 instead of StdJsonIo.json_call/1. otp_app is also something useless — it is required to configure StdJsonIo in a way of config :myapp, Myapp.StdJsonIo, config_list while it could be easily done by allowing users to configure StdJsonIo in a standard way of defining an OTP app and configuring it via config :std_json_io, config_list. Time to get rid of the __using__ macro in <strong>lib/std_json_io.ex </strong>and make StdJsonIo a full-fledged OTP application with it’s own supervision tree. Create a file <strong>lib/std_json_io/application.ex</strong> with a basic App/Supervisor setup:</p><pre>defmodule StdJsonIo.Application do<br>  use Application</pre><pre>  def start(_type, _args) do<br>    import Supervisor.Spec, warn: false<br>    children = []<br>    opts = [strategy: :one_for_one, name: StdJsonIo.Supervisor]<br>    Supervisor.start_link(children, opts)<br>  end<br>end</pre><p>and update application/0 function in mix.exs:</p><pre>def application do<br>  [<br>    applications: [:logger, :porcelain],<br>    mod: {StdJsonIo.Application, []}<br>  ]<br>end</pre><p>Once done, commit:</p><pre>git add . &amp;&amp; git commit -m &#39;Added OTP Application and Supervisor&#39; </pre><p>Test environment should be rewritten accordingly: we no longer will need neither setup to start supervisor nor StdJsonIoMock to use StdJsonIo since that’s what we are aimed to get rid of. So <strong>test/test_helper.exs</strong> will end up with a single line ExUnit.start() and in <strong>test/std_json_io_test.exs</strong> remove completely setup macro and replace StdJsonIoMock with StdJsonIo.</p><p>Since app will use config instead of options passed to __using__/1 macro, it’s time to fill <strong>config/config.exs</strong> with values suitable for running tests:</p><pre>config :std_json_io,<br>  pool_size: 5,<br>  pool_max_overflow: 10,<br>  script: &quot;python -u test/fixtures/echo.py&quot;</pre><p>Next step is to move all the supervisor setup (excluding Reloader, problem #7) from <strong>lib/std_json_io.ex</strong> to <strong>lib/std_json_io/application.ex</strong>:</p><pre>def start(_type, _args) do<br>  import Supervisor.Spec, warn: false<br>  config = Application.get_all_env(:std_json_io)<br>  pool_options = [<br>    name: {:local, StdJsonIo.Pool},<br>    worker_module: StdJsonIo.Worker,<br>    size: Keyword.get(config, :pool_size, 15),<br>    max_overflow: Keyword.get(config, :pool_max_overflow, 10)<br>  ]<br>  children = [<br>    :poolboy.child_spec(StdJsonIo.Pool, pool_options, [script: Keyword.fetch!(config, :script)])<br>  ]<br>  opts = [strategy: :one_for_one, name: StdJsonIo.Supervisor]<br>  Supervisor.start_link(children, opts)<br>end</pre><p>Since we moved all the setup to <strong>lib/std_json_io/application.ex</strong>, we can clean up <strong>lib/std_json_io.ex </strong>and leave only 2 API functions: json_call/2 and json_call!/2. Finally, the whole module will fit in just 24 LOC:</p><pre>defmodule StdJsonIo do<br>  def json_call!(map, timeout \\ 10000) do<br>    case json_call(map, timeout) do<br>      {:ok, data} -&gt; data<br>      {:error, reason } -&gt; raise &quot;Failed to call to json service #{__MODULE__} #{to_string(reason)}&quot;<br>    end<br>  end</pre><pre>  def json_call(map, timeout \\ 10000) do<br>    result = :poolboy.transaction(StdJsonIo.Pool, fn worker -&gt;<br>      GenServer.call(worker, {:json, map}, timeout)<br>    end)</pre><pre>    case result do<br>      {:ok, json} -&gt;<br>        {:ok, data} = Poison.decode(json)<br>        if data[&quot;error&quot;] do<br>          {:error, Map.get(data, &quot;error&quot;)}<br>        else<br>          {:ok, data}<br>        end<br>      other -&gt; other<br>    end<br>  end<br>end</pre><p>Seems all is done, time to run mix test:</p><blockquote>…</blockquote><blockquote>Finished in 0.1 seconds<br>3 tests, 0 failures</blockquote><p>Great! We changed a lot, but everything is working as before, time to commit:</p><pre>git add . &amp;&amp; git commit -m &#39;Moved init functionality to OTP Application start\2 function&#39;</pre><p>So far we resolved problems #1, #2, #3, #5 and #7. The rest is to update dependencies and to fix warnings.</p><h4>Updating dependencies</h4><p>mix hex.outdated command will show list of all deps and it’s up-to-date status. In my case it was</p><pre>Dependency  Current  Latest  Update possible<br>poison      1.5.0    3.1.0   No<br>poolboy     1.5.1    1.5.1<br>porcelain   2.0.1    2.0.3   Yes</pre><p>Let’s update Porcelain version required in <strong>mix.exs</strong> to 2.0.3 instead of 2.0, run mix deps.update porcelain and then mix test. Tests are passing, dependency updated, everything is fine. Next in queue is Poison:</p><p>Update Poison version required in mix.exs to 3.1.0, run mix deps.update poison and then mix test… Error:</p><blockquote>..<br>18:50:51.991 [error] GenServer #PID&lt;0.329.0&gt; terminating<br>** (CaseClauseError) no case clause matching: {:error, :invalid, 65536}<br> (std_json_io) lib/std_json_io/worker.ex:24: anonymous fn/3 in StdJsonIo.Worker.handle_call/3<br> (stdlib) gen_server.erl:615: :gen_server.try_handle_call/4<br> (stdlib) gen_server.erl:647: :gen_server.handle_msg/5<br> (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3<br>Last message: {:json, %{“thisishuge” =&gt; “Lorem Ipsum Dolor Sit Amet&lt;…&gt;Lorem Ipsum Dolor Sit Amet (truncated)</blockquote><blockquote>1) test Can handle big response (StdJsonIoTest)<br> test/std_json_io_test.exs:17<br> ** (exit) exited in: GenServer.call(#PID&lt;0.329.0&gt;, {:json, %{“thisishuge” =&gt; “Lorem Ipsum Dolor Sit Amet&lt;…&gt;Lorem Ipsum Dolor Sit Amet”}}, 10000)<br> ** (EXIT) an exception was raised:<br> ** (CaseClauseError) no case clause matching: {:error, :invalid, 65536}<br> (std_json_io) lib/std_json_io/worker.ex:24: anonymous fn/3 in StdJsonIo.Worker.handle_call/3<br> (stdlib) gen_server.erl:615: :gen_server.try_handle_call/4<br> (stdlib) gen_server.erl:647: :gen_server.handle_msg/5<br> (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3<br> stacktrace:<br> (elixir) lib/gen_server.ex:737: GenServer.call/3<br> src/poolboy.erl:76: :poolboy.transaction/3<br> (std_json_io) lib/std_json_io.ex:10: StdJsonIo.json_call/2<br> test/std_json_io_test.exs:20: (test)</blockquote><blockquote>Finished in 0.1 seconds<br>3 tests, 1 failure</blockquote><p>Let’s check what’s going on at lib/std_json_io/worker.ex:24: there’s a call to Poison.decode/1. As you can see, 2 tests successfully passed while testing big response failed. It means that when Poison.decode/1 returns {:ok, _} everything is fine but expected {:error, error} is not returned for incomplete JSON, because Poison.decode/1 was updated and now returns {:error, :invalid, 65536} instead of {:error, error}. Quick googling shows up the change was introduced in this PR: <a href="https://github.com/devinus/poison/pull/100">https://github.com/devinus/poison/pull/100</a> and 65536 is a position where Poison parser got failure trying to decode data (since it was just a chunk of a JSON but not a complete and valid one). We don’t actually care about it and can simply fix it by changing the case-block in following way:</p><pre>case Poison.decode(new_data) do<br>  {:ok, _} -&gt;<br>    # All chunks received<br>    {:reply, {:ok, new_data}, state}<br>  _ -&gt;<br>    # Couldn&#39;t decode JSON, there are more chunks<br>    # to receive and concat with<br>    f.(f, new_data)<br>end</pre><p>Now tests are passing again. Good reason to commit:</p><pre>git add . &amp;&amp; git commit -m &#39;Upgraded Poison and Porcelain dependencies&#39;</pre><p>Now when problem#4 is resolved, it’s time to get to problem#6 — remove all Elixir compiler warnings. When we started refactoring, there were a lot of them, but most existed in StdJsonIo.__using__/1 and are gone now leaving just these two:</p><blockquote>warning: variable “docs” does not exist and is being expanded to “docs()”, please use parentheses to remove the ambiguity or change the variable name<br> mix.exs:20</blockquote><blockquote>warning: variable “deps” does not exist and is being expanded to “deps()”, please use parentheses to remove the ambiguity or change the variable name<br> mix.exs:21</blockquote><p>Both are as easy to fix as just add () to the end of deps and docs functions calls in <strong>mix.exs</strong>:</p><pre>-     docs: docs,<br>-     deps: deps]<br>+     docs: docs(),<br>+     deps: deps()]</pre><p>Now there are no more warnings but still info-messages from Porcelain appears:</p><blockquote>19:07:23.311 [info] [Porcelain]: goon executable not found</blockquote><blockquote>19:07:23.311 [info] [Porcelain]: falling back to the basic driver.</blockquote><blockquote>19:07:23.311 [info] [Porcelain]: (set `config :porcelain, driver: Porcelain.Driver.Basic` or `config :porcelain, goon_warn_if_missing: false` to disable this warning)</blockquote><p>Since I don’t have goon installed and not planning to do so, I’ll add config :porcelain, driver: Porcelain.Driver.Basic to <strong>config/config.js </strong>for these info messages to disappear and not bother me every time I run tests. Now when I run mix test, the output is clean and nice:</p><blockquote>➜ std_json_io git:(refactoring) ✗ mix test<br>…</blockquote><blockquote>Finished in 0.2 seconds<br>3 tests, 0 failures</blockquote><blockquote>Randomized with seed 158445</blockquote><p>Commit:</p><pre>git add . &amp;&amp; git commit -m &#39;Fixed warnings&#39;</pre><p>Looks like we are done with problems #1 — #7, but when it comes to refactoring, it’s never enough. Solution to handle chunked response from Porcelain is a bit hacky and have some disadvantages, so it sounds like a good idea to refactor it in a way of involving GenServer’s handle_info/2 callback…</p><h4>Refactoring is never enough!</h4><p>First, we must design a new solution to handle chunked response. Since GenServer.handle_call/3 callback is used, we can’t use handle_info just yet because handle_call is blocking to return response to a caller. So first, we must replace it with non-blocking GenServer.handle_cast/2. Since StdJsonIo.json_call/2 can’t receive answer via result = GenServer.call(data), another option is to call GenServer.cast callback and await for response from the server via message-passing. Let’s create a handle_cast/2 callback which will replace handle_call/3 and also update state and init/1 function a bit: use Elixir’sProcess.flag/2 instead of Erlang’s one :erlang.process_flag/2, rename js_proc to pproc (porcelain_proc) since it’s more abstract name rather than js_proc and reflects it’s of type %Porcelain.Process{}, and add reply_to and buffer keys to a state map which we’ll need to handle Porcelain chunked response and to send response to an API functions:</p><pre>def init(script) do<br>  Process.flag(:trap_exit, true)<br>  pproc = Porcelain.spawn_shell(script, in: :receive, out: {:send, self()})<br>  {:ok, %{pproc: pproc, buffer: &quot;&quot;, reply_to: nil}}<br>end</pre><pre>def handle_cast({:json, data, reply_to}, %{pproc: pproc} = state) do<br>  {:ok, json} = Poison.encode(data)<br>  PProc.send_input(pproc, json &lt;&gt; &quot;\n&quot;)<br>  {:noreply, %{state | reply_to: reply_to}}<br>end</pre><p>Also, let’s update alias to Porcelain.Process to be PProc instead of Proc to not confuse it with Process accidentally and to reflect it’s namespace:</p><pre>-  alias Porcelain.Process, as: Proc<br>+  alias Porcelain.Process, as: PProc</pre><p>Now when Porcelain will send response to the server, it will be handled in handle_info/2, which is pretty much similar with our receive approach:</p><pre>def handle_info({pproc_pid, :data, :out, data}, %{pproc: %PProc{pid: pproc_pid}, buffer: buffer} = state) do<br>  new_buffer = buffer &lt;&gt; data<br>  case Poison.decode(new_buffer) do<br>    {:ok, decoded} -&gt;<br>      Process.send(state[:reply_to], decoded, [])<br>      {:noreply, %{state | buffer: &quot;&quot;}}<br>    _ -&gt;<br>      {:noreply, %{state | buffer: new_buffer}}<br>  end<br>end</pre><p>Also, it’s not a bad idea to update handle_info/2 responsible for handling :result (finishing) type of messages from Porcelain in case application it works with exits, to be more strict in checking incoming message:</p><pre>-  def handle_info({_js_pid, :result, %Result{err: _, status: _status}}, state) do<br>+  def handle_info({pproc_pid, :result, %Result{err: _, status: _status}}, %{pproc: %PProc{pid: pproc_pid}} = state) do</pre><p>Because we renamed js_proc to pproc and renamed Proc alias to PProc, it should also be renamed in terminate/2 function. Next, functions terminate(_, _), handle_call(:stop, _from, state) and start_io_server/1 can be removed: first because it’s useless, second because it’s not used from anywhere in the codebase and third is because we moved starting Porcelain process to init/1. The last step in updating the module is to completely remove handle_call/3 function as it’s no longer needed.</p><blockquote>UPDATE WARNING: following is not the best approach for API &lt;-&gt; Worker communication and have disadvantages. You can check out the <a href="https://github.com/chvanikoff/std_json_io">library fork repo</a> for a better design approach.</blockquote><p>Now it’s time to update API functions in <strong>lib/std_json_io.ex</strong> to work with updated worker, this is pretty simple: just replace GenServer.call/2 with GenServer.cast/2 and receive block. Also if you were attentive enough, you could see that we are sending decoded JSON to API now rather than plain one — that is done to avoid double decoding. New version of StdJsonIo.json_call/2 will be following:</p><pre>def json_call(data, timeout \\ 10000) do<br>  result = :poolboy.transaction(StdJsonIo.Pool, fn worker -&gt;<br>    GenServer.cast(worker, {:json, data, self()})<br>    receive do<br>      response -&gt;<br>        response<br>    after<br>      timeout -&gt;<br>        %{&quot;error&quot; =&gt; &quot;timeout&quot;}<br>    end<br>  end)<br>  if result[&quot;error&quot;] do<br>    {:error, Map.get(result, &quot;error&quot;)}<br>  else<br>    {:ok, result}<br>  end<br>end</pre><p>Now it seems everything is in place and time to run mix test:</p><blockquote>…</blockquote><blockquote>Finished in 0.1 seconds<br>3 tests, 0 failures</blockquote><pre>git add . &amp;&amp; git commit -m &#39;Updated Worker design&#39;</pre><p>The final accord to all done above is to update README.md so everyone is aware of how to use the new refactored library, but I think that’s of no interest to copy-paste here so you can check it out in the repo.</p><p>As I mentioned at the very beginning, you can find my fork at <a href="https://github.com/chvanikoff/std_json_io">https://github.com/chvanikoff/std_json_io</a> with all the commits mentioned in the article in place and pull request to the original library can be found here: <a href="https://github.com/hassox/std_json_io/pull/13">https://github.com/hassox/std_json_io/pull/13</a>.</p><p>That’s all folks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e444b6f2c580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Rancher with SSL.]]></title>
            <link>https://medium.com/@chvanikoff/setting-up-rancher-with-ssl-d0491f258720?source=rss-b729aa603207------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0491f258720</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[rancher]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[lets-encrypt]]></category>
            <dc:creator><![CDATA[Roman Chvanikov]]></dc:creator>
            <pubDate>Fri, 21 Apr 2017 03:06:28 GMT</pubDate>
            <atom:updated>2017-04-22T02:17:34.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Here is a process of setting up Rancher with SSL from “Let’s Encrypt” via Nginx.</p><p><strong>Software versions:</strong></p><ul><li><a href="https://www.docker.com/">https://www.docker.com</a> <strong>1.12.6</strong></li><li><a href="http://rancher.com/">http://rancher.com</a> <strong>1.5.5</strong></li><li><a href="http://nginx.org/">http://nginx.org</a> <strong>1.11</strong></li><li><a href="https://letsencrypt.org/">https://letsencrypt.org</a> certbot <strong>0.13.0</strong></li></ul><h3>What we will get:</h3><p>- Let’s Encrypt SSL certificate (for rancher.example.com in this guide)<br>- Nginx listening ports 80 and 443 and redirecting all HTTP requests (to port 80) to HTTPS (port 443)<br>- Rancher server running on port 8080 (which you can forbid access to from anywhere but localhost after finishing the installation).</p><h3>The guide.</h3><ol><li>Prepare a server — install docker and the rest is up to you. My minimum is:</li></ol><pre>apt-get update &amp;&amp; apt-get -y dist-upgrade &amp;&amp; apt-get -y install vim wget docker.io</pre><p>2. Setup DNS records for your domain, ex.:</p><pre>A rancher.example.com 1.2.3.4</pre><p>2. Setup Let’s Encrypt app:</p><pre>wget <a href="https://dl.eff.org/certbot-autochmod">https://dl.eff.org/certbot-auto<br>chmod</a> a+x certbot-auto<br>./certbot-auto</pre><p>you’ll get an error “<strong>Failed to find executable apache2ctl in PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin</strong>” which is absolutely fine — we don’t have any webserver for Let’s encrypt and we will use it’s built-in temporary one.<br>3. Obtain SSL certificates for the domain rancher.example.com:</p><pre>./certbot-auto certonly<br></pre><p>when asked for the way to authenticate with ACME CA, select “<strong>2: spin up a temporary webserver (standalone)</strong>”, following questions are up to you.<br>4. Create config for Nginx to redirect HTTP to HTTPS and to use our fresh SSL certificates:<br><em>vim /etc/nginx.conf</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd9d9317b5fec4fe6a2da36fee7ac2e/href">https://medium.com/media/dbd9d9317b5fec4fe6a2da36fee7ac2e/href</a></iframe><p>&lt;DOMAIN&gt; is the domain your SSL certificate was created for, in our case — rancher.example.com</p><p>&lt;SERVER_NAME&gt; can be any arbitrary name, but the same name should be used for both the http and https servers, for example: “server_name rancher.example.com”<br>5. Start Rancher server:</p><pre>docker run -d --name=rancher-server --restart=unless-stopped -p 8080:8080 rancher/server</pre><p>Open logs with “docker logs -f rancher-server”, after a minute or so you should see something like this:</p><blockquote>time=”2017–04–20T13:08:08Z” level=info msg=”Updating machine jsons for [packet packet amazonec2 azure digitalocean]”<br>time=”2017–04–20T13:08:09Z” level=info msg=”Creating schema machine, roles [service]” id=1ds29<br>time=”2017–04–20T13:08:09Z” level=info msg=”Creating schema host, roles [service]” id=1ds30<br>time=”2017–04–20T13:08:09Z” level=info msg=”Creating schema machine, roles [project member owner]” id=1ds31<br>time=”2017–04–20T13:08:10Z” level=info msg=”Creating schema host, roles [project member owner]” id=1ds32<br>time=”2017–04–20T13:08:10Z” level=info msg=”Creating schema machine, roles [admin user readAdmin]” id=1ds33<br>time=”2017–04–20T13:08:10Z” level=info msg=”Creating schema host, roles [admin user readAdmin]” id=1ds34<br>time=”2017–04–20T13:08:10Z” level=info msg=”Creating schema machine, roles [readonly]” id=1ds35<br>time=”2017–04–20T13:08:10Z” level=info msg=”Creating schema host, roles [readonly]” id=1ds36</blockquote><p>Now “ctr-c” and go to the next step.<br>6. Run Nginx linked with rancher-server container:</p><pre>docker run -d --name=nginx --restart=unless-stopped -p 80:80 -p 443:443 -v /etc/letsencrypt:/etc/letsencrypt -v /etc/nginx.conf:/etc/nginx/conf.d/default.conf --link=rancher-server nginx:1.11</pre><p>7. Setup Rancher access: ADMIN -&gt; Access Control</p><p>Enjoy your Rancher server running at <a href="https://rancher.example.com/">https://rancher.example.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0491f258720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phoenix + React: love story. RePh 2.]]></title>
            <link>https://medium.com/@chvanikoff/phoenix-react-love-story-reph-2-14a6dcadbbd0?source=rss-b729aa603207------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a6dcadbbd0</guid>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Roman Chvanikov]]></dc:creator>
            <pubDate>Wed, 25 May 2016 02:56:54 GMT</pubDate>
            <atom:updated>2017-06-20T15:13:58.819Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Want to start building RePh app without carrying about scaffolding? Good news: I just released RePh app generator, <a href="https://medium.com/@chvanikoff/reph-react-phoenix-app-scaffolding-made-easy-346cddc76838">take a look</a>!</blockquote><p>In <a href="https://medium.com/@chvanikoff/phoenix-react-love-story-reph-1-c68512cfe18#.koav204ij">RePh 1</a> part of the article we’ve created a very basic app. Today we are going to improve it with authorization and different apps for guests and authorized users — it is a common task to have a landing page and application page which provides completely different layout, styles and JS. Another feature not covered in similar tutorials is authorization via websockets and storing auth status in session — that’s what you’ll learn as well.</p><p>Complete app code is available at Github, every step lives in it’s own commit: <a href="https://github.com/chvanikoff/reph2">https://github.com/chvanikoff/reph2</a></p><p>The demo is available at <a href="https://reph2.herokuapp.com/">https://reph2.herokuapp.com</a> but is only available 18h/day due to Heroku free dyno limitation. If you see `Application Error` message — this is the case.</p><h4>Primary tech stack used.</h4><ul><li>Elixir 1.2.5</li><li>Node 4.4.3</li><li>NPM 3.9.2</li><li>WebPack 1.13.0</li><li>Phoenix 1.1.4</li><li>React 15.0.2</li></ul><h4>Getting started.</h4><p>We will use <a href="https://medium.com/@chvanikoff/phoenix-react-love-story-reph-1-c68512cfe18#.fr84tb1bb">RePh 1</a> app as a base and to get started you should clone <a href="https://github.com/chvanikoff/reph">the repo</a>. Again, I will use <em>~/phoenix </em>as a root directory for the app but you can choose whichever you want.</p><pre>cd ~/phoenix<br>git clone <a href="https://github.com/chvanikoff/reph.git">https://github.com/chvanikoff/reph.git</a><br>cd reph<br>mix deps.get &amp;&amp; npm install</pre><h4>Hello landing.</h4><p>Now let’s think about our app’s file structure — since we are going to have 2 bundles (landing and app), it doesnt’t make sense to keep all the files right in <em>web/static/js</em> and <em>web/static/styles</em>. Instead, we will use 2 subdirectories — “landing” and “app” — in both <em>js</em> and <em>styles</em> folder. Create the directories and move all files from <em>priv/static/js</em> to <em>priv/static/js/landing</em> and from <em>priv/static/styles</em> to <em>priv/static/styles/landing</em>:</p><pre># First, let&#39;s move all JS files to new path<br>cd web/static/js<br>mkdir landing<br># Following will throw an error but it will do what we need - to<br># move all the files we have to &quot;landing&quot; directory. If you know a<br># better way of doing this, let me know.<br>mv ./* landing<br>mkdir app</pre><pre># And now exactly the same for styles<br>cd ../styles<br>mkdir landing<br>mv ./* landing<br>mkdir app</pre><pre># Let&#39;s get back to our root before next steps<br>cd ../../../</pre><p>We will have 2 different applications, so let’s split images into <em>landing</em> and <em>app</em> as well — just create 2 directories in <em>web/static/assets/images</em> and move phoenix.png to <em>images/landing:</em></p><pre>cd web/static/assets/images<br>mkdir landing app<br>mv phoenix.png landing</pre><pre># Let&#39;s get back to our root before next steps<br>cd -</pre><p>Now when we know about our app file structure, we can update Webpack config files. There are a few changes to do:</p><ul><li>in <em>webpack.config.js</em> change all references of <em>web/static/js</em> and <em>web/static/styles</em> with <em>web/static/js/landing </em>and <em>web/static/styles/landing</em> accordingly</li><li>update images and fonts loaders to put files into <em>images/landing </em>instead of just <em>images</em></li><li>update output filename to be <em>js/landing.js</em></li></ul><p>Also, I’ve decided to cleanup url-loaders declaration a bit and created a helper function <em>URLLoader </em>to replace current images/fonts loaders with a cleaner representation<em>. </em>Here is <em>webpack.config.js</em> after all changes done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a68f2dadd5f344a7db8e5b58008d8c2b/href">https://medium.com/media/a68f2dadd5f344a7db8e5b58008d8c2b/href</a></iframe><p>Once done, update <em>webpack.server.config.js </em>as well. We will name our file and library to be generated “<em>landing”</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f75ef92ccfb37c517b7ea2847a45349/href">https://medium.com/media/5f75ef92ccfb37c517b7ea2847a45349/href</a></iframe><p>Now we are done with Webpack configs and the rest of our app should be updated to work with new paths.</p><p>Since we moved our images to <em>images/landing</em>, logo path in styles must be changed<em>. </em>Update <em>web/static/styles/landing/index.less:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c939d4e705b0a7eb5159dffbe048237b/href">https://medium.com/media/c939d4e705b0a7eb5159dffbe048237b/href</a></iframe><p>We also changed server bundle name to <em>landing.js </em>so change <em>reph.js </em>to it in <em>web/controllers/page_controller.ex</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1bb0ebe70815ee33e69d1cc8538dc8/href">https://medium.com/media/7e1bb0ebe70815ee33e69d1cc8538dc8/href</a></iframe><p>Next, let’s create a separate layout for landing: <em>web/templates/layout/landing.html.eex. </em>It will be the same as <em>app.html.eex </em>but js and css would be different. Copy <em>app.html.eex </em>layout</p><pre>cd web/templates/layout<br>cp ./app.html.eex ./landing.html.eex</pre><p>and update paths to static files. Finally, the <em>landing.html.eex </em>will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d14bee6b5ec4f1a9819fbf2b894f0c8/href">https://medium.com/media/4d14bee6b5ec4f1a9819fbf2b894f0c8/href</a></iframe><p>To use this layout instead of default <em>app.html.eex</em>, we have to update <em>page_controller.ex </em>with a call to <em>put_layout/2 </em>function before rendering:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d5a26a5a93ea4e52bfb0012c96a6fcc/href">https://medium.com/media/6d5a26a5a93ea4e52bfb0012c96a6fcc/href</a></iframe><p>Next, let’s remove visitors from the landing — it will be kind of secret information which is only visible for authorized users. Open <em>web/static/js/landing/components/Main/index.js </em>and remove everything related to visitors info displaying as well as <em>connect </em>function call — there’s no need in state anymore. Here is the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/144ea5ef1c6680d3eccabc61e09469ad/href">https://medium.com/media/144ea5ef1c6680d3eccabc61e09469ad/href</a></iframe><p>At this point our setup is done, you can launch the app with <em>mix phoenix.server</em> and check that everything is correctly bundled in new paths and looks exactly same as before.</p><h4>Hello auth.</h4><p>Next thing to do in our app is authorization. We will use <a href="https://hex.pm/packages/comeonin">Comeonin</a> 2.4, <a href="https://hex.pm/packages/guardian">Guardian</a> 0.11 and <a href="https://hex.pm/packages/guardian_db">GuardianDB</a> 0.5 (since latest 0.6 requires Ecto 2.0 which is still having RC status) so add all of these into <em>deps </em>and <em>applications </em>lists of <em>mix.exs </em>and then run <em>“mix deps.get”:</em></p><pre>def application do<br>  [mod: {Reph, []},<br>   applications: [:phoenix, :phoenix_html, :cowboy,<br>     :logger, :gettext, :phoenix_ecto, :postgrex,<br>     :std_json_io, :guardian, :comeonin]]<br>end</pre><pre># ...</pre><pre>defp deps do<br>  [{:phoenix, &quot;~&gt; 1.1.4&quot;},<br>   {:postgrex, &quot;&gt;= 0.0.0&quot;},<br>   {:phoenix_ecto, &quot;~&gt; 2.0&quot;},<br>   {:phoenix_html, &quot;~&gt; 2.4&quot;},<br>   {:phoenix_live_reload, &quot;~&gt; 1.0&quot;, only: :dev},<br>   {:gettext, &quot;~&gt; 0.9&quot;},<br>   {:cowboy, &quot;~&gt; 1.0&quot;},<br>   {:std_json_io, &quot;~&gt; 0.1&quot;},<br>   {:comeonin, &quot;~&gt; 2.4&quot;},<br>   {:guardian, &quot;~&gt; 0.11&quot;},<br>   {:guardian_db, &quot;~&gt; 0.5&quot;}]<br>end</pre><p>Guardian requires configuration so open <em>config/config.exs </em>and add configs for <em>guardian </em>and <em>guardian_db:</em></p><pre>config :guardian, Guardian,<br>  issuer: &quot;reph2&quot;,<br>  ttl: {30, :days},<br>  secret_key: &quot;a big secured secret key&quot;,<br>  serializer: Reph.Guardian.Serializer,<br>  hooks: GuardianDb</pre><pre>config :guardian_db, GuardianDb,<br>  repo: Reph.Repo,<br>  schema_name: &quot;tokens&quot;</pre><p><em>Tip: you can generate secret key with “mix phoenix.gen.secret” but you need to save the config first because running tasks requires project compilation which will fail without the config in place.</em></p><p>As you can see, we will use GuardianDB to persist tokens which means we need a migration to create “tokens” table. Create migration with</p><pre>mix ecto.gen.migration create_tokens</pre><p>and update <em>priv/repo/migrations/</em>%DATETIME%_create_tokens.exs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/494d36910c62b489ccb6f3baf88df606/href">https://medium.com/media/494d36910c62b489ccb6f3baf88df606/href</a></iframe><p>Now let’s start with a simple User model which will only have <em>id, email </em>and <em>password </em>(hash). Also we will need 2 virtual fields for validation purpose — <em>password_plain </em>and <em>terms_confirmed. </em>We’ll generate the model with Phoenix generator:</p><pre>mix phoenix.gen.model User users email password</pre><p>Since email should be unique, add such a key to the column in <em>priv/repo/migrations/%DATETIME%_create_user.exs:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbf84bb775d82f83b1773df233db8756/href">https://medium.com/media/fbf84bb775d82f83b1773df233db8756/href</a></iframe><p>Now you can run “<em>mix ecto.setup</em>” to create database and run 2 migrations — for users and guardian tokens. To add virtual fields to User model, open <em>web/models/user.ex</em> and update <em>schema:</em></p><pre>schema &quot;users&quot; do<br>  field :email, :string<br>  field :password, :string<br>  field :password_plain, :string, virtual: true<br>  field :terms_confirmed, :boolean, virtual: true</pre><pre>  timestamps<br>end</pre><p>Also I suggest to add alias for Reph.Repo — just add this line to the beginning of User model file:</p><pre>alias Reph.Repo</pre><p>List of required fields will contain data sent from client and optional fields will only have <em>password</em>, where we will put hash of <em>password_plain:</em></p><pre>@required_fields ~w(email password_plain terms_confirmed)<br>@optional_fields ~w(password)</pre><p>In <em>changeset/2 </em>function we will perform all validations and set <em>password</em> field. Setting password field means hashing of virtual <em>password_plain</em> field and setting the hash to <em>password </em>field<em>. </em>To do this, let’s create a function <em>cs_encrypt_password </em>(“<em>cs”</em> stands for changeset) which will set the field when all validations passed and just return the same changeset if not:</p><pre>defp cs_encrypt_password(%Ecto.Changeset{valid?: true, changes: %{password_plain: pwd}} = cs) do<br>  put_change(cs, :password, Comeonin.Bcrypt.hashpwsalt(pwd))<br>end<br>defp cs_encrypt_password(cs), do: cs</pre><p>And here is what <em>changeset/2</em> function will look like:</p><pre>def changeset(model, params \\ :empty) do<br>  model<br>  |&gt; cast(params, <a href="http://twitter.com/required_fields">@required_fields</a>, <a href="http://twitter.com/optional_fields">@optional_fields</a>)<br>  |&gt; validate_format(:email, ~r/@/, message: &quot;Email format is not valid&quot;)<br>  |&gt; validate_length(:password_plain, min: 5, message: &quot;Password should be 5 or more characters long&quot;)<br>  |&gt; validate_confirmation(:password_plain, message: &quot;Password confirmation doesn’t match&quot;)<br>  |&gt; unique_constraint(:email, message: &quot;This email is already taken&quot;)<br>  |&gt; validate_change(:terms_confirmed, fn<br>    _, true -&gt; []<br>    _, _ -&gt; [terms_confirmed: &quot;Please confirm terms and conditions&quot;]<br>  end)<br>  |&gt; cs_encrypt_password()<br>end</pre><p>In the User model we will also process users signin/signup actions. Signup will be very simple since all related logic is already defined in <em>changeset/2:</em></p><pre>def signup(params) do<br>  %__MODULE__{}<br>  |&gt; changeset(params)<br>  |&gt; Repo.insert()<br>end</pre><p>Signin will require a function to check password based on user model loaded and password provided by user<em>. </em>If user was not loaded (not found by email), we will perform a dummy password check. The reason for this check is in order to make user enumeration by timing responses more difficult. We might want this check only on real prod so let’s also add an if-condition to not do this unless we are running with <em>MIX_ENV=prod:</em></p><pre>defp check_password(%__MODULE__{password: hash} = user, password) do<br>  case Comeonin.Bcrypt.checkpw(password, hash) do<br>    true -&gt; {:ok, user}<br>    false -&gt; {:error, &quot;Invalid email or password&quot;}<br>  end<br>end<br>defp check_password(nil, _password) do<br>  if Mix.env == :prod do<br>    Comeonin.Bcrypt.dummy_checkpw()<br>  end<br>  {:error, &quot;Invalid email or password&quot;}<br>end</pre><p>Now when we can check passwords, let’s write signin function:</p><pre>def signin(params) do<br>  email = Map.get(params, &quot;email&quot;, &quot;&quot;)<br>  password = Map.get(params, &quot;password&quot;, &quot;&quot;)<br>  __MODULE__<br>  |&gt; Repo.get_by(email: String.downcase(email))<br>  |&gt; check_password(password)<br>end</pre><p>And here is complete code for <em>web/model/user.ex</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369a2b1a5a7c556cc8ceb493d605a66f/href">https://medium.com/media/369a2b1a5a7c556cc8ceb493d605a66f/href</a></iframe><p>Once you have User model in place, create Guardian serializer which will handle it’s serialization. Open file <em>lib/reph/guardian/serializer.ex</em> and put the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17e0e7426e81a13e0320b6d92378a8db/href">https://medium.com/media/17e0e7426e81a13e0320b6d92378a8db/href</a></iframe><p>To login and register, we will use websocket connection as a transport. Once user successfully registered, login action will be immediately fired to authorize him. Since we need user auth status on server side (stored in session) to allow or disallow access to our app, in response to login we’ll send user a short-lived token. This token must be used in very limited timeframe at a proxy verification page. If token successfully validated, we will authorize user with Guardian and redirect him to the app.</p><p>Let’s start with an Auth channel — web/channels/<em>auth_channel.ex </em>and add signin/signup handlers where we will send short-lived auth token to client in case of success:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d97e95ba35e0a0ecd4054d48cc212570/href">https://medium.com/media/d97e95ba35e0a0ecd4054d48cc212570/href</a></iframe><p>And add it to <em>web/channels/user_socket.ex</em> channels section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90f91734c6ce6c237c40252974a40928/href">https://medium.com/media/90f91734c6ce6c237c40252974a40928/href</a></iframe><p>Once client received <em>{:ok, jwt}</em> response, it should redirect user to the proxy page I’ve mentioned above. URL will be “<em>/?token=%JWT%</em>” and handler will locate in <em>PageConroller. </em>Update <em>web/controllers/page_controller.ex </em>with the handler (remember to put it before “index(conn, _params)” function because later matches everything):</p><pre>def index(conn, %{&quot;token&quot; =&gt; token}) do<br>  case Guardian.decode_and_verify(token) do<br>    { :ok, claims } -&gt;<br>      Guardian.revoke!(token)<br>      {:ok, user} = Guardian.serializer.from_token(claims[&quot;sub&quot;])<br>      conn<br>      |&gt; Guardian.Plug.sign_in(user)<br>      |&gt; redirect(to: &quot;/app&quot;)<br>    _ -&gt;<br>      redirect(conn, to: &quot;/&quot;)<br>  end<br>end</pre><p>Now when we have all the server code in place, let’s move to client-side.</p><p>To connect to auth channel, dispatch another <em>channel_join </em>action at <em>web/static/js/landing/store/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/145347adb3883cc365ac02141c91d782/href">https://medium.com/media/145347adb3883cc365ac02141c91d782/href</a></iframe><p>Now, we need an auth reducer where we will keep login failure status and registration errors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f1c49c445fa18744f707fd788c6ebe3/href">https://medium.com/media/4f1c49c445fa18744f707fd788c6ebe3/href</a></iframe><p>Don’t forget to add it to list of reducers in <em>web/static/js/landing/reducers/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/697657ef28dc02975b589b4c4b05c633/href">https://medium.com/media/697657ef28dc02975b589b4c4b05c633/href</a></iframe><p>To process forms inputs, we need a new set of actions, create <em>web/static/js/landing/actions/auth.js </em>and add <em>register/login</em> actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a258aa3c542f459b5767a6b80c28e592/href">https://medium.com/media/a258aa3c542f459b5767a6b80c28e592/href</a></iframe><p>And finally, we’ll create registration component. It will be a form with onSubmit handler calling “register” auth action and list of errors if any. Create <em>web/static/js/landing/components/Registration/index.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54740ddefd638fa871fb1b1c5f802d3b/href">https://medium.com/media/54740ddefd638fa871fb1b1c5f802d3b/href</a></iframe><p>Now the last thing to do is login form. Create <em>web/static/js/landing/components/Login/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42292353c248c722339cd616884c182d/href">https://medium.com/media/42292353c248c722339cd616884c182d/href</a></iframe><p>The forms are using some css-classes I’ve got styles for, open <em>web/static/styles/landing/index.less </em>and insert the following to the bottom of the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/429d6df5c12cb5f4e145c24104787422/href">https://medium.com/media/429d6df5c12cb5f4e145c24104787422/href</a></iframe><p>Now update <em>web/static/js/landing/routes/index.js </em>with routes to the auth components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ae7c4edb53f1eaef2121d911d94223e/href">https://medium.com/media/3ae7c4edb53f1eaef2121d911d94223e/href</a></iframe><p>and<em> web/static/js/landing/containers/App/index.js </em>with links to login/register:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c41a1c7121c62b50e165f52b38f3dcab/href">https://medium.com/media/c41a1c7121c62b50e165f52b38f3dcab/href</a></iframe><p>Authorization is done! Launch the app with “<em>mix phoenix.server” — </em>registration and login should work as expected: show errors if any and redirect to <em>/app (</em>which is not working so far) if everything is ok.</p><h4>Hello app.</h4><p>The last thing in our app will be the app itself. After login, user is redirected to “/app” but currently there’s nothing but error, let’s fix this. First, we need 2 more webpack configs: <em>webpack.app.config.js </em>and<em> webpack.app.server.config.js. </em>I’ve tried to avoid this and put both landing and app into 1 config but it didn’t work (most probably because my webpack-fu isn’t strong enough), let me know if you are aware of how to do this.</p><p>The configs will be almost same as for landing but will bundle “app” instead of “landing” and will not include copying of assets directory because we already do this in our landing webpack config. Here is the <em>webpack.app.config.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24f219a3c5761070d8e19a30729a0d4e/href">https://medium.com/media/24f219a3c5761070d8e19a30729a0d4e/href</a></iframe><p>and here is <em>webpack.app.server.config.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c28432ab9a3154ffc76f4206db7ba9d/href">https://medium.com/media/7c28432ab9a3154ffc76f4206db7ba9d/href</a></iframe><p>I also suggest renaming <em>webpack.config.js </em>to <em>webpack.landing.config.js </em>and <em>webpack.server.config.js </em>to <em>webpack.landing.server.config.js. </em>Too long, I know, but that’s the cost of explicitness.</p><p>Now when we have 4 watchers, it can be a good idea to add a function to generate similar watchers based on config name instead of copy same code again and again. Here is final <em>config/dev.exs:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec6646dba6b419f4d4a564301eb2c6f/href">https://medium.com/media/4ec6646dba6b419f4d4a564301eb2c6f/href</a></iframe><p>Next, create <em>web/controllers/app_controller.ex, </em>there’s nothing new in it except we will use Guardian plug to only allow authenticated users to access the controller. Also, logout action will be handled by the controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd394add511b4cd8ddc8b458dd929438/href">https://medium.com/media/dd394add511b4cd8ddc8b458dd929438/href</a></iframe><p>and let’s update Phoenix router: add new scope “/app” and use 2 Guardian plugs — VerifySession and LoadResource — for it via new “app” pipeline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46631c5a9b84cf20b6fc264c3bae8293/href">https://medium.com/media/46631c5a9b84cf20b6fc264c3bae8293/href</a></iframe><p>Since template will be the same as for PageController, just copy it to the <em>app </em>directory:</p><pre>cp -r web/templates/page web/templates/app</pre><p>App layout already have correct css/js paths in place so the only thing left is to create an empty view file for app controller — web/views/app_view.ex:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3063f1f7b03c94d7fe3fb40c15af7624/href">https://medium.com/media/3063f1f7b03c94d7fe3fb40c15af7624/href</a></iframe><p>And that’s all we need on server side. The rest is the app client code.</p><p>Let’s prepare our app static files:</p><pre>cd web/static</pre><pre># most of code will remain the same<br>cp -r js/landing/* js/app/<br>cp -r styles/landing/* styles/app/</pre><pre># these files are not needed for app<br>cd js/app<br>rm -rf actions/auth.js components/Login components/Registration reducers/auth.js</pre><pre># Let&#39;s get back to our root before next steps<br>cd ../../../../</pre><p>Next, update <em>web/static/js/app/routes/index.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d1f59a38e2c12d34951a7476a9d5037/href">https://medium.com/media/7d1f59a38e2c12d34951a7476a9d5037/href</a></iframe><p>We removed auth-related stuff so let’s clean up our code accordingly. Remove auth reducer from <em>web/static/js/app/reducers/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87d89b8ec40d01b89021317ec5358802/href">https://medium.com/media/87d89b8ec40d01b89021317ec5358802/href</a></iframe><p>And remove connection to <em>auth </em>channel from <em>web/static/js/app/store/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05488719d7a7ea79e95d93fa427710ac/href">https://medium.com/media/05488719d7a7ea79e95d93fa427710ac/href</a></iframe><p>I’m going to use <a href="http://getbootstrap.com/examples/dashboard/">the Dashboard template example</a> from Bootstrap for the app so let’s update app styles first. We will remove everything but <em>Bootstrap</em> import from <em>web/static/styles/app/index.less </em>and insert styles provided with the template. Finally, the styles file will look like following (I’ve converted CSS to less automatically):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a7ee7b9e1f6f48f5a41ca2fe0ddc43/href">https://medium.com/media/b2a7ee7b9e1f6f48f5a41ca2fe0ddc43/href</a></iframe><p>Now, update <em>web/static/js/app/containers/App/index.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e8755b888cfa3ee09c18f01a985917d/href">https://medium.com/media/4e8755b888cfa3ee09c18f01a985917d/href</a></iframe><p>and <em>web/static/js/app/components/Main/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37268e365651a65516309cc3cf04ed51/href">https://medium.com/media/37268e365651a65516309cc3cf04ed51/href</a></iframe><p>Now we have fully functional app. Run “<em>mix phoenix.server”</em> and play around with authorization and two different apps. That’s a good start point for something great!</p><h4>Stay tuned!</h4><p>In next part we will either write more useful application (users management, for example, or will start developing yet another blog), or prepare the current one for real production with refactoring and caching server-rendered JS. Comments are yours to vote for the “<em>RePh 3”</em> topic!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a6dcadbbd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phoenix + React: love story. RePh 1.]]></title>
            <link>https://medium.com/@chvanikoff/phoenix-react-love-story-reph-1-c68512cfe18?source=rss-b729aa603207------2</link>
            <guid isPermaLink="false">https://medium.com/p/c68512cfe18</guid>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Roman Chvanikov]]></dc:creator>
            <pubDate>Fri, 06 May 2016 20:23:42 GMT</pubDate>
            <atom:updated>2017-06-20T15:14:20.746Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Want to start building RePh app without carrying about scaffolding? Good news: I just released RePh app generator, <a href="https://medium.com/@chvanikoff/reph-react-phoenix-app-scaffolding-made-easy-346cddc76838">take a look</a>!</blockquote><p>Hi, in this article I’m going to show you, how to create a fullstack app with React and Phoenix. There are already a few similar tutorials out there, however none of them shows process of development for a complete functional app with server-side rendering and routing. The article is about to fill the gap. In the first part we will create a basic (but yet functional) app which will copy standard Phoenix app layout and will include real-time statistics of visitors: number of total, online and max. online users. The app name is RePh which stands for REactPHoenix.</p><p>Complete app code is available at Github, every step lives in it’s own commit: <a href="https://github.com/chvanikoff/reph">https://github.com/chvanikoff/reph</a></p><p>The demo is available at <a href="https://reph.herokuapp.com/">https://reph.herokuapp.com</a> but is only available 18h/day due to Heroku free dyno limitation. If you see `Application Error` message — this is the case.</p><h4>Primary tech stack used.</h4><ul><li>Elixir 1.2.5</li><li>Node 4.4.3</li><li>NPM 3.8.9</li><li>WebPack 1.13.0</li><li>Phoenix 1.1.4</li><li>React 15.0.2</li></ul><h4>Getting started.</h4><p>First of all we will create a Phoenix app named <em>reph. </em>I’m using <em>~/phoenix </em>directory for my Phoenix projects so change it to the one you prefer. During project generation you will be suggested to install dependencies — answer “no”. This will save your time because fetching npm deps usually takes long and we will not need the ones installed by default with Phoenix app generator.</p><pre>mix phoenix.new ~/phoenix/reph</pre><p>Once we have a fresh Phoenix app in place, let’s install all deps we will need and clean it up a bit — there’s some stuff we will not need and some we would like to change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb966da5138e640cedee0a62adbb4228/href">https://medium.com/media/fb966da5138e640cedee0a62adbb4228/href</a></iframe><p>Now let’s create a WebPack config file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2900acad3a8fb2f49a0072c7f3728596/href">https://medium.com/media/2900acad3a8fb2f49a0072c7f3728596/href</a></iframe><p>And final step in our setup is to replace Brunch with Webpack in config/dev.exs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/777e53cbbcc2f4fc61ed1276b0055b0e/href">https://medium.com/media/777e53cbbcc2f4fc61ed1276b0055b0e/href</a></iframe><h4>Hello Phoenix.</h4><p>In this part we will reproduce a simple starter Phoenix page. First look at <em>web/templates/layout/app.html.eex — </em>the whole app is in &lt;div class=”container”&gt;&lt;/div&gt;. It will be our primary React App container. The <em>web/templates/page/index.html.eex </em>content will be moved to a React component. Remove everything but inner view and JS tag from the <em>web/template/layout/app.html.eex </em>layout file so it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/061973a25c88638754060d857ea58c5d/href">https://medium.com/media/061973a25c88638754060d857ea58c5d/href</a></iframe><p>and replace all the <em>web/templates/page/index.html.eex </em>file contents with a single div — here we will render our React app:</p><pre>&lt;div id=&quot;index&quot;&gt;&lt;/div&gt;</pre><p>Now create App container in <em>containers/App/index.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb22e42ae55f3480fd01a7651d0f48b3/href">https://medium.com/media/bb22e42ae55f3480fd01a7651d0f48b3/href</a></iframe><p>The <em>render()</em> function returns almost the same what Phoenix default layout does. However, don’t forget to replace all “class=” with “className=” while copying HTML to React classes as JSX. Also don’t forget to close all single-tags like &lt;hr/&gt; or &lt;img/&gt; with trailing slash.</p><p>The container is a wrapper around our components and it will remain the same for all the routes inside the initial one, “/” in case of our simple app. The only part that will change when route changes will be <em>{this.props.children}.</em></p><p>Now let’s write our only component which will render all the <em>web/templates/page/index.html.eex</em>, the component will be located in <em>components/Main/index.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8139f796cf4a5b9159cd96f4f75527b6/href">https://medium.com/media/8139f796cf4a5b9159cd96f4f75527b6/href</a></iframe><p>Next thing we need is a router, it will be pretty much simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ad33e2d5142cd0f3cda006fb42bdd26/href">https://medium.com/media/1ad33e2d5142cd0f3cda006fb42bdd26/href</a></iframe><p>Now let’s define our app state and reducers required. Initially we’ll focus on the basic app without any logic — at this point our primary goal is to make the app render all the same what Phoenix does by default. This means our app’s state will be empty. However, it still must contain routing object in it. Let’s create a simple reducer at <em>reducers/index.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee1649506a60041085b371d41ea676b/href">https://medium.com/media/5ee1649506a60041085b371d41ea676b/href</a></iframe><p>Next what we need is a <em>store</em>, as long as we are writing a minimal working app, it will be very simple. Create a <em>store/index.js</em> file with following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2b30d52ae3bd8d2937f28a2588fda70/href">https://medium.com/media/a2b30d52ae3bd8d2937f28a2588fda70/href</a></iframe><p>Router is also usually kept in container so we need to create <em>containers/index.js</em> since router is the app’s entry point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23321a737b2e036944cdd246fabb2168/href">https://medium.com/media/23321a737b2e036944cdd246fabb2168/href</a></iframe><p>Now it’s time to connect all the parts together, create <em>index.js</em> file which will be an entry point for webpack to compile the app</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19a8338682700c0fa24ff78654ed8c66/href">https://medium.com/media/19a8338682700c0fa24ff78654ed8c66/href</a></iframe><p>Last thing to do is to replace embedded into <em>styles/index.less </em>Bootstrap with the NPM dependency. First, we will be able to easily customize it if needed, and second it’s just needless to have there. Open <em>web/static/styles/index.less</em> and replace all the Bootstrap code with this line:</p><pre><a href="http://twitter.com/import">@import</a> &quot;~bootstrap/less/bootstrap&quot;;</pre><p>From here we are good to compile and launch the app. Run</p><pre>mix phoenix.server</pre><p>and open <a href="http://localhost:4000/">http://localhost:4000</a> to see the basic Phoenix page was rendered with React.</p><h4>Hello visitors.</h4><p>To track visitors, we will use a stateful gen_server. It will have 3 API functions we’ll use: <em>add/0</em> to be called when a client joins, <em>remove/0</em> to be called when a client leaves and <em>state/0</em> to provide connected clients with current state. Here is the code for complete server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db9d4905e347cb45f17d849b7d7def6b/href">https://medium.com/media/db9d4905e347cb45f17d849b7d7def6b/href</a></iframe><p>To make the server usable, we must add it into our supervision tree. Open <em>lib/reph.ex</em> and add</p><pre>worker(Reph.Visitors, [])</pre><p>to the list of app supervisor children, right after the comment “<em># Here you could define other workers and supervisors as children</em>”.</p><p>Now we need a reducer to get this state on client, it will process state initialization and replicate the server’s logic. Create <em>reducers/visitors.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320b5c18c586985b746cf069960dfcb6/href">https://medium.com/media/320b5c18c586985b746cf069960dfcb6/href</a></iframe><p>and add the reducer to <em>reducers/index.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4794a557ec23468ac47efc9fea734df2/href">https://medium.com/media/4794a557ec23468ac47efc9fea734df2/href</a></iframe><p>Now when we can use the state in our app, let’s update <em>components/Main/index.js</em>, we will use <em>connect </em>from <em>react-redux </em>library to access application state (and <em>visitors</em> in it). New version of the Main component will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c08716de7e811b8801c612ec85a3878/href">https://medium.com/media/6c08716de7e811b8801c612ec85a3878/href</a></iframe><p>You can run the app and see the state was rendered. However it is useless so far, we must add server-client communication layer to register and unregister client, provide it with initial state and update on new connections. Obviously, we’re going to handle all of this with websockets and I’d suggest to keep websocket and channels in state having another reducer for it. I’ve seen a lot tutorials with WS and it’s callbacks put directly into store or even entry (<em>index.js) </em>file, but I always felt wrong doing this — mostly because of difficult access to the objects when it’s needed. Create a new reducer in <em>reducers/ws.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cd3df5e45a3151c6e2e0e9e0a1e8683/href">https://medium.com/media/2cd3df5e45a3151c6e2e0e9e0a1e8683/href</a></iframe><p>and add it to <em>reducers/index.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9510f79caba388e2a113f18fab8255e3/href">https://medium.com/media/9510f79caba388e2a113f18fab8255e3/href</a></iframe><p>To connect to websocket and channels, we need to specify certain actions — we will do this with action creators. Create a file <em>actions/ws.js:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d95a4c6e0409af41c2a1c06c42be71/href">https://medium.com/media/58d95a4c6e0409af41c2a1c06c42be71/href</a></iframe><p>Now we can connect to websocket but let’s first create functional channel to connect to. Open <em>web/channels/user_socket.ex</em> and add the following route in it (right after commented “Channels” section):</p><pre>channel &quot;visitors&quot;, Reph.VisitorsChannel</pre><p>Our <em>VisitorsChannel</em> will be capable of sending current Visitors state and adding a new one on connect, removing visitor from state on disconnect and broadcasting all incoming add/remove event messages to clients. Here is the file <em>web/channels/visitors_channel.ex</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52b3a1f465feae757e23f31b28b6c88/href">https://medium.com/media/b52b3a1f465feae757e23f31b28b6c88/href</a></iframe><p>The only thing left on server side is broadcasting event messages when we update Visitors state, let’s extend the module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b5de988b31bbea6208903d11fd223c5/href">https://medium.com/media/4b5de988b31bbea6208903d11fd223c5/href</a></iframe><p>Now we are ready to serve our client app so let’s connect it with websocket. Open <em>web/static/js/store/index.js </em>and update it to make look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64b39d0fa3910e34dace211718cbafa7/href">https://medium.com/media/64b39d0fa3910e34dace211718cbafa7/href</a></iframe><p>Here we go! Launch the app with</p><pre>mix phoenix.server</pre><p>and play around with live visitors counter.</p><h4>Hello server-side rendering.</h4><p>This part will be culmination of our simple app development. We already have it working, but what we want now is to perform initial rendering on server side. How we are going to handle this? With 2 libraries: <a href="https://github.com/mjackson/react-stdio"><em>react-stdio</em></a><em> </em>to compile React app and <a href="https://github.com/hassox/std_json_io/"><em>std_json_io</em></a><em> </em>to deliver the result to clients. But before diving into usage of these libraries, we’ll need to make our JS bundle server-friendly. First, we must create a new Webpack config file to create the bundle in a bit different way: it should be compiled as a commonjs2 library and the entry point will be our app index container since the only thing we need the library to return is the component to render. Also we will skip everything but JS. Here is the config for server, save it as <em>webpack.server.config.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3ffb50015679324936ef26598d2636d/href">https://medium.com/media/b3ffb50015679324936ef26598d2636d/href</a></iframe><p>To automatically recompile the server bundle as well as regular one, add a new watcher to <em>config/dev.exs, </em>finally <em>watchers</em> value should be this<em>:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf0236ad96dac6522c5b1e2f07735e76/href">https://medium.com/media/cf0236ad96dac6522c5b1e2f07735e76/href</a></iframe><p>There is some code in our app that should only be executed in browser, like websocket connection. Also, routing must be synchronized between client and server so when you add a new route “<em>/mypage”, </em>you can access it directly, not only from the index page of the app. This means we must update our JS. To determine if the code is running in browser we will simply use <em>typeof window !== “undefined” </em>condition.</p><p>First, let’s remove dispatching of WSActions if we are not in browser. Open <em>store/index.js</em> and add the if-condition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fb4c2d3f182f8ab6aa8d46d95998100/href">https://medium.com/media/7fb4c2d3f182f8ab6aa8d46d95998100/href</a></iframe><p>All the routing/initializing logic is determined in our root container — <em>containers/index.js</em>. Remember we have a state in our app? We will pass it to the container on server-side via <em>props</em> attribute and we will set global JS variable <em>__INITIAL__STATE__</em> to use on client-side even before receiving the one from websocket. State received from WS will just update it if needed. To use the initial state on client, you should pass it to createStore function in <em>store/index.js</em> as second argument. The <em>configureStore</em> function will receive it from Index container:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8f882033dd969768e6ed5b5bb8928fa/href">https://medium.com/media/b8f882033dd969768e6ed5b5bb8928fa/href</a></iframe><p>Now it’s time to update the Index container. It will be responsible for proper requests routing on server and for passing initial state down to <em>configureStore.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/860e3ebc654de5fbca7e0ae3152fb135/href">https://medium.com/media/860e3ebc654de5fbca7e0ae3152fb135/href</a></iframe><p>It was our final step in client-side, now we need to compile the server bundle on user’s request to send it to him. In a real world I’d use precompiled (cached) bundles which are recompiled on the related state change. One day I will cover this topic as well but now we are still building a simple app and generating the bundle on the fly will work just fine.</p><p>Now we need to setup <em>std_json_io</em>, which will take care of managing pool of react-stdio workers and communicating with them. Add <em>{:std_json_io, “~&gt; 0.1”} </em>to list of deps and :std_json_io to list of apps in <em>mix.exs:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8d7104fa8b7413407ef77f8f86efe1/href">https://medium.com/media/fb8d7104fa8b7413407ef77f8f86efe1/href</a></iframe><p>run mix deps.get to fetch the library and then create a module in lib/reph/react_io.ex:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e07341943e7abad33b27bbce5698cdc/href">https://medium.com/media/6e07341943e7abad33b27bbce5698cdc/href</a></iframe><p>This module is a supervisor for react-stdio workers so add it to our supervision tree next to Visitors worker:</p><pre>supervisor(Reph.ReactIO, [])</pre><p>In <em>PageController</em>, we are going to include React-generated HTML as well as initial state into template params. Here is how we will do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c882cb9e5588bc31dd1851e5d6e3274b/href">https://medium.com/media/c882cb9e5588bc31dd1851e5d6e3274b/href</a></iframe><p>And now we can update <em>page/index.html.eex</em> to embed the generated HTML and initial state into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b0fe181012eb2be0f3926a1e6552a03/href">https://medium.com/media/8b0fe181012eb2be0f3926a1e6552a03/href</a></iframe><p>We are passing <em>conn.request_path</em> to our JS but currently we only serve “/” location. To serve all requests with PageController, replace <em>get “/”</em> with <em>forward “/”</em> in your web/router.ex:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cf761a1b6756b7932690f7acb14b1a2/href">https://medium.com/media/7cf761a1b6756b7932690f7acb14b1a2/href</a></iframe><p>Next step is… Hold on, there is no next step! That’s it, go run mix phoenix server and enjoy the fact that you know how to create fullstack apps with Phoenix and React! =)</p><h4>Hello DevTools.</h4><p>It is worth nothing to add <a href="https://github.com/zalmoxisus/redux-devtools-extension">Redux Devtools for Chrome extension</a> so why not? Since this is a store enhancer, we will need <em>compose</em> utility from <em>redux</em> library to actually compose it with <em>applyMiddleware</em> enhancer. The devtools enhancer will look like following:</p><pre>const devToolsExt = typeof window === &quot;object&quot; &amp;&amp; typeof window.devToolsExtension !== &quot;undefined&quot;<br>  ? window.devToolsExtension()<br>  : f =&gt; f;</pre><p>and the complete <em>store/index.js</em> code will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c277df43e4e60dd8802124f71b8a2a18/href">https://medium.com/media/c277df43e4e60dd8802124f71b8a2a18/href</a></iframe><p>Install the chrome extension from the <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd">extension page</a> and run the app, you should see Redux Devtools icon turned on, also it should be available from context menu.</p><h4>Next part</h4><p>In next part we will improve this app with authorization and different apps for guests and logged in users.</p><p><a href="https://medium.com/@chvanikoff/phoenix-react-love-story-reph-2-14a6dcadbbd0#.qh7ai7t75">Go to part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c68512cfe18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>