<?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 Fredrik Andersson on Medium]]></title>
        <description><![CDATA[Stories by Fredrik Andersson on Medium]]></description>
        <link>https://medium.com/@fredrikanderzon?source=rss-81855f0dd6eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dtZi5LyWe_fiuUKO15PMlQ.jpeg</url>
            <title>Stories by Fredrik Andersson on Medium</title>
            <link>https://medium.com/@fredrikanderzon?source=rss-81855f0dd6eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:02:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fredrikanderzon/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[Setting up SSH keys for multiple Bitbucket/Github accounts]]></title>
            <link>https://medium.com/@fredrikanderzon/setting-up-ssh-keys-for-multiple-bitbucket-github-accounts-a5244c28c0ac?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5244c28c0ac</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Tue, 14 Mar 2017 13:02:31 GMT</pubDate>
            <atom:updated>2018-12-27T09:10:58.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time I switch computers I go through this dance of setting up new SSH keys for my different code repository accounts.</p><p>Coincidentally, every time I switch computers I’ve completely forgotten how to set up different SSH keys for my different accounts, leading to me Googling and looking through my old .ssh folder a lot trying to figure it out.</p><p>So this post is for future me, and probably present you, since you are here. 🤔</p><h3>Generating keys</h3><p>If you are setting up a new machine, first generate a key to the default ~/.ssh/id_rsa by running:</p><pre>ssh-keygen -t rsa<br>ssh-add ~/.ssh/id_rsa</pre><blockquote><em>The created key is a private key you should never share with anyone. A public key </em><em>~/.ssh/id_rsa.pub will also be created.</em></blockquote><p>You will be prompted for the location to save the keys in, hit enter to accept the default. You will also be asked for a passphrase to protect the key, enter anything you want here.</p><p>The idea is that you’ll use this key for your personal accounts.</p><p>Next, for each company account you have, run this command (substituting companyName to something more meaningful), which tags the key with companyName and saves it to ~/.ssh/companyName.</p><pre>cd ~/.ssh<br>ssh-keygen -t rsa -C &quot;companyName&quot; -f &quot;companyName&quot;<br>ssh-add ~/.ssh/companyName</pre><p>That takes care of generating the keys, next up you have some SSH config to write.</p><h3>Config</h3><p>Open up the SSH config file:</p><p>nano ~/.ssh/config</p><p>Don’t worry if this file doesn’t already exists, it will be created later when you save your changes.</p><p>What you will do is add rules for different hosts.</p><pre>Host bitbucket.org<br>  HostName bitbucket.org<br>  IdentityFile ~/.ssh/id_rsa</pre><pre>Host companyname.bitbucket.org<br>  HostName bitbucket.org<br>  IdentityFile ~/.ssh/companyName</pre><pre>Host github.com<br>  HostName github.com<br>  IdentityFile ~/.ssh/id_rsa</pre><pre>Host companyname.github.com<br>  HostName github.com<br>  IdentityFile ~/.ssh/companyName</pre><p>First you make sure that requests to plain bitbucket.org uses the default ~/.ssh/id_rsa that you set up for your personal account.</p><p>Next, add a rule for companyname.bitbucket.org and make it use the ~/.ssh/companyName key instead.</p><blockquote><em>companyname.bitbucket.org can be anything that makes sense to you </em><em>FluffyBunny or </em><em>Bow-Ties-Are-Cool. A subdomain makes sense to me, and it&#39;s a format that I remember when cloning repositories.</em></blockquote><p>The Github config is just a repeat of the Bitbucket config.</p><p>When you are happy with how your config looks, save the changes by hitting CTRL+O (CTRL+X to exit the file).</p><h3>Adding SSH keys to Bitbucket/Github</h3><p>You’re all set locally, now we just need to tell Bitbucket/Github to trust these keys you have created.</p><p>The key you share with these services is the public key, copy it to your clipboard with:</p><p>pbcopy &lt; ~/.ssh/id_rsa.pub</p><p>Now log in to Bitbucket or Github and add your SSDH key.</p><p>In Bitbucket:</p><ol><li>Click on your user icon in the top right and select Bitbucket settings from the menu</li><li>Click on SSH keys in the left hand menu</li><li>Click the Add key button, enter whatever you want for label and paste your key into the box below.</li><li>Click ‘Add key’ and you are done</li></ol><p>In Github:</p><ol><li>Click on your user icon in the top right and select Settings from the menu</li><li>Click SSH and GPG keys in the left hand menu.</li><li>Click the New SSH key button, enter whatever you want for title and paste your key in the box below</li><li>Click Add key and you&#39;re done</li></ol><p><em>Repeat process for the next account, except this time copy the companyName key </em><em>pbcopy &lt; ~/.ssh/companyName.pub</em></p><h3>Cloning repositories</h3><p>With all the setup done you should be ready to clone a repository.</p><p>Personal projects can now be cloned by following the normal directions given by Bitbucket/Github, like this:</p><p>git clone git@bitbucket.org:yourPersonalAccount/pet-project.git</p><p>Your default SSH key will verify your access and you will be able to pull and push as much as you want.</p><p>For your work projects however, one alteration needs to be made, in a command like this:</p><p>git clone git@bitbucket.org:companyName/company-project.git</p><p>bitbucket.org should be replaced by companyname.bitbucket.org (or whatever matches the SSH rules you set up earlier).</p><p>git clone git@companyname.bitbucket.org:companyName/company-project.git</p><p>This will ensure that the correct SSH key is used and verify your identity with Bitbucket/Github.</p><p>That’s all folks! 👋</p><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2017/03/14/setting-up-ssh-keys-for-multiple-bitbucket-github-accounts/"><em>fredrik.anderzon.se</em></a><em> on January 31, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5244c28c0ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust code style and Rustfmt]]></title>
            <link>https://medium.com/@fredrikanderzon/rust-code-style-and-rustfmt-4f69fbd87c18?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f69fbd87c18</guid>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Sun, 05 Feb 2017 19:56:55 GMT</pubDate>
            <atom:updated>2017-02-05T19:56:55.009Z</atom:updated>
            <content:encoded><![CDATA[<p>Coming to Rust most recently from the JavaScript world I was used to code style being something that was wildly debated and something that would change from project to project I worked on.</p><p>In Rust land, however, things are quite different.</p><p>For one thing the strong type system and the compiler’s borrow, ownership and lifetime checking simply makes some bad code style from JavaScript impossible in Rust.</p><p>There is also a whole different level of consensus in the Rust camp on things like variable naming (snake_case), trailing commas (yes), indentation (4 spaces). And the language has no automatic semicolon insertion so there is no semicolon debate.</p><p>It helps that there is an official page in the Rust docs with style guidelines <a href="https://doc.rust-lang.org/1.12.0/style/README.html">https://doc.rust-lang.org/1.12.0/style/README.html</a>.</p><p>A few of these rules are checked by the compiler itself, while the rest is left to the excellent <a href="https://github.com/rust-lang-nursery/rustfmt">Rustfmt tool</a>.</p><h3>Rustfmt</h3><p>To install Rustfmt, simply run (assuming you have <a href="https://www.rustup.rs/">rustup</a> installed): rustup run nightly cargo install rustfmt</p><p>Rustfmt has several modes you can run it in. To simply list the problems, as a linter might, run it in diff mode. cargo fmt -- --write-mode=diff</p><p>The default if you just run cargo fmt is to use the replacemode, which will fix all code style issues, and make a .bk backup file for every changed file.</p><p>Since I just want something that keeps all code in the same style I use the overwrite mode: cargo fmt -- --write-mode=overwrite</p><h3>Install Rustfmt in Atom</h3><p>I don’t actually run that command though, I have Rustfmt integrated into Atom, so that it fixes my code style everytime I save.</p><p>To use Rustfmt in Atom you use the atom-beautify package.</p><p>Go to Atom &gt; Preferences &gt; Install and search for atom-beautify.</p><p>Install it and then click Settings, you&#39;ll have a list of languages there, scroll down to Rust:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cYU4zzAc_zE0nz66UsZUA.png" /></figure><p>Make sure Beautify on save is checked and enter the path rustfmt below. The easiest way to get the path is to run which rustfmt in your terminal.</p><p>Having Rustfmt format your code every time you save is like having a buddy proofread your code and fix it for you. 🤓</p><blockquote><em>If you don’t use Atom, there are Rustfmt integrations for other editors. Check the </em><a href="https://github.com/rust-lang-nursery/rustfmt"><em>Rustfmt readme</em></a><em> for more info.</em></blockquote><h3>Skipping code</h3><p>If you know you are going to write weird looking code but want to keep it that way you can add #[cfg_attr(rustfmt, rustfmt_skip)] before the your code you want to keep intact.</p><h3>Configuring Rustfmt</h3><p>I’m perfectly happy using the default settings, and I think it’s a strength to keep it that way, but if you absolutely can’t stand one of the things Rustfmt does it is very configurable.</p><p>Create a rustfml.toml in the root of your project and add any rule changes you want. Run rustfmt --config-helpto get a list of all rules and possible values.</p><p>This would be the contents of rustfmt.toml if you can&#39;t stand trailing commas in structs for example:</p><pre>struct_trailing_comma = &quot;Never&quot;</pre><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2017/01/31/rust-code-style-and-rustfmt-2/"><em>fredrik.anderzon.se</em></a><em> on January 31, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f69fbd87c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Error types in Rust and the ? operator]]></title>
            <link>https://medium.com/@fredrikanderzon/custom-error-types-in-rust-and-the-operator-b499d0fb2925?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b499d0fb2925</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Sun, 05 Feb 2017 19:46:02 GMT</pubDate>
            <atom:updated>2017-02-19T16:45:18.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was “forced” into writing some Rust again, after a few months of working on other things, because I had made a commitment to give a talk on the <a href="https://rocket.rs/">Rocket framework</a> — a beautiful web framework for Rust.</p><blockquote><em>The slides from the talk can be found </em><a href="http://rest-in-rust.surge.sh/"><em>here</em></a><em> and a more detailed blog post is coming soonish. Meanwhile, the source code can be found </em><a href="https://github.com/fanderzon/rocket-api/tree/step3-error-handling"><em>here</em></a></blockquote><h3>The problem</h3><p>One thing I didn’t have time to finish in time for the presentation was custom Error handling, my route handlers would simply return diesel::result::Error if anything went wrong with the database request (including trying to query missing records).</p><pre>#[get(&quot;/notes/&lt;id&gt;&quot;, format = &quot;application/json&quot;)]<br>fn note_get(db: DB, id: i32) -&gt; Result&lt;JSON&lt;Note&gt;, diesel::result::Error&gt; {<br>    let note = get_note(db.conn(), id);<br>    match note {<br>        Ok(note) =&gt; Ok(JSON(note)),<br>        Err(err) =&gt; Err(err),<br>    }<br>}</pre><p>Since Rocket doesn’t understand anything about a Diesel error, other than it being an error, the server will respond with 500 Internal Server Error.</p><p>I will be absolutely fine with that for most errors, if the database is down, or if parsing a query failed, but I do want to catch any diesel::result::Error::NotFound errors so that I can return 404.</p><h3>Rocket’s Responder trait</h3><p>Now, for Rocket to take an Error and use it as a response, the Error needs to implement Rocket&#39;s Responder trait.</p><p>It’s going to look like this in my case:</p><pre>impl&lt;&#39;r&gt; Responder&lt;&#39;r&gt; for Error {<br>    fn respond(self) -&gt; Result&lt;Response&lt;&#39;r&gt;, Status&gt; {<br>        match self {<br>            Error::NotFound =&gt; Err(Status::NotFound),<br>            _ =&gt; Err(Status::InternalServerError),<br>        }<br>    }<br>}</pre><p>All we have to do inside the respond function is to add our own logic for taking the error from self and returning a Rust Result error containing the Rocket Status we want.</p><h3>A custom error type</h3><p>A logical idea would be to import diesel::result::Error and implement Rocket&#39;s Responder trait on it. If that worked we would be done here. 😎</p><p>Unfortunately (quick fix wise), Rust will not let you implement traits from one external crates on types from another external crate. Which means we will have to create our own error type, and implement Rocket’s Responder trait on this new type.</p><p>So let’s get to work! We’ll start off with this enum:</p><pre>#[derive(Debug)]<br>pub enum Error {<br>    NotFound,<br>    InternalServerError,<br>}</pre><p>Next, any Rust error needs to implement the Display and Error traits from the standard library.</p><pre>use std::fmt;<br>use std::error::Error as StdError;</pre><pre>impl fmt::Display for Error {<br>    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {<br>        match *self {<br>            Error::NotFound =&gt; f.write_str(&quot;NotFound&quot;),<br>            Error::InternalServerError =&gt; f.write_str(&quot;InternalServerError&quot;),<br>        }<br>    }<br>}</pre><pre>impl StdError for Error {<br>    fn description(&amp;self) -&gt; &amp;str {<br>        match *self {<br>            Error::NotFound =&gt; &quot;Record not found&quot;,<br>            Error::InternalServerError =&gt; &quot;Internal server error&quot;,<br>        }<br>    }<br>}</pre><p>This is the minimum we need to implement, a printable representation of the errors for Display, and a description of the errors for Error.</p><blockquote><em>Error also let&#39;s you implement an optional </em><em>cause method that can return a reference to the error that caused your error. Not very useful for this use case.</em></blockquote><p>If we combine that with the Rocket Responder implementation earlier, we could now write our Rocket handler like this:</p><pre>use diesel::result::Error;<br>use error::Error as ApiError;</pre><pre>#[get(&quot;/notes/&lt;id&gt;&quot;, format = &quot;application/json&quot;)]<br>fn note_get(db: DB, id: i32) -&gt; Result&lt;JSON&lt;Note&gt;, ApiError&gt; {<br>    let note = get_note(db.conn(), id);<br>    match note {<br>        Ok(note) =&gt; Ok(JSON(note)),<br>        Err(err) =&gt; {<br>            match err {<br>                Error::NotFound =&gt; Err(ApiError::NotFound),<br>                _ =&gt; Err(ApiError::InternalServerError),<br>            }<br>        }<br>    }<br>}</pre><p>We call our custom error type ApiError and the Diesel error Error.</p><p>We try to fetch a note from the database, and match the result, if we successfully get a note we return it as JSON.</p><p>If it is an error, however, we do another match, and map the Diesel Error::NotFound to our own ApiError::NotFound, and any other Diesel errors to ApiError::InternalServerError.</p><p>This works, Rocket will now receive our error and process it using the Responder trait. It is a lot of code to write in every handler though.</p><h3>The From trait</h3><p>Once upon a time Rust had a trait called FromError, it was specifically designed to handle conversions between different error types.</p><p>It has since been generalized into From that can handle conversions between any types.</p><p>It works like this:</p><pre>impl From&lt;DieselError&gt; for Error {<br>    fn from(e: DieselError) -&gt; Self {<br>        match e {<br>            DieselError::NotFound =&gt; Error::NotFound,<br>            _ =&gt; Error::InternalServerError,<br>        }<br>    }<br>}</pre><p>Basically the same as the error match we just wrote in the route handler. Since we have now moved the conversion logic here we can shorten the route handler to look like this:</p><pre>#[get(&quot;/notes/&lt;id&gt;&quot;, format = &quot;application/json&quot;)]<br>fn note_get(db: DB, id: i32) -&gt; Result&lt;JSON&lt;Note&gt;, ApiError&gt; {<br>    let note = get_note(db.conn(), id);<br>    match note {<br>        Ok(note) =&gt; Ok(JSON(note)),<br>        Err(err) =&gt; Err(ApiError::from(err)),<br>    }<br>}</pre><p>ApiError::from(err) is pretty succinct. Still, we can this code even shorter, and easier to read (IMO anyway).</p><h3>The try! macro</h3><p>One of the biggest advantages of implementing From is that it would be automatically called by Rust&#39;s try! macro.</p><p>The try! is essential to error handling in Rust, as it will get the value from a Result, or exits early if the Result contains an error, propagating the error to the caller of the current function (and calling From::from on any errors).</p><p>Using the try! macro our route handler can be shortened to this:</p><pre>#[get(&quot;/notes/&lt;id&gt;&quot;, format = &quot;application/json&quot;)]<br>fn note_get(db: DB, id: i32) -&gt; Result&lt;JSON&lt;Note&gt;, ApiError&gt; {<br>    let note = try!(get_note(db.conn(), id));<br>    Ok(JSON(note))<br>}</pre><p>If the try! fails, the function will exit immediately with an ApiError, so we can be sure that on the line below, we have a note (or more specifically, we can be sure that get_note returned a Result with Ok and not Err).</p><h3>The ? operator</h3><p>By adding a ? to something that returns a Result you get the same behavior as if you had used try!.</p><pre>#[get(&quot;/notes/&lt;id&gt;&quot;, format = &quot;application/json&quot;)]<br>fn note_get(db: DB, id: i32) -&gt; Result&lt;JSON&lt;Note&gt;, ApiError&gt; {<br>    let note = get_note(db.conn(), id)?;<br>    Ok(JSON(note))<br>}</pre><p>This is the final version of this function, and I’m quite happy with how it looks.</p><blockquote><em>More changes to Rust’s error handling is proposed in the same </em><a href="https://github.com/rust-lang/rfcs/blob/master/text/0243-trait-based-exception-handling.md"><em>RFC</em></a><em> that introduced the </em><em>? operator.</em></blockquote><p>The full source code for the Rocket based API with error handling applied can be found <a href="https://github.com/fanderzon/rocket-api/tree/step3-error-handling">here</a>.</p><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2017/02/05/custom-error-types-in-rust-and-the-question-mark-operator/"><em>fredrik.anderzon.se</em></a><em> on February 5, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b499d0fb2925" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding create-react-app scripts to an existing project]]></title>
            <link>https://medium.com/@fredrikanderzon/adding-create-react-app-scripts-to-an-existing-project-207cfe3cd190?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/207cfe3cd190</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Sun, 04 Dec 2016 20:00:35 GMT</pubDate>
            <atom:updated>2018-11-22T09:07:11.709Z</atom:updated>
            <content:encoded><![CDATA[<p>I love <a href="https://github.com/facebookincubator/create-react-app"><strong>create-react-app</strong></a>, I’ve used it to scaffold every new React app and React experiment I’ve worked on since it was released.</p><p>As I was updating one little hobby project (<a href="https://github.com/fanderzon/markdown-to-medium-tool">Markdown To Medium Tool</a>) I built before <em>Create React App</em> I realized I wanted it to have the same webpack config, and the same npm scripts as all my more recent projects.</p><h3>Dependencies</h3><p>Most of the magic of <em>Create React App</em> is done by installing <a href="https://github.com/facebookincubator/create-react-app/tree/master/packages/react-scripts"><strong>react-scripts</strong></a> and adding it to package.json.</p><p>So I started by installing it to my old project:</p><p><strong>npm install — save-dev react-scripts</strong></p><h3>NPM scripts</h3><p>Next part was to peek into one of my <em>Create React App</em> projects and see what it had added to the <strong>scripts</strong> section in package.json:</p><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    &quot;build&quot;: &quot;react-scripts build&quot;,<br>    &quot;test&quot;: &quot;react-scripts test --env=jsdom&quot;,<br>    &quot;eject&quot;: &quot;react-scripts eject&quot;</pre><h3>Conventions</h3><p>The last part that makes <em>Create React App</em> work is of course that every <em>Create React App</em> is set up the same.</p><h3>A public folder</h3><p>There needs to be a <em>public</em> folder with an <strong>index.html</strong> that looks like this:</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;link rel=&quot;shortcut icon&quot; href=&quot;%PUBLIC_URL%/favicon.ico&quot;&gt;<br>    &lt;!--<br>      Notice the use of %PUBLIC_URL% in the tag above.<br>      It will be replaced with the URL of the `public` folder during the build.<br>      Only files inside the `public` folder can be referenced from the HTML.</pre><pre>      Unlike &quot;/favicon.ico&quot; or &quot;favicon.ico&quot;, &quot;%PUBLIC_URL%/favicon.ico&quot; will<br>      work correctly both with client-side routing and a non-root public URL.<br>      Learn how to configure a non-root public URL by running `npm run build`.<br>    --&gt;<br>    &lt;title&gt;React App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;!--<br>      This HTML file is a template.<br>      If you open it directly in the browser, you will see an empty page.</pre><pre>      You can add webfonts, meta tags, or analytics to this file.<br>      The build step will place the bundled scripts into the &lt;body&gt; tag.</pre><pre>      To begin the development, run `npm start`.<br>      To create a production bundle, use `npm run build`.<br>    --&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>There should also be a <strong>favicon.ico</strong>, but that doesn’t seem super important…</p><h3>root element</h3><p>As you can see in the above html it adds an element with id <strong>root</strong>, my previous app had an element with id <strong>app</strong>.</p><p>I could change the id in the html but I changed <strong>document.querySelector(‘#app’)</strong> to <strong>#root</strong> in my <strong>index.js</strong> where I mount the app, since the point was to have it conform to the <em>Create React App</em> standards.</p><pre>ReactDOM.render(&lt;App /&gt;, document.querySelector(&#39;#root&#39;));</pre><p>That’s it! Running <strong>npm start</strong> and <strong>npm build</strong> now runs the <strong>react-scripts</strong> and can build and serve the project perfectly. 🙌</p><p>This project didn’t have any tests, if you have run of the mill jest tests and your test files are suffixed with <strong>.test.js </strong>or <strong>.spec.js</strong> it should work out of the box though.</p><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2016/12/04/adding-create-react-app-scripts-to-an-existing-project/"><em>fredrik.anderzon.se</em></a><em> on December 4, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207cfe3cd190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a REST API on AWS Lambda using Lambdasync]]></title>
            <link>https://medium.com/@fredrikanderzon/create-a-rest-api-on-aws-lambda-using-lambdasync-e46c68f8043f?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e46c68f8043f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Fri, 02 Dec 2016 08:51:51 GMT</pubDate>
            <atom:updated>2016-12-02T08:51:51.640Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Lambda is a pretty great place to put your APIs, you don’t need to configure any servers, you pay only for what you use, and it automatically scales as your audience does.</p><p>It can be a little tricky to get started though, this guide will talk you through building a basic API on Lambda.</p><h3>AWS prerequisites</h3><p>To follow this tutorial you must have an account at <a href="https://aws.amazon.com/">Amazon Web Services</a>, and you must have a set of security credentials ready.</p><p>You can get your AWS access key and secret key by following these instructions: <a href="http://goo.gl/aMbXsg">http://goo.gl/aMbXsg</a></p><h3>Setting up the project</h3><p>To set up the project that will be deployed on <a href="https://aws.amazon.com/lambda/details/">AWS Lambda</a> we’ll use <a href="https://github.com/fanderzon/lambdasync">Lambdasync</a> which is my pet project to make deploying APIs to Lambda a lot easier.</p><p>”<strong><em>npm install -g lambdasync</em></strong>”</p><p>Once that finishes we’ll let lambdasync create a new project:</p><p>”<strong><em>lambdasync new notetaker</em></strong>”</p><p>Just follow the guide and supply it your AWS credentials. Lambdasync creates a new folder and scaffolds everything we need to deploy what is basically a ”<strong><em>hello world</em></strong>” example to Lambda.</p><p>I’m imagining this API will be for a note taker app so I’m naming the project notetaker, but since it will Create, Read, Update and Delete objects by id it could store pretty much anything.</p><p>If you go into your new project folder and check out the ”<strong><em>index.js</em></strong>” file you can see it looks like this:</p><pre>exports.handler = (event, context, callback) =&gt; {<br>  callback(null, {<br>    statusCode: 200,<br>    message: &quot;Everything is awesome&quot;<br>  });<br>};</pre><p>This is your <a href="http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html">Lambda handler function</a> that will be executed whenever someone calls your API.</p><p>”<strong><em>event</em></strong>” will contain any interesting information about the request, this is where we will find request parameters, http method used etc.</p><p>”<strong><em>context</em></strong>” contains some uninteresting meta info about your Lambda environment. In earlier versions the context object was also used to return a response.</p><p>”<strong><em>callback</em></strong>” this parameter is a function you can call to send a response, the first parameter is reserved for errors, and the second for a success response.</p><p>Deploy this function by running ”<strong><em>lambdasync</em></strong>” in the root of your project folder. Once it is done you will have the URL to your API copied to your clipboard. Paste it into the browser and you should see the result of our callback function.</p><p>Before we build on the handler function to do something useful we need to create a place to store our API data.</p><h3>Setting up a database</h3><p>For this API we’ll use a MongoDB database hosted on <a href="http://mlab.com/">mLab</a>. mLab is awesome for this kind of prototyping. In very few steps we get a working database for free.</p><p>Go to <a href="http://mlab.com/">mLab</a> and sign up.</p><p>Once you are logged in you will be greeted by a control panel like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F07Aj1lvziCjijvdJvdJ7Q.png" /></figure><p>Click the ”<strong><em>Create new</em></strong>” button to the far right of <em>MongoDB Deployments</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6acVOBETAE45DjBjXKQ2Q.png" /></figure><p>On the next page make sure you click the ”<strong><em>Single-node</em></strong>” tab under <em>Plan</em> to reveal the free ”<strong><em>Sandbox</em></strong>” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1krt7q81gbWquZiVNweQCQ.png" /></figure><p>Finally just give your database any name you like and click ”<strong><em>Create new MongoDB deployment</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmRg2UlDhL3aC1edgr0RKA.png" /></figure><p>To connect to our database from Node.js we’ll use a ”<strong><em>mongodb://</em></strong>” URL, you can see that mLab gives us this URL on the database page: ”<strong><em>mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@dsxxxxxx.mlab.com:49207/notetaker</em></strong>” for my database.</p><p>The one thing missing there is a user and password for our database, so let’s create a user by clicking the ”<strong><em>Add database user</em></strong>” to the far right of <em>Database Users</em>. Enter whatever username and password you want, make note of them, and copy the ”<strong><em>mongodb://</em></strong>” URL for your database. We’ll use them next.</p><h3>The event object</h3><p>As mentioned earlier the event object passed to your handler contains most useful information you could want from an incoming request. The whole thing looks like this:</p><pre>{<br>    bodyJson: {},<br>    params: {<br>        path: {<br>            proxy: &#39;api&#39;<br>        },<br>        querystring: {},<br>        header: {<br>            Accept: &#39;text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8&#39;,<br>            &#39;Accept-Encoding&#39;: &#39;gzip, deflate, sdch, br&#39;,<br>            &#39;Accept-Language&#39;: &#39;en-US,en;q=0.8,sv;q=0.6&#39;,<br>            &#39;CloudFront-Forwarded-Proto&#39;: &#39;https&#39;,<br>            &#39;CloudFront-Is-Desktop-Viewer&#39;: &#39;true&#39;,<br>            &#39;CloudFront-Is-Mobile-Viewer&#39;: &#39;false&#39;,<br>            &#39;CloudFront-Is-SmartTV-Viewer&#39;: &#39;false&#39;,<br>            &#39;CloudFront-Is-Tablet-Viewer&#39;: &#39;false&#39;,<br>            &#39;CloudFront-Viewer-Country&#39;: &#39;SE&#39;,<br>            Host: &#39;xxxxxxxx.execute-api.eu-west-1.amazonaws.com&#39;,<br>            &#39;Upgrade-Insecure-Requests&#39;: &#39;1&#39;,<br>            &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36&#39;,<br>            Via: &#39;1.1 fe843ed327cefb9c06d08a7369d7ed2c.cloudfront.net (CloudFront)&#39;,<br>            &#39;X-Amz-Cf-Id&#39;: &#39;Foaw6k9sVC1U_wqIHQuC-8GARduC1V6Uy6u-4g8eJ83Xi8StJh25LQ==&#39;,<br>            &#39;X-Forwarded-For&#39;: &#39;x.x.x.x&#39;,<br>            &#39;X-Forwarded-Port&#39;: &#39;443&#39;,<br>            &#39;X-Forwarded-Proto&#39;: &#39;https&#39;<br>        }<br>    },<br>    stageVariables: {},<br>    context: {<br>        accountId: &#39;&#39;,<br>        apiId: &#39;xxxxxxxxxx&#39;,<br>        apiKey: &#39;&#39;,<br>        authorizerPrincipalId: &#39;&#39;,<br>        caller: &#39;&#39;,<br>        cognitoAuthenticationProvider: &#39;&#39;,<br>        cognitoAuthenticationType: &#39;&#39;,<br>        cognitoIdentityId: &#39;&#39;,<br>        cognitoIdentityPoolId: &#39;&#39;,<br>        httpMethod: &#39;GET&#39;,<br>        stage: &#39;prod&#39;,<br>        sourceIp: &#39;x.x.x.x&#39;,<br>        user: &#39;&#39;,<br>        userAgent: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36&#39;,<br>        userArn: &#39;&#39;,<br>        requestId: &#39;6ad2e7a9-b349-11e6-b34b-2dd1df05a1b9&#39;,<br>        resourceId: &#39;tvopih&#39;,<br>        resourcePath: &#39;/{proxy+}&#39;<br>    }<br>}</pre><p>The interesting parts are basically:</p><ul><li>”<strong><em>bodyJson</em></strong>” will contain any params sent as json.</li><li>”<strong><em>params.header</em></strong>” contains request headers</li><li>”<strong><em>params.path.proxy</em></strong>” gives us the relative path of the request</li><li>”<strong><em>context.httpMethod</em></strong>” tells us the http method used</li></ul><h3>Environment variables</h3><p>The mongodb url we have, complete with username password, is a perfect use for an environment variable, since we don’t want to put sensitive information in our source code. Environment variables can be added in the AWS Lambda control panel, or by using the ”<strong><em>lambdasync secret</em></strong>” command like this:</p><p>”<strong><em>lambdasync secret MONGO_URL=mongodb://xxxxxx:yyyyyy@dszzzzzz.mlab.com:49207/notetaker</em></strong>”</p><blockquote><em>Note: Environment variable support is fairly new in AWS Lambda, previous versions of Lambdasync used API Gateway stage variables to store secrets</em></blockquote><p>Add your mongo url like that and let’s also install the ”<strong><em>mongodb</em></strong>” Node.js driver before we get to coding:</p><p>”<strong><em>npm install -SE mongodb</em></strong>”</p><h3>Connecting to our database</h3><pre>const MongoClient = require(&#39;mongodb&#39;).MongoClient;</pre><pre>exports.handler = function handler(event, context, callback) {<br>  const MONGO_URL = process.env.MONGO_URL || null;<br>  MongoClient.connect(MONGO_URL, function (err, db) {<br>    if (err) {<br>      return callback(null, err);<br>    }</pre><pre>    db.close();<br>    callback(null, &quot;Successful db connection&quot;)<br>  });<br>};</pre><p>Connecting to a mongo database using the standard driver is pretty straightforward, we get the MONGO_URL from ”<strong><em>process.env</em></strong>”, send it in to the ”<strong><em>connect</em></strong>” method, and supply a callback function that will give us a ”<strong><em>db</em></strong>” instance if it worked.</p><p>Closing the db connection with ”<strong><em>db.close()</em></strong>” when done is important, or the Lambda request will time out.</p><h3>Adding notes</h3><p>Alright, we’ve got us a database connection. Let’s start by adding notes, I want you to npm install one more module before we start:</p><p>”<strong><em>npm install -SE node-uuid</em></strong>”</p><p>node-uuid will help us generate a unique id for each note.</p><pre>const MongoClient = require(&#39;mongodb&#39;).MongoClient;<br>const uuid = require(&#39;node-uuid&#39;).v4;</pre><pre>const SUCCESS = &#39;success&#39;;</pre><pre>function addNote(db, note) {<br>  return new Promise((resolve, reject) =&gt; {<br>    db<br>      .collection(&#39;notes&#39;)<br>      .insertOne(<br>        Object.assign({}, note, {<br>          id: uuid(),<br>          pinned: false<br>        }),<br>        err =&gt; {<br>          if (err) {<br>            reject(err);<br>          }<br>          resolve(SUCCESS);<br>        }<br>      );<br>  });<br>}</pre><pre>function respondAndClose(db, callback, error, response) {<br>  db.close();<br>  callback(error, {<br>    result: response<br>  });<br>}</pre><pre>exports.handler = function handler(event, context, callback) {<br>  const MONGO_URL = process.env.MONGO_URL || null;<br>  MongoClient.connect(MONGO_URL, function (err, db) {<br>    if (err) {<br>      return callback(null, err);<br>    }</pre><pre>    switch (event.context.httpMethod) {<br>      case &#39;POST&#39;:<br>        addNote(db, event.bodyJson)<br>          .then(res =&gt; respondAndClose(db, callback, null, res))<br>          .catch(err =&gt; respondAndClose(db, callback, err, null));<br>        break;<br>      default:<br>        respondAndClose(db, callback, null, &#39;unhandled request&#39;);<br>    }<br>  });<br>};</pre><p>We add a function to add a note, it takes an incoming POST json object, adds a unique id and a ”<strong><em>pinned</em></strong>” boolean to it, since we want the ability to pin notes, and finally adds that to the mongodb ”<strong><em>notes</em></strong>” collection using the ”<strong><em>insertOne</em></strong>” method. addNote returns a promise so it will either resolve or reject.</p><p>We also add a convenience function ”<strong><em>respondAndClose</em></strong>” that will help us to remember to close the db connection and keep a consistent format on our API responses.</p><p>In our main handler we add a switch to check the http method being used to hit our API. Currently we check for POST and just return a result of ”<strong><em>unhandled request</em></strong>” for anything else.</p><p>Run ”<strong><em>lambdasync</em></strong>” again and once it’s updated your function you should be able to add a note, you can do this with curl (example below), Postman or any number of fun ways.</p><pre>curl --request POST \<br>  --url https://yourapihere.execute-api.eu-west-1.amazonaws.com/prod/api \<br>  --header &#39;cache-control: no-cache&#39; \<br>  --header &#39;content-type: application/json&#39; \<br>  --data &#39;{&quot;title&quot;: &quot;Hello Lambda&quot;,&quot;text&quot;: &quot;This text was added by a lambdasync API&quot;}&#39;</pre><p>This should give you a ”<strong><em>{“result”:”success”}</em></strong>” response. You can edit the title and text and add a few of these. Of course, it would be nice if you could actually retrieve your notes somehow…</p><h3>Fetching notes</h3><p>Let’s add a getNotes function. It will fetch all notes unless you pass in a filter object, like ”<strong><em>{pinned: true}</em></strong>” to get only pinned notes for example.</p><pre>function getNotes(db, filter) {<br>  filter = filter || {};<br>  return new Promise((resolve, reject) =&gt; {<br>    db.collection(&#39;notes&#39;).find(filter).toArray((err, data) =&gt; {<br>      if (err) {<br>        reject(err);<br>      }<br>      resolve(data);<br>    });<br>  });<br>}</pre><p>Next add another clause to the switch to match get requests, and return the result of getNotes.</p><pre>case &#39;GET&#39;:<br>        return getNotes(db)<br>          .then(res =&gt; respondAndClose(db, callback, null, res))<br>          .catch(err =&gt; respondAndClose(db, callback, err, null));</pre><p>Deploy again by running ”<strong><em>lambdasync</em></strong>” and you should now be able to go to your API url in the browser (or curl, Postman again) and get the JSON for your notes.</p><h3>Updating and deleting notes</h3><p>Our API can now <strong>Create</strong> and <strong>Read</strong> notes, but how about updating and deleting?</p><p>For both of these methods we want to be able to pick out the notes id from the URL that will look like this:</p><p>”<strong><em>/api/e2f9b2c4–54b1–496b-a988–7b7c1967813c</em></strong>”</p><p>For updating there will also be a new note object to replace the old note with. For delete the http verb DELETE and the url is enough.</p><p>Let’s start with the functions again:</p><pre>const idRegex = /^api\/(.*?)(\/|$)/;<br>function getIdFromPath(path) {<br>  const match = idRegex.exec(path);<br>  return match &amp;&amp; match[1];<br>}</pre><pre>function updateNote(db, noteId, note) {<br>  if (!note || !noteId) {<br>    return Promise.reject();<br>  }<br>  return new Promise((resolve, reject) =&gt; {<br>    db<br>      .collection(&#39;notes&#39;)<br>      .updateOne({id: noteId}, Object.assign({}, note), err =&gt; {<br>        if (err) {<br>          return reject(err);<br>        }<br>        return resolve(JSON.stringify(SUCCESS));<br>      });<br>  });<br>}</pre><pre>function deleteNote(db, id) {<br>  if (!id) {<br>    return Promise.reject();<br>  }<br>  return new Promise((resolve, reject) =&gt; {<br>    db<br>      .collection(&#39;notes&#39;)<br>      .deleteOne({id}, err =&gt; {<br>        if (err) {<br>          return reject(err);<br>        }<br>        return resolve(JSON.stringify(SUCCESS));<br>      });<br>  });<br>}</pre><p>We will get the current path from ”<strong><em>event.params.path.proxy</em></strong>” and use some regex in the ”<strong><em>getIdFromPath</em></strong>” function to pick out the id portion of the path.</p><p>Inside your handler get the noteId from the path:</p><pre>exports.handler = function handler(event, context, callback) {<br>  const MONGO_URL = process.env.MONGO_URL || null;<br>  const noteId = getIdFromPath(event.params.path.proxy);<br>  ...</pre><p>Finally, add this to the switch:</p><pre>case &#39;PUT&#39;:<br>        if (!noteId) {<br>          return respondAndClose(db, callback, &#39;Missing id parameter&#39;, null);<br>        }<br>        updateNote(db, noteId, event.bodyJson)<br>          .then(res =&gt; respondAndClose(db, callback, null, res))<br>          .catch(err =&gt; respondAndClose(db, callback, err, null));<br>        break;<br>      case &#39;DELETE&#39;:<br>        if (!noteId) {<br>          return respondAndClose(db, callback, &#39;Missing id parameter&#39;, null);<br>        }<br>        deleteNote(db, noteId)<br>          .then(res =&gt; respondAndClose(db, callback, null, res))<br>          .catch(err =&gt; respondAndClose(db, callback, err, null));<br>        break;</pre><p>Deploy this and you are done! You can now create, read, update and delete notes with your AWS Lambda API! 🙌</p><p>The full example code can be found here: <a href="https://github.com/fanderzon/lambdasync-example/blob/master/index.js">https://github.com/fanderzon/lambdasync-example/blob/master/index.js</a>.</p><p>Some curl to try out your API:</p><pre>// POST<br>curl --request POST \<br>  --url https://yourapihere.execute-api.eu-west-1.amazonaws.com/prod/api \<br>  --header &#39;cache-control: no-cache&#39; \<br>  --header &#39;content-type: application/json&#39; \<br>  --data &#39;{&quot;title&quot;: &quot;Hello Lambda&quot;,&quot;text&quot;: &quot;This text was added by a lambdasync API&quot;}&#39;</pre><pre>// GET<br>curl --request GET \<br>  --url https://yourapihere.execute-api.eu-west-1.amazonaws.com/prod/api \<br>  --header &#39;cache-control: no-cache&#39;</pre><pre>// DELETE (replace 9fdcf243-d212-446f-9654-a97e241c66c1 with one of your note ids)<br>curl --request DELETE \<br>  --url https://yourapihere.execute-api.eu-west-1.amazonaws.com/prod/api/9fdcf243-d212-446f-9654-a97e241c66c1 \<br>  --header &#39;cache-control: no-cache&#39;</pre><pre>// UPDATE (replace 9fdcf243-d212-446f-9654-a97e241c66c1 with one of your note ids)<br>curl --request PUT \<br>  --url https://yourapihere.execute-api.eu-west-1.amazonaws.com/prod/api/9fdcf243-d212-446f-9654-a97e241c66c1 \<br>  --header &#39;cache-control: no-cache&#39; \<br>  --header &#39;content-type: application/json&#39; \<br>  --data &#39;{&quot;id&quot;:&quot;9fdcf243-d212-446f-9654-a97e241c66c1&quot;,&quot;title&quot;:&quot;New title&quot;,&quot;text&quot;:&quot;New text too&quot;,&quot;pinned&quot;: true}&#39;</pre><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2016/11/26/create-a-rest-api-on-aws-lambda-using-lambdasync/"><em>fredrik.anderzon.se</em></a><em> on November 26, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e46c68f8043f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust for Node.js developers — Part 3 — Crates, Modules and the web]]></title>
            <link>https://medium.com/@fredrikanderzon/rust-for-node-js-developers-part-3-crates-modules-and-the-web-a7652b611b63?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7652b611b63</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Tue, 12 Jul 2016 19:50:13 GMT</pubDate>
            <atom:updated>2016-07-14T18:44:03.790Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of a series. Links to all parts below.</p><ul><li><a href="http://fredrik.anderzon.se/2016/05/10/rust-for-node-developers-part-1-introduction/">Part 1 — Introduction to Rust</a></li><li><a href="http://fredrik.anderzon.se/2016/06/17/rust-for-node-js-developers-part-2-can-i-borrow-that/">Part 2 — Can I borrow that?</a></li><li>Part 3 — Crates, Modules and the web</li></ul><h3>Rust on the web</h3><p>So far in this series we have learned the basic data types available in Rust and how to use them, we have learned about ownership and borrowing. We have built 2 iterations of a todo-list, but we have done all of this without leaving the command line.</p><p>If your main language is Javascript your main platform is pretty likely to be the web, and you may have impatiently been asking yourself how to write Rust for the web when reading the previous parts. That is a great question, and something the Rust community spends quite a lot of time thinking about. So much so, that there is an excellent web site dedicated to it <a href="http://www.arewewebyet.org/">Are we web yet?</a>.</p><p>The idea of being able to compile Rust for any popular platform, including front-end web, mobile app environments, embedded systems is strong in the community, and improving the cross compile story is actively being worked on. To quote this excellent and very exciting recent post on the <a href="http://blog.rust-lang.org/2016/05/13/rustup.html">official rust-lang blog</a>:</p><blockquote><em>Rust has already been ported to Emscripten (at least twice), but the code has not yet fully landed. This summer it’s happening though: Rust + Emscripten. Rust on the Web. Rust everywhere.</em></blockquote><p>As excited as I am about that, let’s stick to a server rendered Rust app in this post. :)</p><h3>Adding dependencies</h3><p>It’s soon time to add our first dependencies in this series, but first use the hopefully familiar <strong>cargo new</strong> command to scaffold a new project for us:</p><pre>cargo new hello-server --bin</pre><p>The dependency we will install is called <a href="https://github.com/nickel-org/nickel.rs">nickel</a> and is in it’s own words:</p><blockquote><em>An expressjs inspired web framework for Rust</em></blockquote><p>There is no Cargo command to install local dependencies for a project. The <strong>cargo install</strong> command will only install global binaries. But there is an external crate, <strong>cargo-add</strong> that lets us add dependencies from the command line.</p><p>So to add nickel, we’ll first install cargo-add and then use it to install nickel.</p><pre>cargo install cargo-add<br>cargo add nickel --version 0.8.1</pre><blockquote><em>0.8.1 is the version we’ll use in this post, if you want to look up the latest version you can run </em><strong><em>cargo search nickel</em></strong><em>.</em></blockquote><p>If we check our <strong>Cargo.toml</strong> file we should now see this (you could of course also just add it manually):</p><pre>...<br>[dependencies]<br>nickel = &quot;0.8.1&quot;</pre><p>This is very similar to the dependencies you would have in a <strong>package.json</strong> file, where you might have something like:</p><pre>...<br>&quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;4.14.0&quot;,<br>    ...</pre><p><strong>*</strong> just like for npm dependencies is a wildcard meaning any version (the latest).</p><p>The rules about specifying versions are mostly the same as in package.json, with a few exceptions. In npm land a full semver version <strong>1.2.3</strong> means that exact version and only that exact version. Cargo will instead read it as <strong>^1.2.3</strong> (any “compatible” version &lt; 2.0.0). Wildcards <strong>*</strong>, carets <strong>^</strong>, and tildes <strong>~</strong>work the same as in npm.</p><p>If you need a recap of how they work here’s a quick demonstration from the <a href="http://doc.crates.io/specifying-dependencies.html">Cargo docs</a> of how versions are interpreted:</p><pre>^1.2.3 := &gt;=1.2.3 &lt;2.0.0<br>^1.2 := &gt;=1.2.0 &lt;2.0.0<br>^1 := &gt;=1.0.0 &lt;2.0.0<br>^0.2.3 := &gt;=0.2.3 &lt;0.3.0<br>^0.0.3 := &gt;=0.0.3 &lt;0.0.4<br>^0.0 := &gt;=0.0.0 &lt;0.1.0<br>^0 := &gt;=0.0.0 &lt;1.0.0<br>~1.2.3 := &gt;=1.2.3 &lt;1.3.0<br>~1.2 := &gt;=1.2.0 &lt;1.3.0<br>~1 := &gt;=1.0.0 &lt;2.0.0</pre><p>If you did mean to add an exact version you would use <strong>= 1.2.3</strong>. This is usually not necessary though since Cargo automatically generates a <strong>Cargo.lock</strong> for us, that locks down all the version of your dependencies (and their dependencies) to the versions that just got installed for you, these dependencies will not update automatically, you have to run <strong>cargo update</strong> to do that.</p><p>The same goes for anyone who clones your project (including Cargo.lock file), Cargo will build everything with the exact same versions you used.</p><p>If you are familiar with npm’s shrinkwrap this is very similar behavior. :)</p><p>We are going to need two more dependencies before we are done, so we might as well add them now:</p><pre>cargo add handlebars --version 0.18.1<br>cargo add rustc-serialize --version 0.3.19</pre><p>OK! Time to write our first Rust server example!</p><h3>Nickel “Hello world!”</h3><p>So… we have a Rust library that is trying to be close to express, how does that look?</p><p>Let’s add a Hello world example to the <strong>src/main.rs</strong> file that cargo created for us.</p><pre>extern crate nickel;<br>use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};</pre><pre>fn hello_world&lt;&#39;mw&gt;(_req: &amp;mut Request, res: Response&lt;&#39;mw&gt;) -&gt; MiddlewareResult&lt;&#39;mw&gt; {<br>    res.send(&quot;Hello World!&quot;)<br>}</pre><pre>fn main() {<br>    let mut app = Nickel::new();<br>    app.get(&quot;/&quot;, hello_world);<br>    app.listen(&quot;0.0.0.0:3000&quot;);<br>}</pre><p>Now if you run this with:</p><pre>cargo run</pre><p>Cargo will download and install your dependencies, build and then run your project. When it is done you should be able to open <a href="http://localhost:3000/">http://localhost:3000</a> in your browser and see a nice <strong>Hello world!</strong> message.</p><h3>Comparing Nickel and Express</h3><p>Let’s write the same code in Node/Express and look at the differences:</p><pre>const express = require(&#39;express&#39;);</pre><pre>function helloWorld(req, res) {<br>  res.send(&#39;Hello World!&#39;);<br>}</pre><pre>const app = express();<br>app.get(&#39;/&#39;, helloWorld);<br>app.listen(3000, &#39;0.0.0.0&#39;);</pre><p>There are 2 key differences, let’s start with the non scary one. Where in Node you just use express as:</p><pre>const express = require(&#39;express&#39;);</pre><p>In Rust we have 2 steps:</p><pre>extern crate nickel;<br>use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};</pre><p>First we declare that we have an installed external crate to look in, and then we state what parts of that we are going to use in this file.</p><p>This <strong>use</strong> syntax is close to es6 <strong>import</strong> syntax. If we imagined that nickel was an npm module, the es6 way to write the above Rust code would be:</p><pre>import {Nickel, HttpRouter, Request, Response, MiddlewareResult} from &#39;nickel&#39;;</pre><p>The next difference is the hello world function:</p><pre>function helloWorld(req, res) {<br>  res.send(&#39;Hello World!&#39;);<br>}</pre><p>vs.</p><pre>fn hello_world&lt;&#39;mw&gt;(_req: &amp;mut Request, res: Response&lt;&#39;mw&gt;) -&gt; MiddlewareResult&lt;&#39;mw&gt; {<br>    res.send(&quot;Hello World!&quot;)<br>}</pre><p>Both are functions that take a request and response “object” (in Rust these are structs), and sends a hello world response, but the Rust function probably looks slightly complex.</p><p>That Rust functions must declare the type of what goes into and out of a function we have already covered. But what are all these <strong>&lt;’mw&gt;</strong> about? These are explicit lifetimes, we will cover them in more detail in a future post, but what this code is basiclly saying is that the hello_world function has a lifetime (that is named mw). That the incoming <strong>res: Response&lt;’mw&gt;</strong> and the result <strong>MiddlewareResult&lt;’mw&gt;</strong> must both live longer than the lifetime of the function.</p><p>If that makes sense to you, great! If not, don’t worry too much about it. We are going to replace this hello_world function with a <strong>macro</strong> that the Nickel crate provides for us. This way of returning a result is so common that there is a shorthand for it.</p><pre>#[macro_use] extern crate nickel;<br>use nickel::{Nickel, HttpRouter};</pre><pre>fn main() {<br>    let mut app = Nickel::new();<br>    app.get(&quot;/&quot;, middleware!(&quot;Hello World!&quot;));<br>    app.listen(&quot;0.0.0.0:3000&quot;);<br>}</pre><p>We will be using this <strong>middleware!</strong> macro from now on, I just wanted you to see that what is actually passed to our nickel app is a function very much like on we would write for an express app, just think of the macro as a shorthand that will write that rather verbose function code for us.</p><p><strong>#[macro_use]</strong> is necessary to tell the compiler we want to use macros from an external crate.</p><h3>Modularizing our app</h3><p>As shocking as this may be to you, the web app we are going to build is a todo app! 😲</p><p>We will reuse almost all of the code from the previous example, <a href="https://github.com/fanderzon/rust-for-nodejs-devs/blob/master/part2-borrowing/redux-light/src/main.rs">part 2 code here</a>, splitting the logic up in modules. If you want to join in on the migration fun you should copy that code to your <strong>src/main.rs</strong>.</p><p>I won’t shoot for some grand complicated app structure for this tiny app, but instead simply break out <strong>todo</strong> and <strong>store</strong> modules from main, so that main just uses the data types and structures we have.</p><p>Start by creating a new file <strong>src/todo.rs</strong> and we’ll start cutting the todo specific code out of main.</p><pre>// Lines 30-48<br>#[derive(Clone, Debug)]<br>struct Todo {<br>    id: i16,<br>    title: String,<br>    completed: bool,<br>    deleted: bool,<br>}</pre><pre>// Create a convenient Todo::new(id, title) method<br>impl Todo {<br>    pub fn new(id: i16, title: String) -&gt; Todo {<br>        Todo {<br>            id: id,<br>            title: title,<br>            completed: false,<br>            deleted: false,<br>        }<br>    }<br>}</pre><pre>// Line 60-67<br>// mark_done from the previous example becomes Toggle to align with the Redux example<br>// otherwise functionality is the same<br>#[derive(Clone, Debug)]<br>enum TodoAction {<br>    Add(String),<br>    Toggle(i16),<br>    Remove(i16),<br>}</pre><pre>// Line 77-80<br>// Helper function for getting a mutable todo from a vector by todo_id<br>fn get_mut_todo(todos: &amp;mut Vec&lt;Todo&gt;, todo_id: i16) -&gt; Option&lt;&amp;mut Todo&gt; {<br>    todos.iter_mut().find(|todo|todo.id == todo_id)<br>}</pre><pre>// Line 93-123<br>// Our todo reducer, takes in state (todo list) and returns a new/cloned version<br>// after applying the action (is applicable)<br>fn todo_reducer(state: &amp;Vec&lt;Todo&gt;, action: &amp;Action) -&gt; Vec&lt;Todo&gt; {<br>    let mut new_state: Vec&lt;Todo&gt; = state.clone();</pre><pre>    // First we make sure it&#39;s a `Todos` action, otherwise return clone of incoming state<br>    match *action {<br>        Todos(ref todo_action) =&gt; match *todo_action {<br>            // Pretty simple from here on, check the type of Todos enum type<br>            // If Add push a new item, and if `Toggle` or `Remove` use our get_mut_todo<br>            // helper function and then change a property on the todo<br>            Add(ref title) =&gt; {<br>                let new_id = new_state.len() as i16 + 1;<br>                new_state.push(Todo::new(new_id, title.to_string()))<br>            },<br>            Toggle(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    if todo.completed { todo.completed = false; } else { todo.completed = true; }<br>                }<br>            },<br>            Remove(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    todo.deleted = true;<br>                }<br>            },<br>        },<br>        // If it&#39;s not a Todos action change nothing<br>        _ =&gt; (),<br>    }<br>    return new_state;<br>}</pre><p>Ok, that should make our main.rs file a little lighter, but if you try to <strong>cargo run</strong> the project now it will of course fail miserably.</p><p>Before we fix the problems, let’s create an <strong>src/store.rs</strong> file. With the todo-code cut out we should now have a block of code that looks like this in main, ready to cut out.</p><pre>// Ripping off the canonical Redux todo example we&#39;ll add a<br>// visibility filter to our state except for the todos we already had<br>#[derive(Clone, Debug)]<br>struct State {<br>    todos: Vec&lt;Todo&gt;,<br>    visibility_filter: VisibilityFilter<br>}</pre><pre>// By implementing a struct we are creating something very much like<br>// a class, we can attach methods to it refering to &amp;self` or `&amp;mut self`<br>impl State {<br>    // This gives us a quick way to initialize a default state with State::default()<br>    pub fn default() -&gt; State {<br>        State {<br>            todos: Vec::new(),<br>            visibility_filter: VisibilityFilter::ShowAll,<br>        }<br>    }<br>}</pre><pre>// Rust has enums, so the enum type can replace the &quot;type&quot; property of Redux objects<br>// The enums will replace `action creators` too since Todos(Add(&quot;Todo item&quot;.to_string()))<br>// is pretty clear<br>#[derive(Clone, Debug)]<br>enum Action {<br>    Todos(TodoAction),<br>    Visibility(VisibilityFilter),<br>}</pre><pre>// Our 3 visibility states<br>#[derive(Clone, Debug)]<br>enum VisibilityFilter {<br>    ShowActive,<br>    ShowAll,<br>    ShowCompleted,<br>}</pre><pre>// Our main reducer, returns a new State with the results of the child-reducers<br>// No combineReducers is implemented here, so it calls the child reducers<br>// by function name<br>fn reducer(state: &amp;State, action: Action) -&gt; State {<br>    // Always return a new state<br>    State {<br>        todos: todo_reducer(&amp;state.todos, &amp;action),<br>        visibility_filter: visibility_reducer(&amp;state.visibility_filter, &amp;action),<br>    }<br>}</pre><pre>// Very simple reducer since the action will either be a VisibilityFilter, in which<br>// case we will return that, otherwise just return the incoming state<br>fn visibility_reducer(state: &amp;VisibilityFilter, action: &amp;Action) -&gt; VisibilityFilter {<br>    match *action {<br>        Visibility(ref vis_action) =&gt; vis_action.clone(),<br>        _ =&gt; state.clone(),<br>    }<br>}</pre><pre>// Redux store implementation<br>struct Store {<br>    state: State,<br>    listeners: Vec&lt;fn(&amp;State)&gt;,<br>    reducer: fn(&amp;State, Action) -&gt; State,<br>}</pre><pre>impl Store {<br>    // Takes a reducer function, we skip the initial_state and optional arguments<br>    // TO keep it simple, State::default() from earlier is our initial_state implementation<br>    fn create_store(reducer: fn(&amp;State, Action) -&gt; State) -&gt; Store {<br>        Store {<br>            state: State::default(),<br>            listeners: Vec::new(),<br>            reducer: reducer,<br>        }<br>    }</pre><pre>    // Pushes a listener that will be called for any state change<br>    fn subscribe(&amp;mut self, listener: fn(&amp;State)) {<br>        self.listeners.push(listener);<br>    }</pre><pre>    // Simply returns the state<br>    #[allow(dead_code)]<br>    fn get_state(&amp;self) -&gt; &amp;State {<br>        &amp;self.state<br>    }</pre><pre>    // Called for every new action, calls the reducer to update the state<br>    // and then calls every listener<br>    fn dispatch(&amp;mut self, action: Action) {<br>        self.state = (self.reducer)(&amp;self.state, action);<br>        for listener in &amp;self.listeners {<br>            listener(&amp;self.state)<br>        }<br>    }<br>}</pre><p>With that code moved to store, we should now have a main with only some “print to terminal” helper functions and the input command parsing and action dispatching. Let’s make this code work again.</p><h3>Rust modules 101</h3><p>Rust modules can be declared inline like this:</p><pre>mod hello {<br>    pub fn world() {<br>        println!(&quot;Hello world&quot;);<br>    }<br>}</pre><pre>fn main() {<br>    hello::world(); // prints &quot;Hello world&quot;<br>}</pre><p>This is usually not very practical, since you want to split up your project in files and folder for organizational purposes.</p><p>This is a more common use case:</p><p><strong>src/hello.rs</strong></p><pre>pub fn world() {<br>    println!(&quot;Hello world!&quot;);<br>}</pre><p><strong>src/main.rs</strong></p><pre>mod hello;<br>use hello::world; // Let&#39;s you use hello::world() as just world()<br>use hello::{world}; // Another use syntax for multiple (comma separated) items<br>use hello::*; // Wildcards works for using everything directly under hello</pre><pre>fn main() {<br>    world(); // prints &quot;Hello world!&quot;<br>}</pre><p>An important thing to note is the keyword <strong>pub</strong> in <strong>pub fn world()</strong>. By default everything in a Rust module is private, and usable only within the module, anything you want to expose to the ourside world needs a pub in front of it. In structs individual fields are private by default too, even if the struct is public, so each field needs to be specifically declared <strong>pub</strong> to be public.</p><p>Next up is file structure, when we declare the module <strong>hello</strong> here, Rust will follow a very simple convention for finding the file to import by looking for either <strong>hello.rs</strong> or <strong>hello/mod.rs</strong> starting from the current directory.</p><p>It’s a very light-weight and no nonsense system that I really like, I can decide on a case by case basis if I want to add a folder for a module or just a single file and it’s a very easy convention to remember.</p><p>I usually only put modules in folders when I want them to have submodules:</p><p><strong>src/main.rs</strong></p><pre>mod hello;<br>use hello::earth::earth; // imports the earth function from the hello submodule earth</pre><pre>fn main() {<br>    earth();<br>}</pre><p><strong>src/hello/mod.rs</strong></p><pre>pub mod earth;</pre><pre>pub fn world() {<br>    println!(&quot;Hello world!&quot;);<br>}</pre><p><strong>src/hello/earth.rs</strong></p><pre>use hello::world;</pre><pre>pub fn earth() {<br>    world();<br>    println!(&quot;More specifically, Earth.&quot;);<br>}</pre><p>So main declares the module hello, which in turn declares a submodule earth, that can quite easily use items from it’s parent hello module. And the output of this is:</p><pre>Hello world<br>More specifically, Earth.</pre><p>Ok, those were some pretty silly module examples. Let’s apply this knowledge to the mess we just made out of our todo list project.</p><p>##</p><p>First let’s add our modules to main, and then change the use statements that used to refer to local items to now include the respective modules at the start:</p><p><strong>src/main.rs</strong></p><pre>mod todo;<br>mod store;</pre><pre>// Lets us type `Add(&quot;Todo item&quot;.to_string())` instead of `TodoAction::Add(&quot;Todo item&quot;.to_string())`<br>use todo::TodoAction::{ Add, Remove, Toggle };<br>// Same with the Action enum and VisibilityFilter, Action::*; would work too, but this way we list what we use<br>use store::Action::{ Todos, Visibility };<br>use store::VisibilityFilter:: { ShowActive, ShowAll, ShowCompleted };<br>use todo::{Todo};<br>use store::{Store, State, reducer};</pre><p>Next up let’s make stuff public in our todo, and make sure to add use statements for the things we need there:</p><p><strong>src/todo.rs</strong></p><pre>use store::{ Action };<br>use store::Action::{ Todos };<br>use todo::TodoAction::{ Add, Toggle, Remove };<br>#[derive(Clone, Debug)]<br>pub struct Todo {<br>    pub id: i16,<br>    pub title: String,<br>    pub completed: bool,<br>    pub deleted: bool,<br>}<br>impl Todo {<br>    pub fn new(id: i16, title: String) -&gt; Todo {<br>        Todo {<br>            id: id,<br>            title: title,<br>            completed: false,<br>            deleted: false,<br>        }<br>    }<br>}</pre><pre>// mark_done from the previous example becomes Toggle to align with the Redux example<br>// otherwise functionality is the same<br>#[derive(Clone, Debug)]<br>pub enum TodoAction {<br>    Add(String),<br>    Toggle(i16),<br>    Remove(i16),<br>}</pre><pre>// Helper function for getting a mutable todo from a vector by todo_id<br>pub fn get_mut_todo(todos: &amp;mut Vec&lt;Todo&gt;, todo_id: i16) -&gt; Option&lt;&amp;mut Todo&gt; {<br>    todos.iter_mut().find(|todo|todo.id == todo_id)<br>}</pre><pre>// Our todo reducer, takes in state (todo list) and returns a new/cloned version<br>// after applying the action (is applicable)<br>pub fn todo_reducer(state: &amp;Vec&lt;Todo&gt;, action: &amp;Action) -&gt; Vec&lt;Todo&gt; {<br>    let mut new_state: Vec&lt;Todo&gt; = state.clone();</pre><pre>    // First we make sure it&#39;s a `Todos` action, otherwise return clone of incoming state<br>    match *action {<br>        Todos(ref todo_action) =&gt; match *todo_action {<br>            // Pretty simple from here on, check the type of Todos enum type<br>            // If Add push a new item, and if `Toggle` or `Remove` use our get_mut_todo<br>            // helper function and then change a property on the todo<br>            Add(ref title) =&gt; {<br>                let new_id = new_state.len() as i16 + 1;<br>                new_state.push(Todo::new(new_id, title.to_string()))<br>            },<br>            Toggle(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    if todo.completed { todo.completed = false; } else { todo.completed = true; }<br>                }<br>            },<br>            Remove(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    todo.deleted = true;<br>                }<br>            },<br>        },<br>        // If it&#39;s not a Todos action change nothing<br>        _ =&gt; (),<br>    }<br>    return new_state;<br>}</pre><p>And do the same to store</p><p><strong>src/store.rs</strong></p><pre>use store::Action::{ Visibility };<br>use todo::{ Todo, TodoAction, todo_reducer };</pre><pre>// Ripping off the canonical Redux todo example we&#39;ll add a<br>// visibility filter to our state except for the todos we already had<br>#[derive(Clone, Debug)]<br>pub struct State {<br>    pub todos: Vec&lt;Todo&gt;,<br>    pub visibility_filter: VisibilityFilter<br>}</pre><pre>// By implementing a struct we are creating something very much like<br>// a class, we can attach methods to it refering to &amp;self` or `&amp;mut self`<br>impl State {<br>    // This gives us a quick way to initialize a default state with State::default()<br>    pub fn default() -&gt; State {<br>        State {<br>            todos: Vec::new(),<br>            visibility_filter: VisibilityFilter::ShowAll,<br>        }<br>    }<br>}</pre><pre>// Rust has enums, so the enum type can replace the &quot;type&quot; property of Redux objects<br>// The enums will replace `action creators` too since Todos(Add(&quot;Todo item&quot;.to_string()))<br>// is pretty clear<br>#[derive(Clone, Debug)]<br>pub enum Action {<br>    Todos(TodoAction),<br>    Visibility(VisibilityFilter),<br>}</pre><pre>// Our 3 visibility states<br>#[derive(Clone, Debug)]<br>pub enum VisibilityFilter {<br>    ShowActive,<br>    ShowAll,<br>    ShowCompleted,<br>}</pre><pre>// Our main reducer, returns a new State with the results of the child-reducers<br>// No combineReducers is implemented here, so it calls the child reducers<br>// by function name<br>pub fn reducer(state: &amp;State, action: Action) -&gt; State {<br>    // Always return a new state<br>    State {<br>        todos: todo_reducer(&amp;state.todos, &amp;action),<br>        visibility_filter: visibility_reducer(&amp;state.visibility_filter, &amp;action),<br>    }<br>}</pre><pre>// Very simple reducer since the action will either be a VisibilityFilter, in which<br>// case we will return that, otherwise just return the incoming state<br>fn visibility_reducer(state: &amp;VisibilityFilter, action: &amp;Action) -&gt; VisibilityFilter {<br>    match *action {<br>        Visibility(ref vis_action) =&gt; vis_action.clone(),<br>        _ =&gt; state.clone(),<br>    }<br>}</pre><pre>// Redux store implementation<br>pub struct Store {<br>    state: State,<br>    listeners: Vec&lt;fn(&amp;State)&gt;,<br>    reducer: fn(&amp;State, Action) -&gt; State,<br>}</pre><pre>impl Store {<br>    // Takes a reducer function, we skip the initial_state and optional arguments<br>    // TO keep it simple, State::default() from earlier is our initial_state implementation<br>    pub fn create_store(reducer: fn(&amp;State, Action) -&gt; State) -&gt; Store {<br>        Store {<br>            state: State::default(),<br>            listeners: Vec::new(),<br>            reducer: reducer,<br>        }<br>    }</pre><pre>    // Pushes a listener that will be called for any state change<br>    pub fn subscribe(&amp;mut self, listener: fn(&amp;State)) {<br>        self.listeners.push(listener);<br>    }</pre><pre>    // Simply returns the state<br>    #[allow(dead_code)]<br>    pub fn get_state(&amp;self) -&gt; &amp;State {<br>        &amp;self.state<br>    }</pre><pre>    // Called for every new action, calls the reducer to update the state<br>    // and then calls every listener<br>    pub fn dispatch(&amp;mut self, action: Action) {<br>        self.state = (self.reducer)(&amp;self.state, action);<br>        for listener in &amp;self.listeners {<br>            listener(&amp;self.state)<br>        }<br>    }<br>}</pre><p>And with this the terminal todo app should compile and work with a simple <strong>cargo run</strong>.</p><p>As you can see it was mostly a fairly painless process of adding <strong>pub</strong> in front of the things that other parts of your program was using. And if you didn’t follow my instructions the compiler would be complaining about trying to use undeclared things until you had fixed them all yourself.</p><p>One common pitfall if you are coming from node is that you try to declare modules with <strong>mod</strong> whereever you want to use them. One important difference in Rust is that the <strong>todo</strong> module here isn’t actually declared in <strong>todo.rs</strong>, it’s declared in <strong>main.rs</strong> when it uses <strong>mod todo;</strong>, and a module can only be declared once.</p><p>Once the <strong>todo</strong> module is declared in main it is accessible to the whole program with a simple <strong>use todo;</strong>.</p><h3>Building a server rendered todo list</h3><p>Now that the stuff we want to keep is safely encapsulated in their own modules, and we have tested that it all still works, we can delete most of <strong>main.rs</strong>, leaving only this:</p><pre>use std::io;<br>mod todo;<br>mod store;</pre><pre>// Lets us type `Add(&quot;Todo item&quot;.to_string())` instead of `TodoAction::Add(&quot;Todo item&quot;.to_string())`<br>use todo::TodoAction::{ Add, Remove, Toggle };<br>// Same with the Action enum and VisibilityFilter, Action::*; would work too, but this way we list what we use<br>use store::Action::{ Todos, Visibility };<br>use store::VisibilityFilter:: { ShowActive, ShowAll, ShowCompleted };<br>use todo::{Todo};<br>use store::{Store, State, reducer};</pre><pre>fn main() {<br>    // Let&#39;s create our store and subscribe with print_todos so every update is printed<br>    let mut store = Store::create_store(reducer);<br></pre><pre>}</pre><p>This code should compile, but doesn’t do much. If we want our todo list on the web we should be rendering HTML, and the plan is to use <em>handlebars</em> as our templating language. We have already imported <strong>handlebars</strong> as a dependency, and <a href="https://github.com/sunng87/handlebars-rust">handlebars-rust</a> is a fairly complete handlebars implementation.</p><p>We want the end result to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSyAT3leZRKgADFzN1Of-w.png" /></figure><p>Fortunately, this is the standard <a href="http://todomvc.com/">TodoMVC</a> look, both the CSS and the HTML structure to use is predefined, so we can focus on rendering the data from our <em>Store</em>.</p><p>With that said let’s create a new file <strong>src/todos.tpl</strong>:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;title&gt;Nickel Todo&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;http://todomvc.com/examples/react/node_modules/todomvc-common/base.css&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;http://todomvc.com/examples/react/node_modules/todomvc-app-css/index.css&quot;&gt;<br>    &lt;style type=&quot;text/css&quot;&gt;<br>    label a {<br>      color: #4d4d4d;<br>      text-decoration: none;<br>    }<br>    &lt;/style&gt;<br>    &lt;script&gt;<br>      document.addEventListener(&#39;click&#39;, function clickHandler(e) {<br>        if (e.target &amp;&amp; e.target.dataset &amp;&amp; e.target.dataset.id) {<br>          window.location.href = &#39;/&#39; + e.target.dataset.action + &#39;/&#39; + e.target.dataset.id;<br>        }<br>      });<br>    &lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;section class=&quot;todoapp&quot;&gt;<br>      &lt;header class=&quot;header&quot;&gt;<br>        &lt;h1&gt;todos&lt;/h1&gt;<br>        &lt;form class=&quot;add-todo&quot; action=&quot;/&quot; method=&quot;post&quot;&gt;<br>          &lt;input class=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; name=&quot;todo&quot;&gt;<br>        &lt;/form&gt;<br>      &lt;/header&gt;<br>      &lt;section class=&quot;main&quot;&gt;<br>        &lt;ul class=&quot;todo-list&quot;&gt;<br>          {{#each todos}}<br>          {{#unless deleted}}<br>          &lt;li{{#if completed}} class=&quot;completed&quot;{{/if}} data-id={{id}}&gt;<br>            &lt;div class=&quot;view&quot;&gt;<br>              &lt;input class=&quot;toggle&quot; type=&quot;checkbox&quot;{{#if completed}} checked=&quot;checked&quot;{{/if}} data-id={{id}} data-action=&quot;toggle&quot;&gt;<br>              &lt;label&gt;&lt;a href=&quot;/toggle/{{id}}&quot;&gt;{{title}}&lt;/a&gt;&lt;/label&gt;<br>              &lt;button class=&quot;destroy&quot; data-id={{id}} data-action=&quot;remove&quot;&gt;&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/li&gt;<br>          {{/unless}}<br>          {{/each}}<br>        &lt;/ul&gt;<br>      &lt;/section&gt;</pre><pre>      &lt;footer class=&quot;footer&quot;&gt;<br>        &lt;span class=&quot;todo-count&quot;&gt;<br>          &lt;strong&gt;0 items left&lt;/strong&gt;<br>        &lt;/span&gt;<br>        &lt;ul class=&quot;filters&quot;&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/show/all&quot;&gt;All&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;span&gt; &lt;/span&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/show/active&quot;&gt;Active&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;span&gt; &lt;/span&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/show/completed&quot;&gt;Completed&lt;/a&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/footer&gt;<br>    &lt;/section&gt;</pre><pre>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Handlebars is a very common templating language, it lets us do nice things like <strong>{{#each todos}}</strong> to iterate through each todo in our app state, and within the each block we can access fields from the currently iterated todo as <strong>{{id}}</strong> and <strong>{{title}}</strong>.</p><p>We can also do things like <strong>{{#if completed}}</strong> or <strong>{{#unless deleted}}</strong> to conditionally print render of html.</p><p>This HTML isn’t all that interesting in itself, but it paints a picture of how the app will work. New todos will be posted through a normal html form as POST. The rest of our actions, toggling or removing todos, and changing the visibility filter will be done through normal GET links.</p><p>Most are normal anchor tag links, but where there is a checkbox or X button to remove a todo I cheat a bit and let javascript change the url.</p><h3>Rendering handlebar templates</h3><p>With the template-file in place let’s create a function to render handlebar templates for us. Because there will be more template related helper functions we will create a new module for this:</p><p><strong>src/template.rs</strong></p><pre>use rustc_serialize::json::ToJson;<br>use nickel::{Response, MiddlewareResult};<br>use std::path::Path;<br>use handlebars::{Handlebars, Renderable, RenderError, RenderContext, Helper, Context, JsonRender};</pre><pre>pub fn render&lt;&#39;mw, T:ToJson&gt;(res: Response&lt;&#39;mw&gt;, path: &amp;str, data: &amp;T) -&gt; MiddlewareResult&lt;&#39;mw&gt; {<br>    let mut handlebars = Handlebars::new();</pre><pre>    handlebars.register_template_file(&quot;template&quot;, &amp;Path::new(path)).ok().unwrap();<br>    let result = handlebars.render(&quot;template&quot;, data).ok().unwrap();</pre><pre>    res.send(result)<br>}</pre><p>Our render function will take the nickel Response object as the first argument, the path to a template file as the second argument, and a borrowed reference to the data to render as it’s third argument.</p><p>Handlebars <strong>register_template_file</strong> first lets us name the template we are registering, I named it “template” because I’m very imaginative… The second thing it wants is the path to the template file, it wants it as a <strong>Path</strong> from the Rust standard library, easy!</p><p>Next we render the template and pass it onto Nickel’s <strong>res.send()</strong> so that it’s rendered for the user. This <strong>.ok().unwrap();</strong> is fairly common (especially in example code ;) ). Because handlebars.render returns a Rust <strong>Result</strong>, .ok() grabs the value of the Result as an Option, and then we call .unwrap() on the option to get it’s value. It makes for quick and easy code, but doesn’t really handle any errors that may occur.</p><p>You may notice something that looks a little odd in the function declaration, there’s a T:ToJson in the <strong>pub fn render&lt;’mw, T:ToJson&gt;</strong>, and our data argument has no type declared other than T, <strong>data: &amp;T</strong>. This is Rust’s syntax for <a href="https://doc.rust-lang.org/book/generics.html"><em>generics</em></a>, which you may never have encountered if you’ve worked exclusively with loosely typed languages.</p><p>Since data here can be anything, an array, a vector, a single string, etc. and Rust needs everything to be typed, we can assign it a generic type. Naming it T for Type is a convention in Rust, I could name it something more descriptive as TemplateData if I wanted to. The compiler will ensure that T is consistently the same type whereever T is being used.</p><p>Generics and Traits work very well together, by declaring the type T as <strong>T:ToJson</strong> we are saying that T can be anything, as long as it’s something that implements the ToJson trait. This is a requirement from <em>handlebars-rust</em> to be able to work with the data.</p><p>Handlebars, coming from javascript, is very loose and easy with types and assumes types compatible with the (very few) data types available in javascript. Rust is strict about types and has a very rich type system, so to get around a lot of the problems that would cause, <em>handlebars-rust</em> works by converting the data passed to it to json, or rather <a href="https://doc.rust-lang.org/rustc-serialize/rustc_serialize/json/enum.Json.html"><em>Json</em> coming from the rust-serialize crate</a>.</p><p>This is a pretty clever way to do it, since the json functionality from rust-serialize takes care of all the heavy lifting in turning Rust data into javascript compatible data.</p><p>It does create a little extra work for us though, since it means that our <strong>State</strong> struct now has to implement the <strong>ToJson</strong> trait. There are 3 things we need to do to make this work:</p><ol><li>Add <strong>use rustc_serialize::json::{self, Json, ToJson};</strong> to the top of <strong>src/store.rs</strong>.</li><li>Add the implementation of ToJson for <strong>State</strong>, add this under the struct definition.</li></ol><ul><li>impl ToJson for State { fn to_json(&amp;self) -&gt; Json { Json::from_str( &amp;json::encode(&amp;self).unwrap() ).unwrap() } }</li></ul><ol><li>Let’s find the definition of <strong>State</strong> and <strong>VisibilityFilter</strong> in <strong>src/store.rs</strong> and <strong>Todo</strong> in <strong>src/todo.rs</strong> and add 2 new derivable traits to them, <strong>RustcEncodable</strong> and <strong>RustcDecodable</strong> so we get <strong>#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]</strong>.</li></ol><p>Alright, we should now be able to use our template module to render our todo list:</p><p><strong>src/main.rs</strong></p><pre>#[macro_use] extern crate nickel;<br>extern crate rustc_serialize;<br>extern crate handlebars;</pre><pre>use nickel::{Nickel, HttpRouter};<br>use std::io;<br>mod todo;<br>mod store;<br>mod template;</pre><pre>// Lets us type `Add(&quot;Todo item&quot;.to_string())` instead of `TodoAction::Add(&quot;Todo item&quot;.to_string())`<br>use todo::TodoAction::{ Add, Remove, Toggle };<br>// Same with the Action enum and VisibilityFilter, Action::*; would work too, but this way we list what we use<br>use store::Action::{ Todos, Visibility };<br>use store::VisibilityFilter:: { ShowActive, ShowAll, ShowCompleted };<br>use todo::{Todo};<br>use store::{Store, State, reducer};<br>use template::render;</pre><pre>fn main() {<br>    // Let&#39;s create our store and subscribe with print_todos so every update is printed<br>    let mut store = Store::create_store(reducer);</pre><pre>    // Add some todos so we&#39;ve got something to render<br>    store.dispatch( Todos( Add(&quot;one thing&quot;.to_string()) ) );<br>    store.dispatch( Todos( Add(&quot;another thing&quot;.to_string()) ) );</pre><pre>    let mut server = Nickel::new();<br>    server.get(&quot;/&quot;, middleware! { |_req, res|<br>        return render(res, &quot;./src/todos.tpl&quot;, store.get_state())<br>    });<br>    server.listen(&quot;0.0.0.0:3000&quot;);<br>}</pre><p>You should now be able to <strong>cargo run</strong> this and open <a href="http://localhost:3000/">http://localhost:3000</a> in your browser.</p><p>We can now render a todo list, but not change or add anything. Let’s fix that:</p><h3>toggling and removing todos</h3><p>Add a new server.get block under the one we’ve already got. The logic should be partly familiar. Like with the terminal commands we still have to convert text into actions and params for our code.</p><p>We can access the <strong>:id</strong> part from the url through <strong>_req.param(“id”).unwrap()</strong>, and next we convert it to an integer.</p><p>Next we use the parsed <strong>num</strong> either as a toggle or remove action (or a noop if :action is anything else).</p><p>And finally we render the updated list with our custom render function.</p><pre>server.get(&quot;/:action/:id&quot;, middleware! { |_req, res|<br>        // We try to parse the id param to an int, this works for the<br>        // toggle and remove actions<br>        if let Ok(num) = _req.param(&quot;id&quot;).unwrap().parse::&lt;i16&gt;() {<br>            match _req.param(&quot;action&quot;).unwrap() {<br>                &quot;toggle&quot; =&gt; {<br>                    store.dispatch( Todos( Toggle(num) ) )<br>                },</pre><pre>                &quot;remove&quot; =&gt; store.dispatch( Todos( Remove(num) ) ),<br>                _ =&gt; (),<br>            }<br>        }</pre><pre>        // And render the now updated todo list<br>        return render(res, &quot;./src/todos.tpl&quot;, store.get_state())<br>    });</pre><p>No we should be able to toggle and remove todos… but no, this doesn’t compile!</p><pre>error: capture of moved value: `store`<br>`store` moved into closure environment here because it has type `store::Store`, which is non-copyable</pre><p>So, Nickel actually runs the code from our middleware! macros in threads, and Rust being a safe language very nicely moves ownership of store to the first thread that uses it so there can be no unsafe access.</p><p>To safely share data between threads Rust offers a number of wrappers. One is <strong>Arc</strong>, atomic reference counting. Calling .clone() on an Arc container gives you an immutable reference to the data inside, and Arc keeps track of how many references are in use at any time.</p><p>To get a mutable reference, which we will need to dispatch actions that modify our state, we first wrap our state in a <strong>Mutex</strong> wrapper. You call .lock() instead of clone on a Mutex, which tries to lock access to the data in the wrapper, and return an Option that will contain the data if the lock was successful, and a None if it failed (because there was already a lock in place).</p><p>We will do the least amount of work possible here to make this work, not worrying about handling errors. Let’s change our main function so it compiles:</p><pre>use std::sync::{Arc, Mutex};</pre><pre>fn main() {<br>    let mut server = Nickel::new();</pre><pre>    // Create our todo list store<br>    let mut store = Store::create_store(reducer);</pre><pre>    // Add some todos so we&#39;ve got something to render<br>    store.dispatch( Todos( Add(&quot;one thing&quot;.to_string()) ) );<br>    store.dispatch( Todos( Add(&quot;another thing&quot;.to_string()) ) );</pre><pre>    // Put the store in a container that will let us<br>    // safely use it in multi-threaded environment<br>    let store_container = Arc::new( Mutex::new(store) );</pre><pre>    // Every clone() of our container is counted<br>    // so that when the last clone goes out of scope<br>    // the container can be deallocated<br>    let store = store_container.clone();</pre><pre>    // At the / path let&#39;s just render our current todo list<br>    server.get(&quot;/&quot;, middleware! { |_req, res|<br>        // We get our store from the container by locking it<br>        // from other threads.<br>        let store = store.lock().unwrap();</pre><pre>        // Render from nickel_mustache takes the<br>        // nickel Result struct, a path to a mustache<br>        // template, and the data to use<br>        return render(res, &quot;./src/todos.tpl&quot;, store.get_state())<br>        // And here the lock is released..<br>    });</pre><pre>    // Let&#39;s clone it again for the next closure<br>    let store = store_container.clone();</pre><pre>    // This time we look for requests like /toggle/1<br>    server.get(&quot;/:action/:id&quot;, middleware! { |_req, res|<br>        // We will dispatch an action on our store so we<br>        // get a mutable reference<br>        let mut store = store.lock().unwrap();</pre><pre>        // We try to parse the id param to an int, this works for the<br>        // toggle and remove actions<br>        if let Ok(num) = _req.param(&quot;id&quot;).unwrap().parse::&lt;i16&gt;() {<br>            match _req.param(&quot;action&quot;).unwrap() {<br>                &quot;toggle&quot; =&gt; {<br>                    store.dispatch( Todos( Toggle(num) ) )<br>                },</pre><pre>                &quot;remove&quot; =&gt; store.dispatch( Todos( Remove(num) ) ),<br>                _ =&gt; (),<br>            }<br>        }<br>        // And render the now updated todo list<br>        return render(res, &quot;./src/todos.tpl&quot;, store.get_state())<br>    });</pre><pre>    server.listen(&quot;0.0.0.0:3000&quot;);<br>}</pre><p>Toggling and removing todos work, yay!</p><h3>adding todos</h3><p>New todos are being posted by a form tag in the handlebars <strong>&lt;form class=”add-todo” action=”/” method=”post”&gt;</strong>. So we need to listen for post request and the name property of the input tag <strong>todo</strong> gives us the parameter name to look for.</p><pre>// Let&#39;s clone it again for the next closure<br>    let store = store_container.clone();</pre><pre>    server.post(&quot;/*&quot;, middleware! { |req, res|<br>        let mut store = store.lock().unwrap();<br>        let form_body = req.form_body().ok().unwrap();<br>        if let Some(new_todo) = form_body.get(&quot;todo&quot;) {<br>            if new_todo.len() &gt; 0 {<br>                store.dispatch( Todos( Add(new_todo.to_string()) ) );<br>            }<br>        }</pre><pre>        return render(res, &quot;./src/todos.tpl&quot;, store.get_state())<br>    });</pre><p><strong>server.post(“/*”</strong> matches any post request. We get post parameters by getting the FormBody of the request, to be able to work with FormBody, we need to use this trait, so add it to our nickel use declaration:</p><pre>use nickel::{Nickel, HttpRouter, FormBody};</pre><p>Getting the text for the todo is as easy as calling .get(“todo”).We also check the length to be sure we don’t add empty todos.</p><p>We can now add, toggle and remove todos. There are a few things missing though:</p><ol><li>We can not change the visibility filter.</li><li>We do not filter the visible todos in any way (other than not showing removed todos).</li><li>We have no logic to show which visibility filter is active.</li><li>The count of todos left is hard coded to 0.</li></ol><p>The first point is easy, just more of what we have been doing. Add an else clause to the if in the <strong>server.get(“/:action/:id”</strong> block:</p><pre>if let Ok(num) = _req.param(&quot;id&quot;).unwrap().parse::&lt;i16&gt;() {<br>            match _req.param(&quot;action&quot;).unwrap() {<br>                &quot;toggle&quot; =&gt; {<br>                    store.dispatch( Todos( Toggle(num) ) )<br>                },</pre><pre>                &quot;remove&quot; =&gt; store.dispatch( Todos( Remove(num) ) ),<br>                _ =&gt; (),<br>            }<br>        } else {<br>        // Otherwise look for a show action<br>            match _req.param(&quot;action&quot;).unwrap() {<br>                &quot;show&quot; =&gt; {<br>                    match _req.param(&quot;id&quot;).unwrap() {<br>                        &quot;all&quot; =&gt; store.dispatch( Visibility( ShowAll ) ),<br>                        &quot;active&quot; =&gt; store.dispatch( Visibility( ShowActive ) ),<br>                        &quot;completed&quot; =&gt; store.dispatch( Visibility( ShowCompleted ) ),<br>                        _ =&gt; (),<br>                    }<br>                },<br>                _ =&gt; (),<br>            }<br>        }</pre><p>Now you can click the visibility filter links at the bottom of the list, and it’s set to our state, but we don’t actually do anything with it.</p><h3>custom helpers</h3><p>Handlebars doesn’t let us do something like <strong>{{#if visibility_filter == “active” &amp;&amp; !completed}}</strong>, but what handlebars do have are custom helpers. So we are going to define a <strong>{{#filter_todo}}</strong> helper, that wraps the todo output and only shows the todo if it matches the current filter.</p><p>Here’s how we define one:</p><p><strong>src/template.rs</strong></p><pre>fn filter_todo(c: &amp;Context, h: &amp;Helper, ha: &amp;Handlebars, rc: &amp;mut RenderContext) -&gt; Result&lt;(), RenderError&gt; {<br>    let active_filter = c.navigate(&quot;.&quot;, &quot;visibility_filter&quot;).as_string().unwrap();<br>    let is_completed = c.navigate( rc.get_path(), &quot;completed&quot;).as_boolean().unwrap();<br>    let show_todo: bool = match active_filter {<br>        &quot;ShowAll&quot; =&gt; true,<br>        &quot;ShowCompleted&quot; =&gt; is_completed,<br>        &quot;ShowActive&quot; =&gt; !is_completed,<br>        _ =&gt; false,<br>    };</pre><pre>    if show_todo {<br>        h.template().unwrap().render(c, ha, rc)<br>    } else {<br>        Ok(())<br>    }<br>}</pre><p>And add this inside our render function, before rendering:</p><pre>handlebars.register_helper(&quot;filter_todo&quot;, Box::new(filter_todo));</pre><p>And in your template file add {{#filter_todo}} and {{/filter_todo}} inside your each block:</p><p><strong>src/todos.tpl</strong></p><pre>...<br>      &lt;section class=&quot;main&quot;&gt;<br>        &lt;ul class=&quot;todo-list&quot;&gt;<br>          {{#each todos}}<br>          {{#unless deleted}}<br>          {{#filter_todo}}<br>          &lt;li{{#if completed}} class=&quot;completed&quot;{{/if}} data-id={{id}}&gt;<br>            &lt;div class=&quot;view&quot;&gt;<br>              &lt;input class=&quot;toggle&quot; type=&quot;checkbox&quot;{{#if completed}} checked=&quot;checked&quot;{{/if}} data-id={{id}} data-action=&quot;toggle&quot;&gt;<br>              &lt;label&gt;&lt;a href=&quot;/toggle/{{id}}&quot;&gt;{{title}}&lt;/a&gt;&lt;/label&gt;<br>              &lt;button class=&quot;destroy&quot; data-id={{id}} data-action=&quot;remove&quot;&gt;&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/li&gt;<br>          {{/filter_todo}}<br>          {{/unless}}<br>          {{/each}}<br>        &lt;/ul&gt;<br>      &lt;/section&gt;<br>...</pre><p>Now the filters should actually work!</p><p>So what did we do? Well our filter function gets the access to the Context <strong>c</strong> from handlebars, which has a very useful <strong>.navigate()</strong> method.</p><pre>let active_filter = c.navigate(&quot;.&quot;, &quot;visibility_filter&quot;).as_string().unwrap();</pre><p>We get the active filter by navigating from the root of our date, by passing “.” as the first arg, and the name of the field as the second. This returns a Json result, that in turn has an <strong>.as_string()</strong> method that returns an Option that we can unwrap.</p><p>We get the completed field from the currently iterated todo in almost the same way:</p><pre>let is_completed = c.navigate( rc.get_path(), &quot;completed&quot;).as_boolean().unwrap();</pre><p>Instead of “.” for root, <strong>rc.get_path()</strong> (rc is the RenderContext) instead gets the current position in the data tree, which is inside currently iterated todo items, so it will have a completed field we can retrieve as a boolean.</p><p>Now that we have the data we need it’s just a matter of a simple match statement to set show_todo to either true or false, and then based on that either render the block inside our helper, or do nothing (Return an Ok() result containing an empty tuple ()).</p><p>Worth noting is that the name we give it when registering the helper is the name we can use in our templates, the function name has nothing to do with it.</p><p>We’ll add 2 more helpers to show the active filter, and an accurate count of unfinished todos.</p><pre>fn is_selected_filter(c: &amp;Context, h: &amp;Helper, ha: &amp;Handlebars, rc: &amp;mut RenderContext) -&gt; Result&lt;(), RenderError&gt; {<br>    let param = h.param(0).unwrap().value().as_string().unwrap();<br>    let active_filter = c.navigate(&quot;.&quot;, &quot;visibility_filter&quot;).as_string().unwrap();<br>    let is_selected: bool = match active_filter {<br>        &quot;ShowAll&quot; =&gt; if param == &quot;ShowAll&quot; { true } else { false },<br>        &quot;ShowCompleted&quot; =&gt; if param == &quot;ShowCompleted&quot; { true } else { false },<br>        &quot;ShowActive&quot; =&gt; if param == &quot;ShowActive&quot; { true } else { false },<br>        _ =&gt; false,<br>    };<br>    if is_selected {<br>        h.template().unwrap().render(c, ha, rc)<br>    } else {<br>        Ok(())<br>    }<br>}</pre><pre>#[allow(unused_variables)]<br>fn active_count(c: &amp;Context, h: &amp;Helper, ha: &amp;Handlebars, rc: &amp;mut RenderContext) -&gt; Result&lt;(), RenderError&gt; {<br>    let todos = c.navigate(&quot;.&quot;, &quot;todos&quot;).as_array().unwrap();<br>    let count = todos<br>        .into_iter()<br>        .filter(|todo| {<br>            !todo.find(&quot;completed&quot;).unwrap().as_boolean().unwrap() &amp;&amp;<br>            !todo.find(&quot;deleted&quot;).unwrap().as_boolean().unwrap()<br>        })<br>        .count();</pre><pre>    let mut output = count.to_string();<br>    if count == 1 {<br>        output.push_str(&quot; item left&quot;);<br>    } else {<br>        output.push_str(&quot; items left&quot;);<br>    }</pre><pre>    rc.writer.write(output.as_bytes()).unwrap();<br>    Ok(())<br>}</pre><p>The <strong>is_selected_filter</strong> will be used like this, so we conditionally set a <em>selected</em> class on the right filter link:</p><pre>&lt;a href=&quot;/show/all&quot;{{#is_selected_filter &quot;ShowAll&quot;}} class=&quot;selected&quot;{{/is_selected_filter}}&gt;All&lt;/a&gt;</pre><p>The implementation is mostly a copy of <strong>filter_todo</strong>, with a key difference, it takes an argument, that we access in a slightly complex way.</p><pre>let param = h.param(0).unwrap().value().as_string().unwrap();</pre><p>Get the param with index 0, unwrap the Option returned, get the Json value from that, as a string, and unwrap that Option. 🙌</p><p>The <strong>active_count</strong> helper is a little more interesting, and will actually require us to add a new use statement:</p><pre>use std::io::Write;</pre><p>With this helper we don’t just conditionally show something, we create, or write content to the RenderContext. <strong>active_count</strong> will simply be used like this:</p><pre>{{#active_count}}{{/active_count}}</pre><p>And print out <strong>n item(s) left</strong>.</p><p>It works by getting the list of todos from our state, iterating it and filtering out the todos that are deleted or completed. And finally <strong>.count()</strong> will return the count of the items left.</p><pre>let count = todos<br>        .into_iter()<br>        .filter(|todo| {<br>            !todo.find(&quot;completed&quot;).unwrap().as_boolean().unwrap() &amp;&amp;<br>            !todo.find(&quot;deleted&quot;).unwrap().as_boolean().unwrap()<br>        })<br>        .count();</pre><p>Next we create the string to write:</p><pre>let mut output = count.to_string();<br>    if count == 1 {<br>        output.push_str(&quot; item left&quot;);<br>    } else {<br>        output.push_str(&quot; items left&quot;);<br>    }</pre><p>Strings are kind of nice like this, you can push characters or string slices to them. So to be grammatically correct if there is exactly 1 todo left we can use “item” instead of “items”.</p><p>All that’s left is to output our string and return.</p><pre>rc.writer.write(output.as_bytes()).unwrap();<br>    Ok(())</pre><p>We register these two new helpers in our render function:</p><pre>handlebars.register_helper(&quot;active_count&quot;, Box::new(active_count));<br>    handlebars.register_helper(&quot;is_selected_filter&quot;, Box::new(is_selected_filter));</pre><p>Add them to our template like so:</p><pre>&lt;footer class=&quot;footer&quot;&gt;<br>        &lt;span class=&quot;todo-count&quot;&gt;<br>          &lt;strong&gt;{{#active_count}}{{/active_count}}&lt;/strong&gt;<br>        &lt;/span&gt;<br>        &lt;ul class=&quot;filters&quot;&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/show/all&quot;{{#is_selected_filter &quot;ShowAll&quot;}} class=&quot;selected&quot;{{/is_selected_filter}}&gt;All&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;span&gt; &lt;/span&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/show/active&quot;{{#is_selected_filter &quot;ShowActive&quot;}} class=&quot;selected&quot;{{/is_selected_filter}}&gt;Active&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;span&gt; &lt;/span&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/show/completed&quot;{{#is_selected_filter &quot;ShowCompleted&quot;}} class=&quot;selected&quot;{{/is_selected_filter}}&gt;Completed&lt;/a&gt;<br>          &lt;/li&gt;</pre><pre>        &lt;/ul&gt;<br>      &lt;/footer&gt;</pre><p>And our app is complete! A fully server rendered app, with a round trip to the server for any change to the UI. <a href="https://github.com/fanderzon/rust-for-nodejs-devs/tree/master/part3-web/todo-web">The full code can be found here for a better overview</a>.</p><p>Next time we’ll look at creating a REST API in Rust, but for now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*CQL9_8qTRe6a-SNJ.jpg" /></figure><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2016/07/12/rust-for-node-js-developers-part-3-crates-modules-and-the-web-2/"><em>fredrik.anderzon.se</em></a><em> on July 12, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7652b611b63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust for Node.js developers — Part 2 — Can I borrow that?]]></title>
            <link>https://medium.com/@fredrikanderzon/this-post-is-part-of-a-series-links-to-all-parts-below-1386b095e49e?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1386b095e49e</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Fri, 17 Jun 2016 18:32:56 GMT</pubDate>
            <atom:updated>2016-06-18T21:58:12.919Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of a series. Links to all parts below.</p><ul><li><a href="http://fredrik.anderzon.se/2016/05/10/rust-for-node-developers-part-1-introduction/">Part 1 — Introduction to Rust</a></li><li>Part 2 — Can I borrow that?</li></ul><h3>Ownership</h3><p>Hopefully part 1 gave you a pretty good first impression of Rust, and enticed you to want to learn more. But to keep it reasonably short I had to gloss over some subjects, and skip mentioning some completely. If you try to experiment with the code from part 1 yourselves without reading up on Rust you are likely to run into this message ”<strong>error: use of moved value: x</strong>”.</p><p>This is one of the most foundational concepts in Rust, ”<strong>Ownership</strong>”, where at any point in your program any resource is owned by exactly one thing. And a resource can either be ”<strong>moved</strong>” (change owner), be ”<strong>borrowed</strong>” or be ”<strong>copied</strong>”.</p><p>Let’s have a look at <strong>how</strong> this all works with some code.</p><pre>// Let&#39;s reuse our Todo struct from last time<br>struct Todo {<br>    id: i16,<br>    title: String,<br>    completed: bool,<br>    deleted: bool,<br>}</pre><pre>// Simple function to print a todo, here Rust will default to moving ownership<br>// of the todo to the function<br>fn print_todo(todo: Todo) {<br>    println!(&quot;Todo item {}: {}&quot;, todo.id, todo.title);<br>}</pre><pre>fn main() {<br>    // Create a todo item<br>    let item0 = Todo {<br>        id: 0,<br>        title: &quot;Borrow something&quot;.to_string(),<br>        completed: false,<br>        deleted: false<br>    };<br>    // Print todo, and move ownership away from `item0`<br>    print_todo(item0);<br>    // Try to assign item0 to another variable (this will cause a `use of moved value` error)<br>    let borrow_something = item0;<br>}</pre><p>When a resource is ”<strong>moved</strong>” ownership is transfered, so in our example the ownership of the resource ”<strong>item0</strong>” represents is moved to the ”<strong>print_todo</strong>” function. And when we try to use ”<strong>item0</strong>” again is no longer linked to that resource.</p><p>So how do we fix it? This is where borrowing comes in:</p><pre>// Now the function takes the borrowed version `&amp;Todo`<br>fn print_todo(todo: &amp;Todo) {<br>    println!(&quot;Todo item {}: {}&quot;, todo.id, todo.title);<br>}</pre><pre>fn main() {<br>    // ...<br>    // Print todo, borrowing the item0 value<br>    print_todo(&amp;item0);<br>    // No error here<br>    let borrow_something = item0;<br>}</pre><p>That was easily solved by letting ”<strong>print_todo</strong>” borrow ”<strong>&amp;item0</strong>”. The ampersand signifies borrowing in Rust and makes sure we only get a reference to the value.</p><h3>Copyable types</h3><p>Borrowing is great, but there are times when we don’t need to borrow or move values, I’m talking about copyable types:</p><pre>fn main() {<br>    let maximum_todos = 10;<br>    let max = maximum_todos;<br>    // Integers are a `copyable` type, which means by default no ownership is involved<br>    // The value is simply copied<br>    println!(&quot;maximum_todos is still valid: {}&quot;, maximum_todos);<br>}</pre><p>So this code runs, because integers are <strong>copyable</strong>.</p><p>Primitive types in Rust will by default be copied when used in assignments or passed to functions. You see very similar behaviour in JavaScript where primitive types like ”<strong>number</strong>”, ”<strong>boolean</strong>” and ”<strong>string</strong>” are copied:</p><pre>var a = 7; <br>var b = a; <br>a = 9; <br>console.log(b);</pre><p>will print ”<strong>7</strong>” because <em>b</em> got<em>a copy of the value in </em>a<em> at the time it was copied and there is no further link to the </em>a* variable binding. If we look at ”<strong>object</strong>” or ”<strong>array</strong>” instead, we see a different behaviour:</p><pre>var a = { name: &#39;Fredrik&#39; };<br>var b = a;<br>a.name = &#39;Andersson&#39;;<br>console.log(b);</pre><p>will print ”<strong>Object {name: “Andersson”}</strong>” because b got a reference to the object in a instead of a copy of it, and changes to that object will affect both a and b.</p><p>Back to Rust.</p><p>Let’s look at the primitives that are copied by default so that we know when there is no need to borrow a reference, there will be a few types here that I did not cover in part 1.</p><pre>fn main() {<br>    // All numeric primitives, signed and unsigned are copyable<br>    let a: i64 = 10;<br>    let b = a;<br>    let c: f32 = 0.1;<br>    let d = c;<br>    println!(&quot;a and c are not moved: {} {}&quot;, a, c);</pre><pre>    // Bools too<br>    let e = true;<br>    let f = e;<br>    println!(&quot;Bools are copyable too: {}&quot;, e);</pre><pre>    // Char&#39;s and string slices are copyable too, BUT NOT Strings<br>    let g: char = &#39;g&#39;;<br>    let h = g;<br>    let i = &quot;string slices are copyable&quot;;<br>    let j = i;<br>    println!(&quot;chars are copyable: {} aaaand {}&quot;, g, i);</pre><pre>    // Arrays and array slices too<br>    let k = [1, 2, 3];<br>    let l = k;<br>    // Get a slice of the first entry in the k array<br>    let m = &amp;k[0..1];<br>    let n = m;<br>    println!(&quot;Arrays and array clices are copyable: {:?} {:?}&quot;, k, m);</pre><pre>    // Tuples too<br>    let o = (1, &quot;str&quot;);<br>    let p = o;<br>    println!(&quot;Tuples are copyable {:?}&quot;, o);</pre><pre>    // That was the types that are copyable by default<br>    // We can also implement Copy on our own types as long<br>    // as they hold copyable types themselves<br>    struct Point {<br>        x: i32,<br>        y: i32,<br>    }<br>    impl Copy for Point {}<br>    impl Clone for Point { fn clone(&amp;self) -&gt; Point { *self } }<br>    let q = Point { x: 1, y: 10 };<br>    let r = q;<br>    println!(&quot;We made a copyable struct! {}/{}&quot;, q.x, q.y);</pre><pre>    // Phew! that was some black magic. Copy and Clone are `traits` that are built into the language<br>    // Traits are basically interfaces that you can implement on your types<br>    // You can create them yourselves too, which we&#39;ll get to in a future post<br>    // There is an easier way to make a type copyable though:<br>    #[derive(Copy, Clone, Debug)]<br>    struct Point3D {<br>        x: i32,<br>        y: i32,<br>        z: i32,<br>    }<br>    let s = Point3D { x: 1, y: -20, z: 30 };<br>    let t = s;<br>    println!(&quot;Point3D is now copyable, and the Debug trait let&#39;s us print it easily {:?}&quot;, s);<br>}</pre><p>As I mentioned a few of these types may be new to you, first we have ”<strong>Char</strong>” which represents a single unicode scalar value.</p><p>The second new type is the ”<strong>Tuple</strong>” which is a very interesting collection type, you can stick an unlimited number of comma separated values into parens, and then access them by pattern matching, or by index. They are very handy when you want to return more than one thing from a function.</p><p>Also new is the ability to derive traits, like the Copy trait to make a ”<strong>struct</strong>” copyable. Traits in general are incredibly useful and an awesome language feature deserving of their own chapter.</p><p>This long list of primitive examples hopefully gets the point across that far from all types in Rust will be moved when you assign them to another variable, or pass them to a function.</p><h3>Borrowing</h3><p>Let’s look at a few more examples of borrowing:</p><pre>#[derive(Clone, Debug)]<br>struct Point {<br>    x: i32,<br>    y: i32,<br>}</pre><pre>fn main() {<br>    let a = Point {<br>        x: 0,<br>        y: 0,<br>    };</pre><pre>    // As discussed this would cause a `moved value` error<br>    //let b = a;<br>    //let c = a;</pre><pre>    // Borrowing is fine an unlimited amount of times though<br>    let b = &amp;a;<br>    let c = &amp;a;</pre><pre>    // But only for as long as the reference lives<br>    // Rust is block scoped, basically any time you see {} it&#39;s a block<br>    {<br>        let d = Point { x: 0, y: 0 };<br>        // This is totally fine<br>        let e = &amp;d;<br>        // But here, at the end of this block, d goes out of scope<br>    }<br>    // So this would fail<br>    //let f = &amp;d;</pre><pre>    // You can also borrow a value mutably, but then the borrower has <br>    // exclusive rights to mutate the value until it goes out of scope<br>    let mut f = Point { x: 0, y: 0 };<br>    let g = &amp;mut f;</pre><pre>    // This would fail<br>    //let h = &amp;mut f;</pre><pre>    // Even the owner can&#39;t mutate itself without causing an error<br>    //f.x = 1;</pre><pre>    // This means that mutable borrows are mostly practical when passing something to a function</pre><pre>    fn pointifier(point: &amp;mut Point, multiply_by: i32) {<br>        point.x *= multiply_by;<br>        point.y *= multiply_by;<br>    }</pre><pre>    let mut h = Point { x: 1, y: 2 };<br>    pointifier(&amp;mut h, 20);</pre><pre>    // once the pointifier function has finished the borrow ends and h is mutable again<br>    h.x -= 1;<br>    println!(&quot;Point {:?}&quot;, h);<br>}</pre><p>That’s the basics of it, you might be wondering <strong>why</strong> someone would impose these kinds of restrictions on a language right now…</p><p>This ownership concept is a big part of the secret sauce that lets Rust be both ridiculously fast <strong>and</strong> memory safe. To explain it we need to go into a topic most JavaScript programmers do not spend a great deal of time thinking about:</p><h3>Memory management</h3><p>To make any program work, memory must be allocated for it’s resources, and deallocated when a resource is no longer needed, when the latter doesn’t happen, we have a <em>memory leak</em>.</p><p>Over the years different strategies have evolved to handle this. JavaScript, along with Java, Ruby and many other popular languages, is ”<strong>garbage collected</strong>”. This means that there is a process that, at runtime, will keep track of what allocated memory you aren’t using anymore and will automatically deallocate it for you.</p><p>That sounds great, right? Well, yes. The garbage collectors in these languages are great, they have been optimized over many years, by really smart people with feedback from huge communities. But still, it’s a process that will periodically suspend execution of your program to clean up your mess best it can, impacting performance.</p><p>Coming from JavaScript, memory management is not something you are forced to worry about (though it is extremely easy to create memory leaks when writing JS). In something like C and C++ you are forced to not only think about it, but you spend a lot of time allocating and deallocating memory manually. Rust takes a middle ground here.</p><p>The ownership system makes Rust programs very easy to reason about for the compiler, resources in memory are simply deallocated when the one owner goes out of scope. Combined with a concept called ”<strong>lifetimes</strong>”, that we will cover later, developers get fine grained control of memory management without manually having to dealloce memory. The bigger benefit is that Rust’s compiler/borrow checker will at compile time make sure that your code is memory safe.</p><p>So by not having a garbage collector, but instead through some very well designed constraints allow the compiler to reason about your program to the extent that it can write better memory management code than you would (or at least I would), Rust can be safe and fast.</p><h3>The todo list</h3><p>So using what we now know about borrowing, can we improve upon the structure we created last time? I’m pretty sure we can. Our todo list is the application state, and one of the nicest way to handle state in Javascript is <a href="https://github.com/reactjs/redux">Redux</a>.</p><p>If you don’t know what redux is you can read some of their awesome documentation <a href="http://redux.js.org/docs/basics/index.html">here</a>, or just accept that what we are going to build is pretty close.</p><p>Let’s look at what we need to implement something like Redux:</p><h4>State</h4><pre>// Ripping off the canonical Redux todo example we&#39;ll add a<br>// visibility filter to our state in addition to the todos we already had<br>// This state struct will be the single source of state for our todo list program<br>#[derive(Clone, Debug)]<br>struct State {<br>    todos: Vec&lt;Todo&gt;,<br>    visibility_filter: VisibilityFilter<br>}</pre><pre>impl State {<br>    // Can be called with State::default()<br>    fn default() -&gt; State {<br>        State {<br>            todos: Vec::new(),<br>            visibility_filter: VisibilityFilter::ShowAll,<br>        }<br>    }<br>}</pre><p>So, there are a few things to cover in the above code:</p><p>We define a State struct that will hold our application state. The state is a list of Todo objects (structs), the same we have used before. And a new field to hold a ”<strong>VisibilityFilter</strong>”. This will be of the type ”<strong>enum</strong>”.</p><p>Enums are a special user defined type that can hold data that is one of a predefined number of alternatives. Our VisibilityFilter will look like this:</p><pre>enum VisibilityFilter {<br>    ShowActive,<br>    ShowAll,<br>    ShowCompleted,<br>}</pre><p>So the visibility_filter field in our state will always be one of those 3 options. And they will control what todo items we show in the list.</p><p>You can also see how easy it is to attach methods to a struct, we add a function named ”<strong>default</strong>” to the State, which will let us call State::default() to get a new state with an empty todo list and the visibility_filter set to ShowAll.</p><p>This is also the first time we define a function that <strong>returns</strong> something. In Rust the type a function returns needs to be defined, and it’s done by adding -&gt; and the type before the opening brackets of the function body: ”<strong>fn default() -&gt; State {</strong>”. So this function clearly returns a ”<strong>State</strong>”.</p><h4>Actions</h4><p>Redux has the concept of actions (action objects) which in JavaScript is just an object with a mandatory property ”<strong>type</strong>” so for example: ”<strong>{ type: “ADD_TODO”, title: “Buy milk” }</strong>”.</p><p>When actions are dispatched on a Redux store, it will run a function called a reducer, that takes the current state and the action object, and after modifying a copy of the state according to the action returns the new state.</p><p>A common pattern in Redux is to create functions that create these action objects. These functions are called ”<strong>action creators</strong>”.</p><pre>function addTodo(text) {<br>    return { id: generate_id(), text }<br>}</pre><p>Rust has enums, so the enum type can replace the “type” property of Redux objects. The enums will replace ”<strong>action creators</strong>” too since they can be used as constructors like this: ”<strong>Todos(Add(“Todo item”.to_string()))</strong>”.</p><p>The full code for actions will look like this, note that we are ”<strong>deriving</strong>” 2 traits on these: ”<strong>Clone</strong>” that will let us call ”<strong>.clone()</strong>” on these enums, and ”<strong>Debug</strong>” that will let us print out their values easily.</p><pre>#[derive(Clone, Debug)]<br>enum Action {<br>    Todos(TodoAction),<br>    Visibility(VisibilityFilter),<br>}</pre><pre>// mark_done from the previous example becomes Toggle to align with the Redux example<br>// otherwise functionality is the same<br>#[derive(Clone, Debug)]<br>enum TodoAction {<br>    Add(String),<br>    Toggle(i16),<br>    Remove(i16),<br>}</pre><pre>// Our 3 visibility states<br>#[derive(Clone, Debug)]<br>enum VisibilityFilter {<br>    ShowActive,<br>    ShowAll,<br>    ShowCompleted,<br>}</pre><h3>Reducers</h3><p>I mentioned that when an action is dispatched a function called a reducer is run. Ours will look like this:</p><pre>fn reducer(state: &amp;State, action: Action) -&gt; State {<br>    // Always return a new state<br>    State {<br>        todos: todo_reducer(&amp;state.todos, &amp;action),<br>        visibility_filter: visibility_reducer(&amp;state.visibility_filter, &amp;action),<br>    }<br>}</pre><p>Here we can see some borrowing in action. Our reducer borrows a reference to the current state, and returns a new state. It gets this state by delegating the work to 2 functions we haven’t defined yet.</p><p>”<strong>todo_reducer</strong>” will set the ”<strong>todos</strong>” field of the state, the ”<strong>reducer</strong>” passes on a borrowed reference to the current todos, and the action. If the action is related to todos the todo_reducer will returned a modified todo list, otherwise it will return a copy of the same state that it was passed.</p><p>”<strong>visibility_reducer</strong>” will set the ”<strong>visibility_filter</strong>” field in very much the same way.</p><p>This is a little dirty, the main reducer just has to <strong>know</strong> the names of the child reducers for this to work. Redux provides a ”<strong>combineReducers</strong>” function that would let us build the main reducer function, by passing in the child reducers. However, to recreate that in Rust would bring us into topics that we aren’t going to cover in this post.</p><p>With that said, let’s have a look at how our 2 child reducers are implemented:</p><pre>// Helper function for getting a mutable todo from a vector by todo_id<br>fn get_mut_todo(todos: &amp;mut Vec&lt;Todo&gt;, todo_id: i16) -&gt; Option&lt;&amp;mut Todo&gt; {<br>    todos.iter_mut().find(|todo|todo.id == todo_id)<br>}</pre><pre>// Our todo reducer, takes in state (todo list) and returns a new/cloned version<br>// after applying the action (is applicable)<br>fn todo_reducer(state: &amp;Vec&lt;Todo&gt;, action: &amp;Action) -&gt; Vec&lt;Todo&gt; {<br>    let mut new_state: Vec&lt;Todo&gt; = state.clone();</pre><pre>    // First we make sure it&#39;s a `Todos` action, otherwise return clone of incoming state<br>    match *action {<br>        Todos(ref todo_action) =&gt; match *todo_action {<br>            // Pretty simple from here on, check the type of Todos enum type<br>            // If Add push a new item, and if `Toggle` or `Remove` use our get_mut_todo<br>            // helper function and then change a property on the todo<br>            Add(ref title) =&gt; {<br>                let new_id = new_state.len() as i16 + 1;<br>                new_state.push(Todo::new(new_id, title.to_string()))<br>            },<br>            Toggle(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    if todo.completed { todo.completed = false; } else { todo.completed = true; }<br>                }<br>            },<br>            Remove(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    todo.deleted = true;<br>                }<br>            },<br>        },<br>        // If it&#39;s not a Todos action change nothing<br>        _ =&gt; (),<br>    }<br>    return new_state;<br>}</pre><pre>// Very simple reducer since the action will either be a VisibilityFilter, in which<br>// case we will return that, otherwise just return the incoming state<br>fn visibility_reducer(state: &amp;VisibilityFilter, action: &amp;Action) -&gt; VisibilityFilter {<br>    match *action {<br>        Visibility(ref vis_action) =&gt; vis_action.clone(),<br>        _ =&gt; state.clone(),<br>    }<br>}</pre><p>Hopefully that is pretty clear. In the ”<strong>todo_reducer</strong>” we first clone the state, and then make use of Rusts ”<strong>match</strong>” statement for identifying the action. We first check if it was a Todos action, and if so what kind. The code for adding, toggling or deleting todos is pretty straight forward, and close to what we had in the last example.</p><p>We mutate the state in this function, but we mutate a <strong>cloned</strong> state, so the state that is returned is always a new copy.</p><p>For the ”<strong>visibility_reducer</strong>” an action of the type ”<strong>VisibilityFilter</strong>” is also the value we want in our state, so it will return a clone of the action if it was a VisibilityFilter type, or a clone of the current state otherwise.</p><h3>Store</h3><p>The last big Redux concept missing is the ”<strong>store</strong>”, it’s the piece that ties everything together. It holds the state, and let’s us subscribe to state changes, and dispatch actions to update the state.</p><pre>struct Store {<br>    state: State,<br>    listeners: Vec&lt;fn(&amp;State)&gt;,<br>    reducer: fn(&amp;State, Action) -&gt; State,<br>}</pre><p>The ”<strong>state</strong>” field will hold the current state, the ”<strong>listeners</strong>” field will hold references to any functions that subscribed to our store, and the ”<strong>reducer</strong>” field will hold the reducer function that is passed in to create the store.</p><p>Let’s have a look at the methods of the Store:</p><pre>impl Store {<br>    // Takes a reducer function as the only argument<br>    // To keep it simple, State::default() provides the initial state in this eample<br>    fn create_store(reducer: fn(&amp;State, Action) -&gt; State) -&gt; Store {<br>        Store {<br>            state: State::default(),<br>            listeners: Vec::new(),<br>            reducer: reducer,<br>        }<br>    }</pre><pre>    // Pushes a listener that will be called for any state change<br>    fn subscribe(&amp;mut self, listener: fn(&amp;State)) {<br>        self.listeners.push(listener);<br>    }</pre><pre>    // Simply returns a borrowed reference to the state<br>    #[allow(dead_code)]<br>    fn get_state(&amp;self) -&gt; &amp;State {<br>        &amp;self.state<br>    }</pre><pre>    // Called for every new action, calls the reducer to update the state<br>    // and then calls every listener with the new state<br>    fn dispatch(&amp;mut self, action: Action) {<br>        self.state = (self.reducer)(&amp;self.state, action);<br>        for i in 0..self.listeners.len() {<br>            self.listeners[i](&amp;self.state);<br>        }<br>    }<br>}</pre><p>”<strong>fn create_store(reducer: fn(&amp;State, Action) -&gt; State) -&gt; Store {</strong>” looks a little complicated, but it’s only a function that takes a single function (the reducer) as it’s only argument, and returns a Store object. Because Rust is strongly typed we need to specify the type of the function we pass in: ”<strong>reducer: fn(&amp;State, Action) -&gt; State</strong>”.</p><p>You can check that this matches the reducer we defined earlier, it’s a function that takes a borrowed reference to the state, and an action, and returns a state.</p><p>”<strong>create_store</strong>” then returns a Store struct with the default state, an empty vector of listeners and the reducer we just passed in.</p><p>”<strong>subscribe</strong>” simply pushes the incoming listener function to the Store’s ”<strong>listeners</strong>” vector. Note the function signature on the listener ”<strong>listener: fn(&amp;State)</strong>”, this means any functions passed to subscribe need to take exactly one argument, a borrowed State.</p><p>”<strong>get_state</strong>” is a method to simply grab the current state, it returns a borrowed reference to the state. Note the ”<strong>#[allow(dead_code)]</strong>” above the function definition. This turns off the Rust compiler’s friendly warnings about us not using this code. We keep this method since it’s part of the Redux spec.</p><p>”<strong>dispatch</strong>” is probably the most interesting. You can see it takes a mutable borrow ”<strong>&amp;mut self</strong>”, this is because it will update the current state by calling the reducer and saving the returned state as the new state.</p><p>Once that’s done it loops through the listeners and calls them with the new state, this time passing along an immutable borrowed reference to the state.</p><p>Alright! We have all the building blocks needed for state management. Let’s look at the output functions we have for printing our list and instructions:</p><pre>// Very simple function to print a todo<br>fn print_todo(todo: &amp;Todo) {<br>    let done = if todo.completed { &quot;✔&quot; } else { &quot; &quot; };<br>    println!(&quot;[{}] {} {}&quot;, done, todo.id, todo.title);<br>}</pre><pre>// Our print_todos function from last time, a bit altered to take State<br>// as input instead of a todos list directly<br>fn print_todos(state: &amp;State) {<br>    let visibility = &amp;state.visibility_filter;<br>    println!(&quot;\n\nTodo List:\n-------------------&quot;);<br>    for i in 0..state.todos.len() {<br>        let todo = &amp;state.todos[i];<br>        if !todo.deleted {<br>            match *visibility {<br>                ShowAll =&gt; print_todo(&amp;todo),<br>                ShowCompleted =&gt; if todo.completed { print_todo(&amp;todo) },<br>                ShowActive =&gt; if !todo.completed { print_todo(&amp;todo) },<br>            }<br>        }<br>    }<br>    println!(&quot;-------------------\nVisibility filter:  {:?}&quot;, visibility);<br>    print_instructions();<br>}<br></pre><pre>fn print_instructions() {<br>    println!(&quot;\nAvailable commands: \nadd [text] - toggle [id] - remove [id]\nshow [all|active|completed]&quot;);<br>}</pre><pre>fn invalid_command(command: &amp;str) {<br>    println!(&quot;Invalid command: {}&quot;, command);<br>}</pre><p>A few things have changed here. ”<strong>print_todos</strong>” is now visibility_filter aware. It will print the todos only for the matching filter. We’ve broken out printing of a single todo item to a ”<strong>print_todo</strong>” function so that it’s easy to call it in several branches of our match statement.</p><p>Matching on enums is very straight forward as you can see. We also added a simple function to print the instructions for using the todo list.</p><p>So what about the actual implementation of all this?</p><pre>let mut store = Store::create_store(reducer);<br>    store.subscribe(print_todos);</pre><pre>    print_instructions();</pre><p>Unlike earlier, where we just made a todo list and then started modifying it, we now create a store, and subscribe our ”<strong>print_todos</strong>” function to it. This means the function will be called with the new state whenever it is updated, so we always have an up to date list printed.</p><pre>// Same input handling as last time, the interesting parts will be in our match statement<br>    loop {<br>        let mut command = String::new();<br>        io::stdin()<br>            .read_line(&amp;mut command)<br>            .expect(&quot;failed to read line&quot;);<br>        let command_parts: Vec&lt;&amp;str&gt; = command.split_whitespace().collect();</pre><pre>        match command_parts.len() {<br>            0 =&gt; invalid_command(&amp;command),<br>            _ =&gt; {<br>                match command_parts[0] {<br>                    // Since we prepared so well we just need to call dispatch on our store<br>                    // With the right action<br>                    &quot;add&quot; =&gt; store.dispatch( Todos(Add( command_parts[1..].join(&quot; &quot;).to_string() ))),<br>                    &quot;remove&quot; =&gt; if let Ok(num) = command_parts[1].parse::&lt;i16&gt;() {<br>                        store.dispatch( Todos(Remove(num)));<br>                    },<br>                    &quot;toggle&quot; =&gt; if let Ok(num) = command_parts[1].parse::&lt;i16&gt;() {<br>                        store.dispatch( Todos(Toggle(num)));<br>                    },<br>                    &quot;show&quot; =&gt; match command_parts[1] {<br>                        &quot;all&quot; =&gt; store.dispatch( Visibility(ShowAll) ),<br>                        &quot;active&quot; =&gt; store.dispatch( Visibility(ShowActive) ),<br>                        &quot;completed&quot; =&gt; store.dispatch( Visibility(ShowCompleted) ),<br>                        _ =&gt; invalid_command(&amp;command)<br>                    },<br>                    _ =&gt; invalid_command(&amp;command),<br>                }<br>            },<br>        }<br>    }</pre><p>We get the commands very much like in the previous example, we still split the terminal commands on spaces, and then handle the parts.</p><p>Once we have matched the command to a known action we simply run ”<strong>store.dispatch</strong>” with the action, otherwise we run the invalid_command function to print out the faulty command to the user.</p><p>Let’s look at the add action: ”<strong>”add” =&gt; store.dispatch( Todos(Add( command_parts[1..].join(“ “).to_string() ))),</strong>”. This creates and dispatched a Todos enum, with an Add enum as a value, that in turn holds a String as it’s value, the string being any input that follows the ”<strong>add</strong>” command.</p><p>That’s it, we’ve passed around a bunch of borrowed references, and our todo list still works as before, even with a few new features. The full code now looks like this:</p><pre>use std::io;</pre><pre>// Lets us type `Add(&quot;Todo item&quot;.to_string())` instead of `TodoAction::Add(&quot;Todo item&quot;.to_string())`<br>use TodoAction::{ Add, Remove, Toggle };<br>// Same with the Action enum and VisibilityFilter, Action::*; would work too, but this way we list what we use<br>use Action::{ Todos, Visibility };<br>use VisibilityFilter:: { ShowActive, ShowAll, ShowCompleted };</pre><pre>// Ripping off the canonical Redux todo example we&#39;ll add a<br>// visibility filter to our state except for the todos we already had<br>#[derive(Clone, Debug)]<br>struct State {<br>    todos: Vec&lt;Todo&gt;,<br>    visibility_filter: VisibilityFilter<br>}</pre><pre>// By implementing a struct we are creating something very much like<br>// a class, we can attach methods to it refering to &amp;self` or `&amp;mut self`<br>impl State {<br>    // This gives us a quick way to initialize a default state with State::default()<br>    pub fn default() -&gt; State {<br>        State {<br>            todos: Vec::new(),<br>            visibility_filter: VisibilityFilter::ShowAll,<br>        }<br>    }<br>}</pre><pre>// Same Todo as last time..<br>#[derive(Clone, Debug)]<br>struct Todo {<br>    id: i16,<br>    title: String,<br>    completed: bool,<br>    deleted: bool,<br>}</pre><pre>// Create a convenient Todo::new(id, title) method<br>impl Todo {<br>    pub fn new(id: i16, title: String) -&gt; Todo {<br>        Todo {<br>            id: id,<br>            title: title,<br>            completed: false,<br>            deleted: false,<br>        }<br>    }<br>}<br></pre><pre>// Rust has enums, so the enum type can replace the &quot;type&quot; property of Redux objects<br>// The enums will replace `action creators` too since Todos(Add(&quot;Todo item&quot;.to_string()))<br>// is pretty clear<br>#[derive(Clone, Debug)]<br>enum Action {<br>    Todos(TodoAction),<br>    Visibility(VisibilityFilter),<br>}</pre><pre>// mark_done from the previous example becomes Toggle to align with the Redux example<br>// otherwise functionality is the same<br>#[derive(Clone, Debug)]<br>enum TodoAction {<br>    Add(String),<br>    Toggle(i16),<br>    Remove(i16),<br>}</pre><pre>// Our 3 visibility states<br>#[derive(Clone, Debug)]<br>enum VisibilityFilter {<br>    ShowActive,<br>    ShowAll,<br>    ShowCompleted,<br>}</pre><pre>// Helper function for getting a mutable todo from a vector by todo_id<br>fn get_mut_todo(todos: &amp;mut Vec&lt;Todo&gt;, todo_id: i16) -&gt; Option&lt;&amp;mut Todo&gt; {<br>    todos.iter_mut().find(|todo|todo.id == todo_id)<br>}</pre><pre>// Our main reducer, returns a new State with the results of the child-reducers<br>// No combineReducers is implemented here, so it calls the child reducers<br>// by function name<br>fn reducer(state: &amp;State, action: Action) -&gt; State {<br>    // Always return a new state<br>    State {<br>        todos: todo_reducer(&amp;state.todos, &amp;action),<br>        visibility_filter: visibility_reducer(&amp;state.visibility_filter, &amp;action),<br>    }<br>}</pre><pre>// Our todo reducer, takes in state (todo list) and returns a new/cloned version<br>// after applying the action (is applicable)<br>fn todo_reducer(state: &amp;Vec&lt;Todo&gt;, action: &amp;Action) -&gt; Vec&lt;Todo&gt; {<br>    let mut new_state: Vec&lt;Todo&gt; = state.clone();</pre><pre>    // First we make sure it&#39;s a `Todos` action, otherwise return clone of incoming state<br>    match *action {<br>        Todos(ref todo_action) =&gt; match *todo_action {<br>            // Pretty simple from here on, check the type of Todos enum type<br>            // If Add push a new item, and if `Toggle` or `Remove` use our get_mut_todo<br>            // helper function and then change a property on the todo<br>            Add(ref title) =&gt; {<br>                let new_id = new_state.len() as i16 + 1;<br>                new_state.push(Todo::new(new_id, title.to_string()))<br>            },<br>            Toggle(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    if todo.completed { todo.completed = false; } else { todo.completed = true; }<br>                }<br>            },<br>            Remove(todo_id) =&gt; {<br>                if let Some(todo) = get_mut_todo(&amp;mut new_state, todo_id) {<br>                    todo.deleted = true;<br>                }<br>            },<br>        },<br>        // If it&#39;s not a Todos action change nothing<br>        _ =&gt; (),<br>    }<br>    return new_state;<br>}</pre><pre>// Very simple reducer since the action will either be a VisibilityFilter, in which<br>// case we will return that, otherwise just return the incoming state<br>fn visibility_reducer(state: &amp;VisibilityFilter, action: &amp;Action) -&gt; VisibilityFilter {<br>    match *action {<br>        Visibility(ref vis_action) =&gt; vis_action.clone(),<br>        _ =&gt; state.clone(),<br>    }<br>}</pre><pre>// Redux store implementation<br>struct Store {<br>    state: State,<br>    listeners: Vec&lt;fn(&amp;State)&gt;,<br>    reducer: fn(&amp;State, Action) -&gt; State,<br>}</pre><pre>impl Store {<br>    // Takes a reducer function, we skip the initial_state and optional arguments<br>    // TO keep it simple, State::default() from earlier is our initial_state implementation<br>    fn create_store(reducer: fn(&amp;State, Action) -&gt; State) -&gt; Store {<br>        Store {<br>            state: State::default(),<br>            listeners: Vec::new(),<br>            reducer: reducer,<br>        }<br>    }</pre><pre>    // Pushes a listener that will be called for any state change<br>    fn subscribe(&amp;mut self, listener: fn(&amp;State)) {<br>        self.listeners.push(listener);<br>    }</pre><pre>    // Simply returns the state<br>    #[allow(dead_code)]<br>    fn get_state(&amp;self) -&gt; &amp;State {<br>        &amp;self.state<br>    }</pre><pre>    // Called for every new action, calls the reducer to update the state<br>    // and then calls every listener<br>    fn dispatch(&amp;mut self, action: Action) {<br>        self.state = (self.reducer)(&amp;self.state, action);<br>        for i in 0..self.listeners.len() {<br>            self.listeners[i](&amp;self.state);<br>        }<br>    }<br>}</pre><pre>// Very simple function to print a todo<br>fn print_todo(todo: &amp;Todo) {<br>    let done = if todo.completed { &quot;✔&quot; } else { &quot; &quot; };<br>    println!(&quot;[{}] {} {}&quot;, done, todo.id, todo.title);<br>}</pre><pre>// Our print_todos function from last time, a bit altered to take State<br>// as input instead of a todos list directly<br>fn print_todos(state: &amp;State) {<br>    let visibility = &amp;state.visibility_filter;<br>    println!(&quot;\n\nTodo List:\n-------------------&quot;);<br>    for i in 0..state.todos.len() {<br>        let todo = &amp;state.todos[i];<br>        if !todo.deleted {<br>            match *visibility {<br>                ShowAll =&gt; print_todo(&amp;todo),<br>                ShowCompleted =&gt; if todo.completed { print_todo(&amp;todo) },<br>                ShowActive =&gt; if !todo.completed { print_todo(&amp;todo) },<br>            }<br>        }<br>    }<br>    println!(&quot;-------------------\nVisibility filter:  {:?}&quot;, visibility);<br>    print_instructions();<br>}<br></pre><pre>fn print_instructions() {<br>    println!(&quot;\nAvailable commands: \nadd [text] - toggle [id] - remove [id]\nshow [all|active|completed]&quot;);<br>}</pre><pre>fn invalid_command(command: &amp;str) {<br>    println!(&quot;Invalid command: {}&quot;, command);<br>}</pre><pre>fn main() {<br>    // Let&#39;s create our store and subscribe with print_todos so every update is printed<br>    let mut store = Store::create_store(reducer);<br>    store.subscribe(print_todos);</pre><pre>    print_instructions();</pre><pre>    // Same input handling as last time, the interesting parts will be in our match statement<br>    loop {<br>        let mut command = String::new();<br>        io::stdin()<br>            .read_line(&amp;mut command)<br>            .expect(&quot;failed to read line&quot;);<br>        let command_parts: Vec&lt;&amp;str&gt; = command.split_whitespace().collect();</pre><pre>        match command_parts.len() {<br>            0 =&gt; invalid_command(&amp;command),<br>            _ =&gt; {<br>                match command_parts[0] {<br>                    // Since we prepared so well we just need to call dispatch on our store<br>                    // With the right action<br>                    &quot;add&quot; =&gt; store.dispatch( Todos(Add( command_parts[1..].join(&quot; &quot;).to_string() ))),<br>                    &quot;remove&quot; =&gt; if let Ok(num) = command_parts[1].parse::&lt;i16&gt;() {<br>                        store.dispatch( Todos(Remove(num)));<br>                    },<br>                    &quot;toggle&quot; =&gt; if let Ok(num) = command_parts[1].parse::&lt;i16&gt;() {<br>                        store.dispatch( Todos(Toggle(num)));<br>                    },<br>                    &quot;show&quot; =&gt; match command_parts[1] {<br>                        &quot;all&quot; =&gt; store.dispatch( Visibility(ShowAll) ),<br>                        &quot;active&quot; =&gt; store.dispatch( Visibility(ShowActive) ),<br>                        &quot;completed&quot; =&gt; store.dispatch( Visibility(ShowCompleted) ),<br>                        _ =&gt; invalid_command(&amp;command)<br>                    },<br>                    _ =&gt; invalid_command(&amp;command),<br>                }<br>            },<br>        }<br>    }<br>}</pre><p>Don’t be surprised if you see more of the todo list, or a more complete Redux implementation in future posts.</p><p>Thanks for reading, if there’s any feedback it would be greatly appreciated. Even if you just want to tell me how wrong I am about something. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1386b095e49e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust for Node.js developers — Part 1 — Introduction to Rust]]></title>
            <link>https://medium.com/@fredrikanderzon/rust-for-node-js-developers-part-1-introduction-to-rust-283e8cec45ce?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/283e8cec45ce</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Tue, 10 May 2016 21:33:39 GMT</pubDate>
            <atom:updated>2016-06-18T08:57:07.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Rust?</h3><p>Rust is a strongly typed language from Mozilla that is usually described in sentences containing C++and systems programming. I would however like to compare it to Node, it’s very general purpose, keeps out of your way (most of the time) and just lets you be very productive. You can program pretty much any style in it, it’s a great functional language and I would say an equally great object oriented language if you can live with composition instead of traditional inheritance. Something Rust makes very easy with Traits.</p><h3>Why should I care?</h3><p>In short, you probably don’t have to, Javascript and Node can run everywhere and do pretty much everything. Rust’s main selling point is that it makes low level programming easier and it’s tough to beat JavaScript at easy…</p><p>But if you need more control over performance than Node can give you Rust is definitely for you, and if you have been using projects that makes JavaScript a little harder to write as a trade off for making it safer and more maintainable, Rust might not be such a big step.</p><p>Rust makes it very easy to write blazingly fast and safe code. It has a nicely designed type system and uses immutable data by default. It’s very safe, the compiler will stop you from compiling most code that would cause a runtime crash.</p><h3>What does it look like?</h3><p>This should look kind of familiar:</p><pre>let numbers = [1,2,3,4,5,6,7,8,9,10];</pre><pre>for i in 0..numbers.len() {<br>    println!(&quot;For {}&quot;, i);<br>}</pre><pre>let mut c = 0; <br>while c &lt; numbers.len() {<br>    println!(&quot;While {}&quot;, numbers[c]); <br>    c += 1; <br>}</pre><p>You can run this on <a href="https://play.rust-lang.org/">https://play.rust-lang.org/</a> if you don’t have Rust installed.</p><p>Notice the lack of type declarations? Wait… didn’t I say Rust was strongly typed? It is, but it also has some fairly clever type inference. We will get to the type system shortly though, because it’s pretty great!</p><p>First, let’s see what is going on here. numbers is as you might have guessed an <strong>array</strong>, this could be the last time you see me create one in this series though, since I’m not sure when I would want do that, arrays in Rust are fixed length, to get a data structure you can <strong>.push()</strong> to there are Vectors.</p><p>Next we have <strong>0..numbers.len()</strong>. In Rust you can generate <strong><em>Ranges</em></strong> as <strong>10..15</strong> and iterate over them which is pretty handy, the first number is inclusive, and the last one is exclusive, so you would get 10 through 14 from my example.</p><p><strong>println!</strong> is a macro, we will get to macros eventually, for now think of it as your console.log. println! will replace curly braces with arguments in order so <strong>println!(“I have {} dogs and {} goats…”, 4, 4)</strong>; will print <strong><em>I have 4 dogs and 4 goats…</em></strong>.</p><p>Let’s look at <strong>let mut c = 0;</strong>. Variables in Rust are immutable by default, if you want something you can modify later you need to specify that with the keyword mut.</p><p>The rest of the code behaves pretty much as expected. Array values can be accessed just like in javascript by index. You may also notice that there are no parens around the if and while conditions, this is not needed in Rust. If you include them anyway your code will run, but the compiler will warn about unneeded parens.</p><h3>Installing Rust</h3><p>If you are sufficiently intrigued to continue I strongly suggest installing Rust to follow along, the Rust playground we used above will get you a long way if you’re still not convinced though..</p><p>Up to date instructions can be found here: <a href="https://www.rust-lang.org/downloads.html">https://www.rust-lang.org/downloads.html</a></p><p>On Linux and Mac it should just be as easy as running this command:</p><pre>curl -sSf <a href="https://static.rust-lang.org/rustup.sh">https://static.rust-lang.org/rustup.sh</a> | sh</pre><h3>Setting up an editor for Rust</h3><p>I’m using it with atom, but rust plugins exists for a lot of editors and IDEs, <a href="https://www.rust-lang.org/ides.html">https://www.rust-lang.org/ides.html</a>. If you are planning to use Atom though I recommend installing the language-rust package and you are good to go.</p><p>I have one more package installed for rust that gives me code completion which is very useful, but it’s also a little more setup, so skip this part if you just want to get to the coding already.</p><p>The atom package for code completion is called <strong>racer</strong>. That package is just the racer bindings for atom, Racer is actually a separate piece of software you have to install, preferably via Cargo (Rust’s package manager).</p><p>It also needs access to the rust source code, and the paths to the installed racer binary and the rust language source need to be set in the settings of the atom package.</p><p>I’ll list how I did it on my Mac below, if it doesn’t work for you check out the instructions in the package notes instead:<a href="https://atom.io/packages/racer">https://atom.io/packages/racer</a></p><p>Let’s clone the rust source code repo and install racer, if you like me want a rust directory in your home directory:</p><pre>cd ~/<br>git clone <a href="https://github.com/rust-lang/rust.git">https://github.com/rust-lang/rust.git</a><br>cargo install racer</pre><p>When the Racer install complete’s it will tell you to be sure to add <strong>/Users/you/.cargo/bin</strong> to your PATH to be able to run the installed binaries so let’s do that:</p><p>Type <strong>sudo nano ~/.bash_profile</strong> and add:</p><pre>export PATH=/Users/widespace/.cargo/bin:$PATH </pre><p>on an empty line in the file. CTRL+O to save and CTRL+X to exit nano. Type <strong>source ~/.bash_profile</strong> to refresh with your new settings.</p><p>Next find and install racer in your atom packages, and click on the Settings for it, remember to replace <strong>you</strong> with your own home directory in the paths below, and if rust is not on version 1.8.0 anymore to replace that too.</p><p><em>Path to the Racer executable:</em><br><strong>/Users/you/.cargo/bin/racer</strong><br><em>Path to the Rust source code directory<br></em><strong>/Users/widespace/rust/src/rustc-1.8.0/src</strong><br><em>Cargo home directory<br></em><strong>/Users/you/.cargo</strong></p><p>That’s it, you should now have Rust code completion in Atom! In just a gazillion easy steps…</p><h3>Cargo and crates</h3><p>Rust’s “packages” are called crates and they are handled via Cargo, a command line package manager that get’s installed with the Rust language.</p><p>Cargo will scaffold your projects for you, handle your dependencies, and build/run your program for you.</p><p>Let’s get familiar with it, hop into a folder where you want to keep your rust projects, something like ~/rust/projects/ and run:</p><pre>cargo new intro --bin<br>cd intro</pre><p>The bin option is for binary, as in a normal Rust program, the default for cargo new is to create a library crate.</p><p>Cargo run has created a <strong>Cargo.toml</strong> for us, which is like a package.json file, and a <strong>src/main.rs</strong> which will be the entry point when running your rust program.</p><p>Let’s look at the Cargo.toml first:</p><pre>[package] name = &quot;intro&quot;<br>version = &quot;0.1.0&quot;<br>authors = [&quot;Fredrik Andersson &lt;f.xx@xx.xx&gt;&quot;]</pre><pre>[dependencies]</pre><p>Adding a dependency is as easy as adding a line with crate-name = “1.0.0” under the [dependencies] line. The next time you build your project with <strong>cargo build</strong> or <strong>cargo run</strong> your dependencies will update as needed. There is no npm install equivalent for handling your local dependencies from the command line unfortunately.</p><p>Next up <strong>src/main.rs</strong>:</p><pre>fn main() {<br>    println!(&quot;Hello, world!&quot;);<br>}</pre><p>Hello world! Isn’t that unconventional! <strong>fn</strong> declares a <em>function</em> as you might have guessed, the main function in your entry file is mandatory and is the one that will run when your rust program executes, so it’s very handy that Cargo created this for us.</p><p>Let’s run this with <strong>cargo run</strong> and make sure the setup works. You should get <em>Hello, world!</em> in the console.</p><h3>Time for some code again</h3><p>Let’s see what Rust has to offer from a Javascript perspective. The source code for the examples can be found <a href="https://github.com/fanderzon/rust-for-nodejs-devs">here</a>, but you should probably just follow along.</p><h3>Numbers</h3><p>JavaScript has the Number type, that covers everything. In Rust you will be using signed integers (positive or negative whole numbers), unsigned integers (only positive whole numbers) and floats (floating point, fractional values) in different bit sizes. We have:</p><ul><li><strong>signed integers</strong>: i8, i16, i32, i64</li><li><strong>unsigned integers</strong>: u8, u16, u32, u64</li><li><strong>floating point</strong>: f32, f64</li></ul><pre>fn main() {<br> // Rust can use numbers without needing the type specified<br> let a = 10;<br> let b = 1;<br> let c = a + b;<br> println!(“c is {}”, c);</pre><pre>// But if you want to specify a type in Rust this is the syntax<br> let d: i8 = 100;<br> let e: f32 = 0.42;<br> // and so on…</pre><pre>// This value is too high for an 8 bit integer, so the compiler will warn you<br> let f: i8 = 200;</pre><pre>// Let’s print the min and max value for each type so you get a feel of when to use them<br> println!(“i8 MIN {}”, std::i8::MIN);<br> println!(“i8 MAX {}”, std::i8::MAX);<br> println!(“i16 MIN {}”, std::i16::MIN);<br> println!(“i16 MAX {}”, std::i16::MAX);<br> println!(“i32 MIN {}”, std::i32::MIN);<br> println!(“i32 MAX {}”, std::i32::MAX);<br> println!(“i64 MIN {}”, std::i64::MIN);<br> println!(“i64 MAX {}”, std::i64::MAX);<br> println!(“u8 MIN {}”, std::u8::MIN);<br> println!(“u8 MAX {}”, std::u8::MAX);<br> println!(“u16 MIN {}”, std::u16::MIN);<br> println!(“u16 MAX {}”, std::u16::MAX);<br> println!(“u32 MIN {}”, std::u32::MIN);<br> println!(“u32 MAX {}”, std::u32::MAX);<br> println!(“u64 MIN {}”, std::u64::MIN);<br> println!(“u64 MAX {}”, std::u64::MAX);<br> println!(“f32 MIN {}”, std::f32::MIN);<br> println!(“f32 MAX {}”, std::f32::MAX);<br> println!(“f64 MIN {}”, std::f64::MIN);<br> println!(“f64 MAX {}”, std::f64::MAX);<br>}</pre><p>Running this code will print out c is 11 and a big list of what the min and max values of each type is. This should give you a feel of when to use what.</p><p>Defining a variable with a type is as you can see done with <strong>let variable_name: variable_type = variable_value;</strong>.</p><p>Before the output you should notice some warnings <strong>warning: unused variable</strong>: for <strong><em>d</em></strong>, <strong><em>e</em></strong> and <strong><em>f</em></strong> respectively. That’s right, Rust will warn you about code you are not using, that’s pretty awesome, and the answer to your next question is yes, it can be turned off on a case by case basis. <br> The next warning is <strong>warning: literal out of range for i8</strong>, this is because 200 is a bigger number than an 8 bit signed integer can represent. You can see from the list we should have used i16 there.</p><h3>Strings</h3><p>Rust has <strong>String</strong> and <strong>str</strong> or a <em>string slice</em>. <strong>“hello”</strong> gives you a string slice, and you can use <strong>.to_string()</strong> to get a String out of it, you will see that a lot in the example code to follow. We will go into a little more detail on strings in a later post, but String is the one you will want to use most of the time.</p><h3>Objects (and es6 Maps)</h3><p>Objects are a big part of JavaScript, you can use and abuse them to do almost anything. Rust has a lot more data types, but the ones you will use instead of object for most cases are <strong>Structs</strong> and <strong>HashMaps</strong>. Let’s have a look:</p><pre>// Hey look, we are telling Rust we need to use HashMap from it’s standard library<br>use std::collections::HashMap;</pre><pre>// Structs are great for representing data structures<br>struct Person {<br>    name: String,<br>    age: i16, // Yes, dangling commas are allowed and the convention<br>}</pre><pre>fn main() {<br>    // Using structs is basically like when defining them, <br>    // but with values<br>    let fredrik = Person {<br>        name: “Fredrik”.to_string(),<br>        age: 33,<br>    };<br>    // Snake case is so much the convention that the compiler <br>    // will warn you if you try to use camelCase<br>    let unknown_person = Person {<br>        name: “Unknown”.to_string(),<br>        age: 0,<br>    };</pre><pre>    println!(“Hi there {} and {}”, fredrik.name, unknown_person.name);</pre><pre>    // Let’s create a HashMap, these work more or less as es6 Sets<br>    // So when you want to hold arbitrary keys with arbitrary values<br>    //HashMap is your new best friend<br>    let mut ages = HashMap::new();</pre><pre>    // Insert name as key and age as value into the HashMap<br>    ages.insert(&amp;fredrik.name, &amp;fredrik.age);<br>    ages.insert(&amp;unknown_person.name, &amp;unknown_person.age);</pre><pre>    // Print ages to see what we have, notice the {:?} <br>    // instead of {} here?<br>    // Complex types need to specify how they should be printed <br>    // to work with {}, {:?} instead makes use of a Debug trait <br>    // in Rust, that can print almost anything, though not always <br>    // in a very pretty, readable format<br>    println!(“ages {:?}”, ages);</pre><pre>    // We can also remove stuff<br>    ages.remove(&amp;unknown_person.name);<br>    println!(“ages {:?}”, ages);</pre><pre>    // And we can also get values of course<br>    if let Some(fredrik_from_the_ages) = ages.get(&amp;fredrik.name) {<br>        println!(“Fredrik’s age is {}”, fredrik_from_the_ages);<br>    }<br>    // What is this sorcery? Why the if, and what is `Some`?<br>}</pre><p>Mostly straight forward I hope? There are two things in this example that isn’t really explained, first of all <strong>what’s with the ampersands?</strong>. <strong>&amp;fredrik.name</strong> denotes that we are <strong>borrowing</strong> (an immutable) reference to the name property from the fredrik variable, that means that it is still <strong><em>owned</em></strong> by fredrik. Rust’s borrowing is a subject of it’s own, we’ll gloss over it for now by saying that borrowing with &amp; is usually what you want to do.</p><p>Second, when getting a value from the HashMap we did something that can look a little strange. And this is because of a very good design decision in Rust: <strong>there is no null!</strong> And since <strong>.get()</strong> doesn’t know if it can return what you ask for in advance it returns a special type called <strong>Option</strong>. It’s a little as if you got back a Promise that you had to call <strong>.then()</strong> or <strong>.error()</strong> on, but it’s designed specifically to handle the case of something having a value or not. If it has a value you can get it by using <strong>Some(some_value)</strong> otherwise it will be <strong>None</strong>.</p><p>If you have looked at Elm or Haskell you’ll notice that Option is a lot like the <strong>Maybe</strong> type.</p><p>So in our case <strong>let Some(fredrik_from_the_ages)</strong> will be false if the <strong>.get()</strong> call returned a <strong>None</strong>.</p><h3>Arrays</h3><p>Like I hinted at after the very first example snippet, what you want to reach for in place of JavaScript arrays is probably the Vector type. A vector is a collection of values of the same type, if you need to get around that restriction there are ways to do it. But let’s just assume we will only work with values of the same type for now.</p><p>Example code time:</p><pre>fn main() {<br>    // So we first specify the type of values the vector will hold,<br>    // and then we call new to create an empty vector<br>    // Also notice the `mut`, without it we can’t push or <br>    // change anything<br>    let mut fruits: Vec&lt;String&gt; = Vec::new();</pre><pre>    // Now we can push stuff to it<br>    fruits.push(“Banana”.to_string());<br>    fruits.push(“Banana”.to_string());<br>    fruits.push(“Banana”.to_string());<br>    fruits.push(“Orange”.to_string());<br>    fruits.push(“Orange”.to_string());</pre><pre>    // values can be accessed by index of course<br>    println!(“{} is a fruit”, &amp;fruits[0]);</pre><pre>    // for in should feel familiar? will just print all fruits <br>    // one by one<br>    for fruit in &amp;fruits {<br>        println!(“{}”, fruit);<br>    }</pre><pre>// You can also loop over a range of integers like this<br>    // This will let us print out the lines of that bad joke you<br>    // probably saw coming When the fruits vector was populated ;)<br>    for i in 0..fruits.len() {<br>        // Match is the switch of Rust, it’s smarter as you’ll learn<br>        // later, but this might as well be a switch<br>        match i {<br>            // {} creates a block so we can do more than <br>            // one thing here<br>            // =&gt; will expect one expression<br>            0 =&gt; {<br>                println!(“Knock, knock”);<br>                println!(“Who’s there?”);<br>            },<br>            1 =&gt; {<br>                println!(“{}. Knock, knock”, <br>                    fruits[i]);<br>                println!(“Who’s there???”);<br>            },<br>            2 =&gt; {<br>                println!(“{}. Knock, knock”, fruits[i]);<br>                println!(“WHO’S THERE???”);<br>            },<br>            3 =&gt; {<br>                println!(“{}”, fruits[i]);<br>                println!(“{}, who?”, fruits[i]);<br>            },<br>            4 =&gt; {<br>                println!(“{} you glad I didn’t say {}?”,<br>                    fruits[i], fruits[0]);<br>                println!(“facepalm”);<br>            },<br>            // Rust wants to make sure your match statements <br>            // always get a match to avoid unexpected behaviors<br>            // `_` is the “default” or “catch all” rule<br>            _ =&gt; println!(“You are not even a fruit”),<br>        }<br>    }<br>}</pre><p>The match statement is completely new to you, but let’s just say it’s a switch for now. The rest is explained fairly well in the code.</p><h3>What about functional array methods?</h3><p>You can’t <strong>filter</strong>, <strong>map</strong> or <strong>reduce</strong> (which is called <strong>fold</strong> in Rust) directly over a Vector, but you can get an iterator from it that you can map etc. Let’s have a quick look at how that looks too.</p><pre>fn main() {<br>    // The `vec!` macro is a shorthand for creating vectors<br>    let nums = vec![1,2,3,4,5];</pre><pre>    // We need to specify the type here to make the compiler happy<br>    let multiplied: &amp;Vec&lt;i32&gt; = &amp;nums<br>        // Get an iterator from nums<br>        .iter()<br>        // Map over it and multiply each number by 2<br>        .map(|num| num * 2)<br>        // Filter out numbers that got too big for our taste<br>        .filter(|num| *num &lt; 8)<br>        // collect the result into a new vector<br>        .collect();<br>    println!(“Multiplied: {:?}”, multiplied);<br>}</pre><p>So what happens here? Let’s start almost from the bottom <strong>.collect();</strong>. collect is a consumer operator that takes an iterator and makes a vector out of it, other consumer operators could be <strong>fold</strong> or <strong>count</strong>.</p><p>A consumer operator takes an iterator and produces a value, and without one Rust iterators are <strong><em>lazy</em></strong>, until something comes and consumes the iterator it doesn’t do anything. This concept will be familiar to you if you have been working with <strong>observables/streams</strong> in JavaScript.</p><p>These weird pipe syntax in the map and filter signifies a Rust <strong>closure</strong>, we won’t go into details on that right now, but <strong>.map(|num| num * 2)</strong> is roughly equivalent to <strong>.map(num =&gt; num * 2)</strong> in JavaScript.</p><h3>Functions</h3><p>The last thing I want to cover is function basics, and I think that’s best done by combining what we’ve covered to build something.</p><p>Move up a level (<strong>cd ..</strong>) and start a new Cargo project with</p><pre>cargo new todo-list --bin</pre><p>Oh yeah! What kind of JavaScript developer would you be if your first impulse wasn’t to build a Todo list. Since Rust doesn’t run in the browser let’s make a command line tool:</p><p>Let’s set up the essentials first:</p><pre>use std::io;</pre><pre>struct Todo {<br>    id: i16,<br>    title: String,<br>    completed: bool,<br>    deleted: bool,<br>}</pre><pre>fn main() {<br>    let mut todos: Vec&lt;Todo&gt; = Vec::new();</pre><pre>    loop {<br>        let mut command = String::new();<br>        io::stdin()<br>            .read_line(&amp;mut command)<br>            .expect(“failed to read line”);</pre><pre>        println!(“Command is {}”, command);<br>    }<br>}</pre><p>The input processing is mostly copied from the <a href="https://doc.rust-lang.org/book/guessing-game.html">Guessing Game tutorial</a> from the official Rust book that I recommend doing also. :)</p><p><strong>stdin()</strong> from the <strong>io</strong> module of the Rust standard library is used to get input from the command line, so we need to use it with use <strong>std::io;</strong>.</p><p>Next we set up the struct to represent each todo entry, we want to be able to both get rid of todos added by mistake and mark them as done, so we add completed and deleted fields.</p><p>We make a mutable variable to hold the todos, nothing new there. Next we set up an infinite loop that will just wait for you to enter a line of input, which is then added to the command variable we set up.</p><p>If you run this code you should see some warnings about unused code, but the code will compile, and you can try entering text and have it echoed back at you.</p><p>Time to add some functions, add these just before the main function.</p><pre>fn add_todo(todos: &amp;mut Vec&lt;Todo&gt;, title: &amp;str) {<br>    // The size of the vector + 1 makes a decent enough id<br>    let new_id = todos.len() as i16 + 1;<br>    todos.push(Todo {<br>        id: new_id,<br>        title: title.to_string(),<br>        completed: false,<br>        deleted: false,<br>    });<br>}</pre><p>So, not surprising function parameters are declared much like variables. <strong>todos</strong> is a <strong><em>borrowed mutable reference</em></strong> to a <strong>Vector</strong> of <strong>Todos</strong>, and we take the title as a <strong>&amp;str</strong>, create a new <strong>Todo</strong> and push it into our <strong>todos</strong>. We get the id from adding one to the current size of the vector, one interesting thing could be this: <strong>todos.len() as i16</strong>. We use <strong>as i16</strong> to cast the vector size as an integer, because <strong>.len()</strong> actually returns a special kind of integer type <strong>usize</strong>.</p><pre>fn remove_todo(todos: &amp;mut Vec&lt;Todo&gt;, todo_id: i16) {<br>    if let Some(todo) = todos.iter_mut()<br>                            .find(|todo| todo.id == todo_id) {<br>        todo.deleted = true;<br>    }<br>}</pre><pre>fn mark_done(todos: &amp;mut Vec&lt;Todo&gt;, todo_id: i16) {<br>    if let Some(todo) = todos.iter_mut()<br>                            .find(|todo| todo.id == todo_id) {<br>        todo.completed = true;<br>    }<br>}</pre><p>Some more interesting things in these functions maybe, we iterate todos with .<strong>iter_mut()</strong> because we want to get back a reference we can mutate. <strong>.find()</strong> is a great method that returns an <strong>Option</strong> so we use <strong>if let Some(todo)</strong> as a quick way to only try to mutate the todo if we found a match.</p><pre>fn print_todos(todos: &amp;Vec&lt;Todo&gt;) {<br>    println!(“\n\nTodo List:\n — — — — — — — — — -”);<br>    for todo in todos {<br>        if !todo.deleted {<br>            let done = if todo.completed { “✔” } else { “ “ };<br>            println!(“[{}] {} {}”, done, todo.id, todo.title);<br>        }<br>    }<br>}</pre><pre>fn invalid_command(command: &amp;str) {<br>    println!(“Invalid command: {}”, command);<br>}</pre><p>Finally some convenience functions for printing the todo list, and invalid command messages. <strong>print_todos</strong> will print each line as <strong><em>[ ] 1 Do stuff.</em></strong></p><p>We can see that Rust lacks a ternary operator here: <strong>let done = if todo.completed { “✔” } else { “ “ };</strong>, but since you can assign the result of an if/else expression to a variable it’s still pretty clean.</p><p>That’s all the functions we’ll need, you can try them out as</p><pre>add_todo(&amp;mut todos, “Write Rust tutorial”);<br>add_todo(&amp;mut todos, “Bake cookies”);<br>print_todos(&amp;todos);</pre><p>to see it in action, now let’s write our complete main function:</p><pre>fn main() {<br>    let mut todos: Vec&lt;Todo&gt; = Vec::new();<br>    // Print the Todo list on start up<br>    print_todos(&amp;todos);</pre><pre>    // Loop over input lines forever and ever<br>    loop {<br>        // Assign input lines to the `command` variable<br>        let mut command = String::new();<br>        io::stdin()<br>            .read_line(&amp;mut command)<br>            .expect(“failed to read line”);</pre><pre>        // Split up the input string by spaces (or any whitespace)<br>        let command_parts: Vec&lt;&amp;str&gt; = command.split_whitespace().collect();</pre><pre>// Now match the size of the vector holding the separate <br>        // words in the command<br>        match command_parts.len() {<br>            // If 0 we can’t really do much<br>            0 =&gt; invalid_command(&amp;command),<br>            // If the length is 1 it’ a `list` command, <br>            // or an invalid command<br>            1 =&gt; match command_parts[0] {<br>                “list” =&gt; print_todos(&amp;todos),<br>                // Remember `_`is catch all<br>                _ =&gt; invalid_command(&amp;command),<br>            },<br>            // If the length is bigger than 1 we look for <br>            // `add x x x x`, `remove x` or `done x`<br>            _ =&gt; {<br>                // Match the first word in the command<br>                match command_parts[0] {<br>                    // If add, let’s join up all words except the<br>                    // first one as our todo title<br>                    // `[1..]` means from index 1 in the vector <br>                    // to the end<br>                    “add” =&gt; add_todo(&amp;mut todos,<br>                        &amp;command_parts[1..].join(“ “)),<br>                    // For remove and done we want to send in a<br>                    // todo_id, so we parse the string as an integer<br>                    // parse returns a `Result` that is either <br>                    // `Ok` or `Err`, so we can handle it much as <br>                    // an `Option` return<br>                    “remove” =&gt; if let Ok(num) = command_parts[1].parse::&lt;i16&gt;() {<br>                        remove_todo(&amp;mut todos, num)<br>                    },<br>                    “done” =&gt; if let Ok(num) = command_parts[1].parse::&lt;i16&gt;() {<br>                        mark_done(&amp;mut todos, num)<br>                    },<br>                    _ =&gt; invalid_command(&amp;command),<br>                }<br>            },<br>        }</pre><pre>        // At the end of each loop print the list<br>        print_todos(&amp;todos);<br>    }<br>}</pre><p>There we go, now if you run it it can be used like this:</p><pre>Todo List:<br> — — — — — — — — — -<br>add add items</pre><pre>Todo List:<br> — — — — — — — — — -<br>[ ] 1 add items<br>add show that you can mark items as done</pre><pre>Todo List:<br> — — — — — — — — — -<br>[ ] 1 add items<br>[ ] 2 show that you can mark items as done<br>done 2</pre><pre>Todo List:<br> — — — — — — — — — -<br>[ ] 1 add items<br>[✔] 2 show that you can mark items as done<br>add and maybe that you can remove something</pre><pre>Todo List:<br> — — — — — — — — — -<br>[ ] 1 add items<br>[✔] 2 show that you can mark items as done<br>[ ] 3 and maybe that you can remove something<br>remove 3</pre><pre>Todo List:<br> — — — — — — — — — -<br>[ ] 1 add items<br>[✔] 2 show that you can mark items as done</pre><p>Phew! That wraps up our Rust introduction, hopefully giving you a brief view of what Rust has to offer. We’ve skipped a lot of things completely, and glossed over others. I will try to dig deeper into one or two subjects at a time in future posts.</p><p><em>Originally published at </em><a href="http://fredrik.anderzon.se/2016/05/10/rust-for-node-developers-part-1-introduction/"><em>fredrik.anderzon.se</em></a><em> on May 10, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=283e8cec45ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lamdba (Node): Mapping input parameters and returning html]]></title>
            <link>https://medium.com/@fredrikanderzon/aws-lamdba-node-mapping-input-parameters-and-returning-html-87370ed3dd7?source=rss-81855f0dd6eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/87370ed3dd7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Fredrik Andersson]]></dc:creator>
            <pubDate>Tue, 24 Nov 2015 22:11:27 GMT</pubDate>
            <atom:updated>2015-11-24T22:11:27.984Z</atom:updated>
            <content:encoded><![CDATA[<p>So I sat down a couple of hours ago, thinking AWS Lambda could be the perfect service for something simple I needed to do:</p><p><em>Outputing some html dynamically based on a few incoming parameters, it’s basically “Hello, x”.</em></p><p>Which is exactly what I will boil down this example to, because it turns out there was a lot of hoops to jump through to make this work.</p><h4>Lambda functions</h4><p>Let’s start with the javascript part:</p><ul><li>Select Lambda in the AWS console and click “Create a Lambda function”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*lQPtO_PAxkxwEqd8GA2eFQ.png" /></figure><ul><li>Amazon provides you with some “blueprints”, which are little example functions that can get you started. You might want to browse these later to see what they all do, but for now hit “Skip” at the bottom.</li><li>Enter name and description. Pick any name you want, “helloX” or whatever describes what you want to do.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orD-9Hx5I3S4ngwOqHEAVw.png" /></figure><ul><li>Next we’ll enter some code:</li></ul><pre>const htmlStart = ‘&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;Dynamic page&lt;/title&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;/head&gt;&lt;body&gt;’;<br>const htmlEnd = ‘&lt;/body&gt;&lt;/html&gt;’;</pre><pre>exports.handler = function(event, context) {<br> var hello = event.hello || &#39;X&#39;,<br> code = htmlStart + &#39;Hello, &#39; + hello + htmlEnd;<br> <br> context.succeed({<br>   code: code<br> });<br>};<br></pre><p>Should be easy to keep up with this code, a lamdba handler function expects an event object as first arg (which holds the payload from an event) and a context object as a second arg, which holds runtime and request info.</p><p>The code expect an incoming “hello” property on the event object, wraps it in some html, and calls the context’s succeed method to finish (we could also call .fail() here).</p><p>The only other interesting part is the name of the export, “handler” which should match what’s the handler name we put in the next box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VL9FSbkLapsCepvCKLbkow.png" /></figure><ul><li>Since we named the export handler we can just leave this.</li><li>For Role select “Basic execution role” under “Create new role” in the drop down. This will take you to a new page where you can just select the defaults for creating a new role and clicking “Allow”.</li></ul><p>That’s the setup for the Lambda function, you can now click “Next”, and “Create” after you review your function info.</p><p>Congrats! You have a Lambda function! You can even test it by clicking the blue “Test” button above the code. The first time you do you get to configure the input for the test, for example:</p><pre>{<br>  &quot;hello&quot;: &quot;Lambda&quot;<br>}</pre><p>Running the test now you can see that the function outputs what you would expect.</p><h4>API Endpoints</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsPr7Fk_re-GB5g4qn78rA.png" /></figure><p>We do not yet have an endpoint setup, so let’s remedy that!</p><ul><li>Click “Add API endpoint” and add something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niX4E6VUVsonS-zeewr5Rg.png" /></figure><p>Notice I am creating a public URL by selecting “Open” under security.</p><p>This will give you a URL like: <a href="https://...x.execute-api.us-east-1.amazonaws.com/prod/helloX">https://...x.execute-api.us-east-1.amazonaws.com/prod/helloX</a> where you can access your lambda function.</p><p>This is the part where I thought I was almost done, but the rest took some figuring out unfortunately.</p><h4>Input mapping</h4><p>We have a URL, but no way to get any input variables to our lambda function yet, visiting our URL gives us back json with a default “Hello, X” message.</p><p>This new endpoint is using another AWS service, the “API Gateway”. We’ll do the rest of the configuration there. Open up a new tab and open your AWS console for API Gateway, <a href="https://console.aws.amazon.com/apigateway/home">https://console.aws.amazon.com/apigateway/home</a>.</p><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*rYKGU39zvWpjrS-oIuwQRw.png" /></figure><ul><li>Click “Resources” and then on “GET” on the left hand side:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ1O0T37r8V77jCEshRbZg.png" /></figure><ul><li>“Integration request” is where we can finally get our hands on some input variables, click that.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xHcPq9Jga-4jjS6u95MgQ.png" /></figure><p>This part can get a little frustrating but bear with me.</p><ul><li>First type in “application/json” under Content-Type on the left and click the little check mark.</li><li>Next click the edit button next to where it says “Input passthrough”, pick “Mapping template” in the dropdown.</li><li>In the next dropdown select “[Create a model]”, you would think that you could select Empty, edit the code a bit and save, maybe that’s supposed to work, but whatever I typed there never persisted for me whatever I tried.</li></ul><p>Anyway… A model is a json schema so we can add something like this:</p><pre><br>{<br>  &quot;title&quot;: &quot;Hello Schema&quot;,<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;hello&quot;: {<br>    &quot;type&quot;: “string”<br>   }<br>  },<br>  &quot;required&quot;: [&quot;hello&quot;]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poBOEhSWZbenBtJQ7qB4FQ.png" /></figure><ul><li>Click “Create model” and you’ll be taken back to the previous page.</li></ul><p>This time you can select your new “Hello” model. and tweak the code a little bit so it looks like this:</p><pre><br>#set($inputRoot = $input.path(&#39;$&#39;))<br>{<br>  &quot;hello&quot;: &quot;$input.params(&#39;hello&#39;)&quot;<br>}<br></pre><p>This should take care of input parameter mapping, if you want you can now deploy your API and see that the “hello” parameter is included in the response.</p><p><a href="https://...x.execute-api.us-east-1.amazonaws.com/prod/helloX?hello=Lambda">https://...x.execute-api.us-east-1.amazonaws.com/prod/helloX?hello=Lambda</a></p><p>The output is still JSON though, which is the last thing I wanted to take care of.</p><h4>Output mapping</h4><p>Let’s go back to this page (Click the blue breadcrumb that says “method execution” at the top of the page)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5ClQ6Q13jiIzx3VNxNtlQ.png" /></figure><p>We’re going to make a quick change to “Method Response” and then do most of the work in “Integration Response”, so click “Method Response” first.</p><ul><li>Click the little arrow next to “200” and add a Content-type header, the value we will add on the “Integration Response” page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0yTYI4lok-GkXdt3RRgYA.png" /></figure><p>The last part of the puzzle is the “Integration Response” page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nHY_n4WqzQxd32lifeULg.png" /></figure><ul><li>Under “Header Mappings” add ‘text/html’ as value, the single quotes are important. Save it by clicking the check mark next to the text box.</li><li>Under “Mapping Templates” add a text/html content type, and the following code as the mapping template (here it is perfectly OK to select the “Empty” model and modifying it).</li></ul><pre><br>#set($inputRoot = $input.path(‘$’))<br>$inputRoot.code<br></pre><p>We are just echoing out the code property we are returning from our lambda function here. Which with the proper Content-type headers should be all we need.</p><p>Once you’ve saved this you can hit the blue “Deploy API” button near the top, picking “prod” as environment and you should be good to go.</p><p>Your Lambda function is now a fully working “Hello, X” example, taking url params and delivering html. What else could you need in life? ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87370ed3dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>