<?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 Brook Jeynes on Medium]]></title>
        <description><![CDATA[Stories by Brook Jeynes on Medium]]></description>
        <link>https://medium.com/@jeynesbrook?source=rss-e2e7b4b3e940------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AOs1IqXLnkhHCbdgx-vPmw.jpeg</url>
            <title>Stories by Brook Jeynes on Medium</title>
            <link>https://medium.com/@jeynesbrook?source=rss-e2e7b4b3e940------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeynesbrook/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[Everyday Git: Stashing]]></title>
            <link>https://medium.com/@jeynesbrook/everyday-git-stashing-c858e35b84cc?source=rss-e2e7b4b3e940------2</link>
            <guid isPermaLink="false">https://medium.com/p/c858e35b84cc</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Brook Jeynes]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 22:38:15 GMT</pubDate>
            <atom:updated>2025-04-15T22:38:15.633Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post is part of Everyday Git, a series that explores Git features from the command line, with real-world usage in mind.</em></p><h3>Introduction</h3><p>Imagine you’re in the middle of developing a new feature on a separate branch. You’ve been experimenting with some changes, but you’re not quite ready to commit or push them yet. Suddenly, your boss walks in and asks you to drop everything and fix a critical bug — now.</p><p>You’re stuck. You have local changes you don’t want to lose or push, but you also don’t want to mix them with the quick bug fix. Switching branches isn’t possible while your working directory is dirty. So what now?</p><p>This is exactly where Git stash comes in.</p><h3>The basics of git stash</h3><p>At its core, git stash is a way to:</p><blockquote><em>record the current state of the working directory and the index (while allowing) to go back to a clean working directory. — </em><em>man git-stash(1)</em></blockquote><p>This saves all local changes and reverts the working directory to match the HEAD commit.</p><p>In the following example, foo.txt has been modified, so the working directory is dirty. Running git stash saves the local modifications to a new stash entry and rolls the working directory back to HEAD. A following git status shows what we&#39;d expect, a clean working directory.</p><pre>-- 👇 At HEAD<br>$ git log<br>commit a069749 (HEAD -&gt; main, origin/main, origin/HEAD)<br><br>    initial commit.<br><br>$ ls<br>foo.txt<br><br>-- 👇 Make a change to foo.txt<br>$ echo &quot;foo&quot; &gt;&gt; foo.txt<br><br>$ git status<br>Changes not staged for commit:<br>  modified: foo.txt<br><br>-- 👇 Stash changes<br>$ git stash<br>Saved working directory and index state WIP on main: a069749 initial commit.<br><br>-- 👇 Working tree is clean<br>$ git status<br>On branch main<br>Your branch is up to date with &#39;origin/main&#39;.<br><br>nothing to commit, working tree clean</pre><p>It’s worth noting that, like most Git commands, git stash can be passed the argument [-p | --patch] to interactively choose hunks to stash.</p><h3>Viewing the stash</h3><p>To view all stashed entries, git stash list can be used.</p><blockquote><em>Each stash entry is listed with its name, the name of the branch that was current when the entry was made, and a short description of the commit the entry was based on. — </em><em>man git-stash(1)</em></blockquote><p>The stash works like a stack — the latest stashed changes will always be stash@{0}.</p><pre>$ git stash list<br>stash@{0}: WIP on main: a069749 initial commit.</pre><p>In addition to git stash list, there may be times when the actual changes within a stash need to be seen. git stash show [&lt;stash&gt;] can be used for this purpose.</p><p>git stash show displays</p><blockquote><em>the changes recorded in the stash entry as a diff between the stashed contents and the commit back when the stash entry was first created. — </em><em>man git-stash(1)</em></blockquote><p>By default, git stash show will display the diffstat however, it accepts any formatting options known to git diff. This allows arguments such as -p to be used to see the changes in patch form.</p><pre>$ git stash list<br>stash@{0}: WIP on main: a069749 initial commit.<br>stash@{1}: WIP on main: a069749 initial commit.<br><br>$ git stash show 0<br>foo.txt | 1 +<br>1 file changed, 1 insertion(+)<br><br>$ git stash show -p 0<br>diff --git a/foo.txt b/foo.txt<br>index a069749..855c0bf 100644<br>--- a/foo.txt<br>+++ b/foo.txt<br>@@ -1 +1,4 @@<br>+ foo</pre><p>These defaults can be changed via the stash.showStat, stash.showPatch, and stash.showIncludeUntracked config variables when no &lt;diff-option&gt; is provided.</p><p>Looking back at the stashed changes, it was hard to figure out what each stash represented without further inspection. git stash is actually a shorthand for git stash push [(-m | --message) &lt;message&gt;]. git stash push allows an optional message to be passed giving more description to a stash entry.</p><pre>$ git stash push -m &quot;Add content&quot;<br>Saved working directory and index state On main: Add content<br><br>$ git stash list<br>stash@{0}: On main: Add content</pre><h3>Retrieving stashed changes</h3><p>We’ve stashed our changes, seen that they’ve been stashed, and even added a message to make it easier to find. We’ve fixed the reported bug and we’re ready to start working again on our feature. There are two main ways to recover the stashed changes, git stash pop [--index] [&lt;stash&gt;] and git stash apply [--index] [&lt;stash&gt;].</p><p>So how do these differ?</p><p>git stash pop [--index] [&lt;stash&gt;] will:</p><blockquote><em>Remove a single stashed state from the stash list and apply it on top of the current working tree state. — </em><em>man git-stash(1)</em></blockquote><p>If no additional arguments are passed, git stash pop will remove the top entry from the stash and apply it back to the working tree. This can fail due to conflicts and in these cases, the entry will not be removed from the stash list. Conflicts need to be resolved by hand, with git stash drop needing to be called manually after to remove the entry from the stash.</p><p>The additional arguments allow stash entries to be picked via stash index, e.g. 0, 1, or stash entry name, e.g. stash@{n}.</p><pre>-- 👇 Pops `stash@{0}` from stash<br>$ git stash pop<br>On branch main<br>Your branch is up to date with &#39;origin/main&#39;.<br><br>Changes not staged for commit:<br>    modified: foo.txt<br><br>no changes added to commit<br>Dropped refs/stash@{0} (a069749)<br><br>-- 👇 Nothing in the stash<br>$ git stash list</pre><p>git stash apply [--index] [&lt;stash&gt;] will:</p><blockquote><em>Like pop, (apply the stashed changes to the working tree state), but (will) not remove the state from the stash list. — </em><em>man git-stash(1)</em></blockquote><p>There’s one more difference worth mentioning here. &lt;stash&gt; may be any commit that looks like a commit created by stash push or stash create. You don&#39;t have to use a stash@{n} reference. You can use any commit SHA that was created by git stash push or git stash create. To understand what this means, let&#39;s dive a little deeper into what a stash entry actually is.</p><p>When a stash is created, behind the scenes, each stash is just a special kind of commit (actually, 3 commits: one for the working tree, one for the index, and one for untracked files).</p><p>The ancestry graph looks like this:</p><pre>       .----W<br>      /    /<br>-----H----I</pre><p>where H is the HEAD commit, I is a commit that records the state of the index, and W is a commit that records the state of the working tree.</p><p>You can manually create a stash using git stash create. This creates a stash entry and returns its object name without storing it anywhere in the ref namespace. Do note that git stash create isn&#39;t typically useful for everyday workflows - it&#39;s mainly intended for scripting.</p><h3>Merge conflicts</h3><p>As mentioned before, applying a stash may result in merge conflicts. Sometimes, those merge conflicts are so large that it’s easier to create a new branch from the stashed changes and continue work from there.</p><p>git stash branch &lt;branchname&gt; [&lt;stash&gt;] allows for just that. It will create and checkout a new branch named &lt;branchname&gt; starting from the commit at which the &lt;stash&gt; was originally created. It then applies the stashed changes to the new working tree and index. If this succeeds, it then drops the &lt;stash&gt; entry.</p><h3>Clearing the stash</h3><p>git stash clear will remove all stash entries. Only run this if you&#39;re sure you don&#39;t need the stashed changes anymore as once removed, the entries will be subject to pruning and may be impossible to recover.</p><p>Note, as per the Git man pages, it may be possible to recover mistakenly dropped or cleared stash entries. The following “incantation” will attempt to recover a list of stash entries that are still in your repository but no longer reachable.</p><pre>git fsck --unreachable | <br>grep commit | cut -d\  -f3 | <br>xargs git log --merges --no-walk --grep=WIP </pre><p>git stash drop [&lt;stash&gt;] is a little more safe and simply removes the specified entry from the stash.</p><h3>Scripting</h3><p>Git was designed not just as a user facing tool but also as a scripting tool. As such, there are some commands that are intended to be used for scripting purposes and not directly run by users. git stash create and git stash store are two examples of this.</p><p>As mentioned earlier, git stash create is a way to create a stash entry without storing it anywhere in the ref namespace. git stash store is a direct companion to this command and is a way to store a given stash in the stash ref in addition to updating the stash reflog.</p><h3>Deprecated</h3><p>There’s one additional git stash related command we haven&#39;t talked about yet and that&#39;s git stash save. This option is deprecated in favour of git stash push.</p><p>It behaves in a very similar way to git stash push with the main difference being that it cannot take a pathspec - the list of files to stash. Instead, all non-option arguments are concatenated to form the stash message.</p><h3>Conclusion</h3><p>As with any CLI tool, Git commands have myriad of additional options and edge cases. The goal of this series is to give you a strong foundation and help you confidently explore deeper when you’re ready.</p><p>Whether you’re dropping everything to fix a bug or just experimenting freely, stashing gives you room to breathe.</p><p>Thanks for reading,<br>- Brook ❤</p><p><em>Originally published at </em><a href="https://brookjeynes.dev/posts/everyday-git-stash/"><em>https://brookjeynes.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c858e35b84cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoding Hangeul, Koreas writing system.]]></title>
            <link>https://medium.com/@jeynesbrook/encoding-hangeul-koreas-writing-system-350a6859aab4?source=rss-e2e7b4b3e940------2</link>
            <guid isPermaLink="false">https://medium.com/p/350a6859aab4</guid>
            <category><![CDATA[hangul]]></category>
            <category><![CDATA[unicode]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[korean]]></category>
            <dc:creator><![CDATA[Brook Jeynes]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 02:08:48 GMT</pubDate>
            <atom:updated>2025-01-25T02:08:48.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hangeul (한글) is the modern writing system for the Korean language, created in 1443 by King Sejong the great, the fourth king of the Joseon dynasty¹. Before its invention, Korean was written using Hanja (한자) — Chinese characters adapted for Korean. Even after Hangeul’s creation, Hanja remained in regular use for centuries, particularly in formal and scholarly contexts².</p><p>Hangeul is a syllabic writing system where each syllable is composed of letters called Jamo (자모). These Jamo function like Latin letters, each representing an individual sound. There are a total of 11,172 syllabic combinations of Jamo which can be used to form Hangeul³.</p><p>However, learning Hangeul doesn’t require memorizing thousands of combinations. Instead, one only needs to learn the 68 different Jamo shapes and rules governing the construction of Hangeul. This is much easier than it sounds with the basics of the Korean alphabet being able to be learned within 60–90 minutes.</p><p>This post explores how Hangeul is encoded in Unicode, a universal standard that assigns unique values to characters across all languages⁴. It also delves into the mathematical operations used to construct and deconstruct individual Jamo from encoded Hangeul.</p><h3>Hangeul, Jamo, and Unicode</h3><p>A Korean syllable consists of a lead consonant, a medial vowel, and a tail consonant. For example,</p><p>한 (han) can be deconstructed like so:</p><ul><li>ㅎ (h) is the lead consonant.</li><li>ㅏ (a) is the medial vowel.</li><li>ㄴ (n) is the tail consonant.</li></ul><p>자 (ja) can be deconstructed like so:</p><ul><li>ㅈ (j) is the lead consonant.</li><li>ㅏ (a) is the medial vowel.</li><li>There is no tail consonant.</li></ul><p>Syllables starting with an initial vowel, for example 안 (an), must be prefixed with ㅇ (eung), a special lead consonant that produces no sound.</p><p>There are 19 different lead consonants ranging between Unicode values U+1100 and U+1112. There are 21 different vowels ranging between Unicode values U+1161 and U+1175. Finally, there are 27 tail consonants ranging between Unicode values U+11A8 and U+11C2 + a null consonant used when there is no tail. This range of Unicode is called the Hangeul Jamo block.</p><p>Below is a set of tables providing each Jamo, its canonical order, as well as its Unicode value. When Jamo are used in combination with each other, they change their shape, size, and positions slightly to fit into a single Hangeul. Unicode has a second range of Jamo characters called “Hangeul Compatibility Jamo” starting at U+3130 which represent the initial and final consonants with the same Unicode codepoint as opposed to the Hangeul Jamo block which assigns them separate codepoints⁵. These compatibility Jamo typically render much more clearer.</p><p>The table below shows both, the conjoining Jamo as well as the [compatibility Jamo] with the character reference hex value referring to the former⁶. Depending on your browser, both Jamo may render the same.</p><pre>| Number | Lead | Jamo   | Character reference |<br>|--------|------|--------|---------------------|<br>| 1      | G    | ᄀ [ㄱ] | 0x1100              |<br>| 2      | GG   | ᄁ [ㄲ] | 0x1101              |<br>| 3      | N    | ᄂ [ㄴ] | 0x1102              |<br>| 4      | D    | ᄃ [ㄷ] | 0x1103              |<br>| 5      | DD   | ᄄ [ㄸ] | 0x1104              |<br>| 6      | R    | ᄅ [ㄹ] | 0x1105              |<br>| 7      | M    | ᄆ [ㅁ] | 0x1106              |<br>| 8      | B    | ᄇ [ㅂ] | 0x1107              |<br>| 9      | BB   | ᄈ [ㅃ] | 0x1108              |<br>| 10     | S    | ᄉ [ㅅ] | 0x1109              |<br>| 11     | SS   | ᄊ [ㅆ] | 0x110A              |<br>| 12     |      | ᄋ [ㅇ] | 0x110B              |<br>| 13     | J    | ᄌ [ㅈ] | 0x110C              |<br>| 14     | JJ   | ᄍ [ㅉ] | 0x110D              |<br>| 15     | C    | ᄎ [ㅊ] | 0x110E              |<br>| 16     | K    | ᄏ [ㅋ] | 0x110F              |<br>| 17     | T    | ᄐ [ㅌ] | 0x1110              |<br>| 18     | P    | ᄑ [ㅍ] | 0x1111              |<br>| 19     | H    | ᄒ [ㅎ] | 0x1112              |<br><br>| Number | Vowel | Jamo   | Character reference |<br>|--------|-------|--------|---------------------|<br>| 1      | A     | ᅡ [ㅏ] | 0x1161              |<br>| 2      | AE    | ᅢ [ㅐ] | 0x1162              |<br>| 3      | YA    | ᅣ [ㅑ] | 0x1163              |<br>| 4      | YAE   | ᅤ [ㅒ] | 0x1164              |<br>| 5      | EO    | ᅥ [ㅓ] | 0x1165              |<br>| 6      | E     | ᅦ [ㅔ] | 0x1166              |<br>| 7      | YEO   | ᅧ [ㅕ] | 0x1167              |<br>| 8      | YE    | ᅨ [ㅖ] | 0x1168              |<br>| 9      | O     | ᅩ [ㅗ] | 0x1169              |<br>| 10     | WA    | ᅪ [ㅘ] | 0x116A              |<br>| 11     | WAE   | ᅫ [ㅙ] | 0x116B              |<br>| 12     | OE    | ᅬ [ㅚ] | 0x116C              |<br>| 13     | YO    | ᅭ [ㅛ] | 0x116D              |<br>| 14     | U     | ᅮ [ㅜ] | 0x116E              |<br>| 15     | WEO   | ᅯ [ㅝ] | 0x116F              |<br>| 16     | WE    | ᅰ [ㅞ] | 0x1170              |<br>| 17     | WI    | ᅱ [ㅟ] | 0x1171              |<br>| 18     | YU    | ᅲ [ㅠ] | 0x1172              |<br>| 19     | EU    | ᅳ [ㅡ] | 0x1173              |<br>| 20     | YI    | ᅴ [ㅢ] | 0x1174              |<br>| 21     | I     | ᅵ [ㅣ] | 0x1175              |<br><br>| Number | Tail | Jamo   | Character reference |<br>|--------|------|--------|---------------------|<br>| 1      | G    | ᆨ [ㄱ] | 0x11A8              |<br>| 2      | GG   | ᆩ [ㄲ] | 0x11A9              |<br>| 3      | GS   | ᆪ [ㄳ] | 0x11AA              |<br>| 4      | N    | ᆫ [ㄴ] | 0x11AB              |<br>| 5      | NJ   | ᆬ [ㄵ] | 0x11AC              |<br>| 6      | NH   | ᆭ [ㄶ] | 0x11AD              |<br>| 7      | D    | ᆮ [ㄷ] | 0x11AE              |<br>| 8      | L    | ᆯ [ㄹ] | 0x11AF              |<br>| 9      | LG   | ᆰ [ㄺ] | 0x11B0              |<br>| 10     | LM   | ᆱ [ㄻ] | 0x11B1              |<br>| 11     | LB   | ᆲ [ㄼ] | 0x11B2              |<br>| 12     | LS   | ᆳ [ㄽ] | 0x11B3              |<br>| 13     | LT   | ᆴ [ㄾ] | 0x11B4              |<br>| 14     | LP   | ᆵ [ㄿ] | 0x11B5              |<br>| 15     | LH   | ᆶ [ㅀ] | 0x11B6              |<br>| 16     | M    | ᆷ [ㅁ] | 0x11B7              |<br>| 17     | B    | ᆸ [ㅂ] | 0x11B8              |<br>| 18     | BS   | ᆹ [ㅄ] | 0x11B9              |<br>| 19     | S    | ᆺ [ㅅ] | 0x11BA              |<br>| 20     | SS   | ᆻ [ㅆ] | 0x11BB              |<br>| 21     | NG   | ᆼ [ㅇ] | 0x11BC              |<br>| 22     | J    | ᆽ [ㅈ] | 0x11BD              |<br>| 23     | C    | ᆾ [ㅊ] | 0x11BE              |<br>| 24     | K    | ᆿ [ㅋ] | 0x11BF              |<br>| 25     | T    | ᇀ [ㅌ] | 0x11C0              |<br>| 26     | P    | ᇁ [ㅍ] | 0x11C1              |<br>| 27     | H    | ᇂ [ㅎ] | 0x11C2              |</pre><h3>Encoding Hangeul</h3><p>Although each Jamo has its own individual Unicode value, Unicode values U+AC00 to U+D7A3 define every combination of Jamo, or every Hangeul character. This range of Unicode is called the Hangeul Syllables block⁷.</p><p>These syllables can be directly mapped by algorithm back to sequences of two or three Jamo in the Hangeul Jamo block mentioned earlier⁸. It’s due to this that it’s theoretically possible to encode Korean texts with Jamo only and let the font rendered handle Hangeul construction. This is not recommended in practice though due to limitations and lack of support in current renderers.</p><p>Isolated Jamo are rarely found in Korean texts instead opting for use of the precomposed Hangeul syllables. The codepoint of a Hangeul can be calculated from its Jamo components using the following formula⁹.</p><p>Hangeul Unicode = (((lead − 1) * 588) + ((vowel − 1) * 28) + tail) + 44032</p><p>In the formula, lead, vowel, and tail refer to the small integers given in the above tables. If there is no tail, the value 0 is used. The value 28 is the sum of the tail count. The value 588 is the sum of vowel and tail count. 44032 (0xAC00) is the first character of the Hangeul Syllables Unicode block.</p><p>As an example, let’s take the Hangeul 한 (han), which in Unicode is U+D55C. Using the Jamo that construct it, let’s try reach the final value.</p><pre>ㅎ = 19 // Lead consonant <br>ㅏ = 1 // Median vowel <br>ㄴ = 4 // Tail consonant <br><br>한 = U+D55C = 54620 = (((19 − 1) * 588) + ((1 − 1) * 28) + 4) + 44032 <br>                    = (10584 + 0 + 4) + 44032 <br>                    = 10588 + 44032 <br>                    = 54620</pre><p>Given the above formula, it can be rearranged to extract the Jamo of a Hangeul.</p><p>tail = mod(Hangeul Unicode — 44032, 28)<br>vowel = 1 + mod(Hangeul Unicode — 44032 — tail, 588) / 28<br>lead = 1 + floor[(Hangeul Unicode — 44032) / 588]</p><p>As another example, let’s try work backwards. Given the Hangeul 한 (han), let’s try deconstruct it.</p><pre>한 = U+D55C = 54620 <br><br>// tail <br>ㄴ = 4 = mod(54620 - 44032, 28) <br>       = mod(10588, 28) <br>       = 4 <br><br>// vowel <br>ㅏ = 1 = 1 + mod(54620 - 44032 - 4, 588) / 28 <br>       = 1 + mod(10584, 588) / 28 <br>       = 1 + 0 / 28 <br>       = 1 <br><br>// lead <br>ㅎ = 19 = 1 + floor[(54620 - 44032) / 588] <br>        = 1 + floor[10592 / 588] <br>        = 1 + 18 <br>        = 19</pre><h3>Obsolete Hangeul</h3><p>Overtime, Hangeul has undergone many changes with several Jamo no longer being used in modern Korean¹⁰.</p><ul><li>ㆍ (아래아, arae-a): A short “a” sound.</li><li>ㆆ (여린히읗, yeorin-hieut): A “light h”, akin to a softer version of the English “h”.</li><li>ㅿ (반시옷, bansiot): A “z” sound.</li><li>ㆁ (옛이응, yet-ieung): A velar nasal sound comparable to “ng” in the word “sing”.</li></ul><p>Since these obsolete characters are still used in older literature and historical texts, there’s still a need to have some way of using them. However, because they’re obsolete, Unicode does not offer precomposed Hangeul. Instead, syllables using them must be coded by Jamo.</p><h3>Conclusion</h3><p>Next time you type “한글” on your keyboard or read a text in Korean, you’ll know there’s a beautifully logical system at play behind the scenes — one that blends centuries of linguistic history with the modern efficiency of Unicode.</p><p>Thanks for reading,<br>- Brook ❤</p><h4>Footnotes</h4><p><strong>1</strong>: <a href="https://en.wikipedia.org/wiki/Hangul">https://en.wikipedia.org/wiki/Hangul</a><br><strong>2</strong>: <a href="https://en.wikipedia.org/wiki/Hanja">https://en.wikipedia.org/wiki/Hanja</a><br><strong>3</strong>: <a href="https://www.namhansouthkorea.com/how-many-korean-characters-are-there/">https://www.namhansouthkorea.com/how-many-korean-characters-are-there/</a><br><strong>4</strong>: <a href="https://www.unicode.org/standard/WhatIsUnicode.html">https://www.unicode.org/standard/WhatIsUnicode.html</a><br><strong>5</strong>: <a href="https://en.wikipedia.org/wiki/Hangul_Compatibility_Jamo">https://en.wikipedia.org/wiki/Hangul_Compatibility_Jamo</a><br><strong>6</strong>: <a href="http://www.gernot-katzers-spice-pages.com/var/korean_hangul_unicode.html">http://www.gernot-katzers-spice-pages.com/var/korean_hangul_unicode.html</a><br><strong>7</strong>: <a href="https://en.wikipedia.org/wiki/Hangul_Syllables">https://en.wikipedia.org/wiki/Hangul_Syllables</a><br><strong>8</strong>: <a href="https://www.unicode.org/reports/tr15/tr15-29.html#Hangul">https://www.unicode.org/reports/tr15/tr15-29.html#Hangul</a><br><strong>9</strong>: <a href="https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode">https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode</a><br><strong>10</strong>: <a href="https://colab.research.google.com/github/bebechien/gemma/blob/main/Translator_of_Old_Korean_Literature.ipynb">https://colab.research.google.com/github/bebechien/gemma/blob/main/Translator_of_Old_Korean_Literature.ipynb</a></p><p><em>Originally published at </em><a href="https://brookjeynes.dev/posts/unicode-hangeul/"><em>https://brookjeynes.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350a6859aab4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Tricks: Staging with patches]]></title>
            <link>https://medium.com/@jeynesbrook/git-tricks-staging-with-patches-a57f6a32e0a6?source=rss-e2e7b4b3e940------2</link>
            <guid isPermaLink="false">https://medium.com/p/a57f6a32e0a6</guid>
            <category><![CDATA[cmd]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Brook Jeynes]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 02:26:18 GMT</pubDate>
            <atom:updated>2025-01-03T02:26:18.681Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: This post is also accessible via my blog site found </em><a href="https://brookjeynes.dev/posts/git-tricks-git-add-patch/"><em>here</em></a><em>.</em></p><p>When working with Git, it’s common to accidentally include changes you didn’t intend to stage. Git provides tools to manage these situations effectively. One such tool is the patch sub-command, which allows you to interactively select and stage parts of a file’s changes.</p><p>This post explores how git add operates and how to leverage the patch <br>sub-command to stage changes and avoid unintended modifications in your commits.</p><h4>The basics of `git add`</h4><p>git add [&lt;pathspec&gt;...] will:</p><blockquote>update the index¹ using the current content found in the working tree…</blockquote><p>In other words, this will stage the entire patch from the specified files.</p><p>In the following example, there are two initial untracked files, foo.txt and bar.txt. After running the git-add command specifying foo.txt, it can be seen that the entire patch of foo.txt now exists in the index.</p><pre>$ ls<br>foo.txt bar.txt<br><br>$ cat foo.txt<br>foo<br><br>$ git status<br>Untracked files:<br> foo.txt<br> bar.txt<br><br>$ git add foo.txt<br>$ git status<br>Changes to be committed:<br> new file: foo.txt<br><br>Untracked files:<br> bar.txt</pre><h4>Why use the `patch` sub-command</h4><p>Adding the whole patch is usually the intended result by the user. However, there may be a time when you realise you left a modification within the file <br>you don’t want to stage.</p><p>This is where the patch sub-command can come in handy. Continuing from the previous example, let’s add the following lines to foo.txt.</p><pre>diff --git a/foo.txt b/foo.txt<br>index 257cc56..bbbdac3 100644<br>--- a/foo.txt<br>+++ b/foo.txt<br>@@ -1 +1,4 @@<br>foo<br>+ foo<br>+ bar<br>+ foo</pre><p>Just before staging the file, I notice that the line bar was mistakenly <br>included in foo.txt.</p><p>At this stage, you have two options:</p><ol><li>Open up a code editor and modify the file directly, then run git add foo.txt.</li><li>Use the patch sub-command.</li></ol><p>git add [-p|--patch] allows you to:</p><blockquote>Interactively choose hunks² of patch between the index and the work tree and add them to the index.</blockquote><p>The patch sub-command allows one to review the difference, and optionally edit it, before it is added to the index. The patch sub-command is shorthand for git add --interactive and selecting 5: patch.</p><p>Running the patch sub-command on the current example results in the following:</p><pre>$ git add -p foo.txt<br>diff --git a/foo.txt b/foo.txt<br>index 257cc56..bbbdac3 100644<br>--- a/foo.txt<br>+++ b/foo.txt<br>@@ -1 +1,4 @@<br> foo<br>+foo<br>+bar<br>+foo<br>(1/1) Stage this hunk [y,n,q,a,d,e,p,?]?</pre><p>Git offers many options³, which can be overwhelming at first. Pressing ? will print out a small help menu describing what each of the keybinds do.</p><pre>y - stage this hunk<br>n - do not stage this hunk<br>q - quit; do not stage this hunk or any of the remaining ones<br>a - stage this and all the remaining hunks in the file<br>d - do not stage this hunk nor any of the remaining hunks in the file<br>e - manually edit the current hunk<br>p - print the current hunk<br>? - print help</pre><p>In the example above, the line bar should be removed. To do so, press e to open $EDITOR and manually remove the line.</p><pre># Manual hunk edit mode -- see bottom for a quick guide.<br>@@ -1 +1,4 @@<br> foo<br>+foo<br>+bar<br>+foo<br># ---<br># To remove &#39;-&#39; lines, make them &#39; &#39; lines (context).<br># To remove &#39;+&#39; lines, delete them.<br># Lines starting with # will be removed.<br># If the patch applies cleanly, the edited hunk will immediately be marked for staging.<br># If it does not apply cleanly, you will be given an opportunity to<br># edit again. If all lines of the hunk are removed, then the edit is<br># aborted and the hunk is left unchanged.</pre><p>Once resolved, Git will provide the same options with the next hunk if available.</p><p>After the interaction, the index is left in the following state showing that <br>only our selected hunks were staged.</p><pre>$ git status<br>Changes to be committed:<br> new file: foo.txt<br><br>Changes not staged for commit:<br> modified: foo.txt<br><br>Untracked files:<br> bar.txt<br><br>$ git diff --staged foo.txt<br>diff --git a/foo.txt b/foo.txt<br>new file mode 100644<br>index 0000000..b4dfe34<br>--- /dev/null<br>+++ b/foo.txt<br>@@ -0,0 +1,3 @@<br>+foo<br>+foo<br>+foo<br><br>$ git diff foo.txt<br>diff --git a/foo.txt b/foo.txt<br>index b4dfe34..bbbdac3 100644<br>--- a/foo.txt<br>+++ b/foo.txt<br>@@ -1,3 +1,4 @@<br> foo<br> foo<br>+bar<br> foo</pre><h4>Conclusion</h4><p>By using Gits patch sub-command, changes can be easily reviewed and controlled prior to staging ensuring commits are clean, intentional, and free of accidental modifications.</p><p>Thanks for reading, <br>- Brook ❤</p><h4>Footnotes</h4><p><strong>1</strong>: The “index” holds a snapshot of the content of the working tree, and it is this snapshot that is taken as the contents of the next commit. <br><strong>2</strong>: <a href="https://www.gnu.org/software/diffutils/manual/html_node/Hunks.html](https://www.gnu.org/software/diffutils/manual/html_node/Hunks.html)">https://www.gnu.org/software/diffutils/manual/html_node/Hunks.html</a><br><strong>3</strong>: <a href="https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#_staging_patches](https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#_staging_patches)">https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#_staging_patches</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a57f6a32e0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Leptos: Building a Todo application — The basics, Part 1]]></title>
            <link>https://medium.com/@jeynesbrook/learning-leptos-building-a-todo-application-the-basics-part-1-602d113538d7?source=rss-e2e7b4b3e940------2</link>
            <guid isPermaLink="false">https://medium.com/p/602d113538d7</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[lepto]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Brook Jeynes]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 12:12:31 GMT</pubDate>
            <atom:updated>2023-04-20T13:06:23.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning Leptos: Building a Todo application — The basics, Part 1</h3><h4>Signals are what.. exactly?</h4><p>Hey all, in this 3 part series we’re going to build a simple todo application in <a href="https://github.com/leptos-rs/leptos">Leptos</a>. We’ll start at the basics, building out the initial UI and learning the common Leptos language. Then, we’ll add a database and move server logic into an API layer with Actix in the following parts.</p><p>Here’s a sneak peak of what you will have by the end of this part.</p><figure><img alt="Website design preview" src="https://cdn-images-1.medium.com/max/1024/0*yKie1MARXXnszYty.png" /></figure><p>All the code from this blog post can be found here: <a href="https://github.com/BrookJeynes/todo-leptos">https://github.com/BrookJeynes/todo-leptos</a></p><p>This guide assumes:</p><ul><li>You have a basic-to-decent understanding of Rust concepts and the language syntax.</li><li>You have Rust and Cargo installed</li></ul><p><em>Disclaimer: The code in this tutorial is used for teaching purposes and does not necessarily represent production ready code.</em></p><p>Now that that’s sorted, let’s begin!</p><h4>Getting started</h4><p>First, we must enable nightly rust and add the ability for it to compile Rust to WebAssembly:</p><pre>rustup toolchain install nightly<br>rustup default nightly<br>rustup target add wasm32-unknown-unknown</pre><p>Next we need to install <a href="https://github.com/leptos-rs/leptos">Leptos</a> and it’s build tool <a href="https://github.com/leptos-rs/cargo-leptos">Cargo-Leptos</a></p><pre>cargo install cargo-leptos</pre><p>Now we need to create our project. In this tutorial we will use the Tailwind example Leptos provides for us.</p><p><em>Note: If you don’t\ care about Tailwind integration, then all you have to do is run the following command to pull down the starter template and skip to the next section:</em></p><pre>cargo leptos new - git https://github.com/leptos-rs/start</pre><p>Currently, adding Tailwind is a little bit of a complicated process. Luckily for us, the team has released a Tailwind template we can simply just copy.</p><pre># Clone the Leptos project<br>git clone https://github.com/leptos-rs/leptos<br># Copy the tailwind example and call it todo-leptos<br>mv leptos/examples/tailwind ./todo-leptos<br># Delete the Leptos project<br>rm -rf leptos<br># Navigate into the project<br>cd todo-leptos</pre><p>With our project created, let’s add a few files, folders, and move some things around so we have a more ideal structure for long term.</p><pre>cd src<br><br>mkdir components<br>touch components.rs<br><br>mkdir pages<br>touch pages.rs<br>touch pages/home.rs</pre><p>Now that we have our pages and components set up, we need to expose them to the rest of the project. Add the following code to the top of lib.rs and main.rs</p><pre>pub mod app;<br>pub mod components;<br>pub mod pages;</pre><p>Let’s also move the Home component from app.rs to home.rs and remove everything inside so we’re left with a single div tag.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br><br>#[component]<br>fn Home(cx: Scope) -&gt; impl IntoView {<br>    view! { cx,<br>        &lt;div&gt;&lt;/div&gt;<br>    }<br>}</pre><p>We now need to expose Home by adding it into pages.rs</p><pre>// todo-leptos/src/pages.rs<br><br>pub mod home;</pre><p>Import Home back into app.rs by adding the following code to the <br>top of the file.</p><pre>use crate::pages::home::*;</pre><p>Finally, update Cargo.toml to reflect the code below:</p><pre>[package]<br>name = “todo-leptos”<br>version = “0.1.0”<br>edition = “2021”<br><br>[lib]<br>crate-type = [&quot;cdylib&quot;, &quot;rlib&quot;]<br><br>[dependencies]<br>actix-files = { version = &quot;0.6&quot;, optional = true }<br>actix-web = { version = &quot;4&quot;, optional = true, features = [&quot;macros&quot;] }<br>console_error_panic_hook = &quot;0.1&quot;<br>console_log = &quot;1&quot;<br>cfg-if = &quot;1&quot;<br><br>leptos = { version = &quot;0.2&quot;, default-features = false, features = [<br> &quot;serde&quot;,<br>] }<br>leptos_meta = { version = &quot;0.2&quot;, default-features = false }<br>leptos_actix = { version = &quot;0.2&quot;, optional = true }<br>leptos_router = { version = &quot;0.2&quot;, default-features = false }<br><br>log = &quot;0.4&quot;<br>simple_logger = &quot;4&quot;<br>wasm-bindgen = &quot;0.2&quot;<br><br>[features]<br>hydrate = [&quot;leptos/hydrate&quot;, &quot;leptos_meta/hydrate&quot;, &quot;leptos_router/hydrate&quot;]<br>ssr = [<br> &quot;dep:actix-files&quot;,<br> &quot;dep:actix-web&quot;,<br> &quot;dep:leptos_actix&quot;,<br> &quot;leptos/ssr&quot;,<br> &quot;leptos_meta/ssr&quot;,<br> &quot;leptos_router/ssr&quot;,<br>]<br><br>[profile.release]<br>codegen-units = 1<br>lto = true<br>opt-level = &#39;z&#39;<br><br>[package.metadata.leptos]<br># The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name <br>output-name = &quot;tailwind&quot;<br># The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.<br>site-root = &quot;target/site&quot;<br># The site-root relative folder where all compiled output (JS, WASM and CSS) is written<br># Defaults to pkg <br>site-pkg-dir = &quot;pkg&quot;<br># [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to &lt;site-root&gt;/&lt;site-pkg&gt;/app.css<br>style-file = &quot;style/output.css&quot;<br># [Optional] Files in the asset-dir will be copied to the site-root directory<br>assets-dir = &quot;public&quot;<br># The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.<br>site-addr = &quot;127.0.0.1:3000&quot;<br># The port to use for automatic reload monitoring<br>reload-port = 3001<br># [Optional] Command to use when running end2end tests. It will run in the end2end dir.<br>end2end-cmd = &quot;npx playwright test&quot;<br># The browserlist query used for optimizing the CSS.<br>browserquery = &quot;defaults&quot;<br># Set by cargo-leptos watch when building with tha tool. Controls whether autoreload JS will be included in the head<br>watch = false<br># The environment Leptos will run in, usually either &quot;DEV&quot; or &quot;PROD&quot;<br>env = &quot;DEV&quot;<br># The features to use when compiling the bin target<br>#<br># Optional. Can be over-ridden with the command line parameter - bin-features<br>bin-features = [&quot;ssr&quot;]<br># If the - no-default-features flag should be used when compiling the bin target<br>#<br># Optional. Defaults to false.<br>bin-default-features = false<br># The features to use when compiling the lib target<br>#<br># Optional. Can be over-ridden with the command line parameter - lib-features<br>lib-features = [&quot;hydrate&quot;]<br># If the - no-default-features flag should be used when compiling the lib target<br>#<br># Optional. Defaults to false.<br>lib-default-features = false</pre><p>And we’re done! You should now have something that resembles the following.</p><p><em>Note: Your structure may look a little different depending on whether you installed Tailwind or not, the following structure includes Tailwind files.</em></p><pre>.<br>├── Cargo.lock<br>├── Cargo.toml<br>├── end2end<br>│ ├── package-lock.json<br>│ ├── package.json<br>│ ├── playwright.config.ts<br>│ └── tests<br>│ └── example.spec.ts<br>├── input.css<br>├── LICENSE<br>├── Makefile.toml<br>├── public<br>│ └── favicon.ico<br>├── README.md<br>├── src<br>│ ├── app.rs<br>│ ├── components<br>│ ├── components.rs<br>│ ├── lib.rs<br>│ ├── main.rs<br>│ ├── pages<br>│ │ └── home.rs<br>│ └── pages.rs<br>├── style<br>│ └── output.css<br>└── tailwind.config.js</pre><p>Let’s give the project a test run to ensure everything is running correctly.</p><p><em>Note: If you’re using Tailwind, open up a terminal and run the following command in the background. This will ensure that the tailwind styles are kept updated on save. To run the following command, you will also need to install </em><a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm"><em>npm</em></a></p><pre>npx tailwindcss -i ./input.css -o ./style/output.css - watch</pre><p>We can leverage the cargo-leptos tool to run the web app.</p><pre>cargo leptos watch</pre><p>Hopefully everything ran fine :)</p><p>With that sorted, let’s create our first component!</p><h4>Components</h4><p>So what are components? Components are the basic building blocks of web development and that’s no different here. We can build components in Leptos by writing normal functions and adding the #[component] macro to it.</p><p>Let’s jump straight in and build our first component, something to handle rendering the individual todo items.</p><p>We first need to create a file to house the component.</p><pre># todo-leptos/src/components/<br>touch todo_item.rs</pre><p>and then register it within components.rs</p><pre>// todo-leptos/src/components.rs<br>pub mod todo_item;</pre><p>With all that out of the way, let’s start building out the structure. As mention previously, a Leptos component is a Rust function which has the #[component] macro above it. As well as this, every component must take in a reactive Scope and return impl IntoView</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>#[component]<br>pub fn TodoItem(cx: Scope) -&gt; impl IntoView {<br>    todo!()<br>}</pre><p>So what is Scope and why are we returning impl IntoView?<br>As described by the Leptos handbook:</p><blockquote>“This `Scope` is our entrypoint into the reactive system”</blockquote><p>To expand on this, it’s what gives our components the ability to be reactive and render new outputs on the DOM based on certain conditions.</p><p>impl IntoView on the other hand is almost a wrapper type that allows us to return anything from a Leptos view. This is useful as the view!{} macro we’ll use to write the HTML, generates view types.</p><p>Speaking of the view!{} macro, let’s use it to write some RSX, like JSX but using rust ;)</p><p>The view!{} macro starts by taking in our cx variable followed by a series of RSX statements.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>#[component]<br>pub fn TodoItem(cx: Scope) -&gt; impl IntoView {<br>    // 👇 New!<br>    view! { <br>        cx,<br>        &lt;div class=&quot;flex justify-between items-center&quot;&gt;<br>            &lt;span&gt;&quot;todo task name&quot;&lt;/span&gt;<br>            &lt;div class=&quot;flex justify-between w-fit sm:w-1/3&quot;&gt;<br>                &lt;button class=&quot;hover:cusor-pointer&quot;&gt;&quot;Complete&quot;&lt;/button&gt;<br>                &lt;button class=&quot;hover:cusor-pointer ml-4 sm:ml-0&quot;&gt;&quot;Delete&quot;&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p>I mean, wow! That’s pretty much straight HTML. All that’s really changed is the need to quote text. The power or Rust macros allows us to write (pretty much) standard HTML within our components.</p><p>While we’re inside of this file, let’s setup a struct to represent what a TodoItem will look like.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// 👇 New!<br>#[derive(Clone)]<br>pub struct TodoItem {<br>    pub id: u32,<br>    pub task: String,<br>    pub status: bool<br>}<br><br>#[component]<br>pub fn TodoItem(cx: Scope) -&gt; impl IntoView {<br>    // …<br>}</pre><p>We need to ensure our structures can be cloned as Leptos relies on data to be cloned from time to time. We’ll learn more about signals later on in the post but when signals are created, they must own the data. To access the data from the signal, the value is cloned so the signal can continue owning the underlying value.</p><p>With that all setup, let’s add a TodoItem component to the Home page.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    view! { <br>        cx,<br>        &lt;div class=&quot;h-screen&quot;&gt;<br>            &lt;div class=&quot;pt-20 mb-10 mx-auto px-5 w-full lg:px-0 lg:max-w-[90ch]&quot;&gt;<br>                // 👇 New!<br>                &lt;TodoItem /&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p>And with that, we’ve made our first component in Leptos!</p><h4>Props</h4><p>In the previous section we built a TodoItem component to render the individual todo items. However, you may have noticed that all we did was mock some data inside of the component. Wouldn’t it be great if we could pass a TodoItem into the component?</p><p>Using props we can do exactly that! Props allow us to pass different data structures into components. We define props just as we’d define a function parameter, let’s go ahead and add a TodoItem prop to our TodoItem component.</p><p>While we’re at it, lets also take the time to document our component. We can do so using normal Rust doc strings.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// …<br><br>/// A todo item component<br>#[component]<br>pub fn TodoItem(<br>    cx: Scope, <br>    // 👇 New prop!<br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>) -&gt; impl IntoView {<br>    view! { <br>        // …<br>    }<br>}</pre><p>With a TodoItem now being passed in, let’s display those values within the RSX. Variables can be displayed within RSX by surrounding the expresion in curly brackets — {}.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>#[derive(Clone)]<br>pub struct TodoItem {<br>    pub id: u32,<br>    pub task: String,<br>    pub status: bool<br>}<br><br>/// A todo item component<br>#[component]<br>pub fn TodoItem(<br>    cx: Scope, <br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>) -&gt; impl IntoView {<br>    view! { <br>        cx, <br>        &lt;div class=&quot;flex justify-between items-center&quot;&gt;<br>            &lt;span&gt;<br>                {todo_item.task} // 👈 New! <br>            &lt;/span&gt;<br> <br>            &lt;div class=&quot;flex justify-between w-fit sm:w-1/3&quot;&gt;<br>                &lt;button class=&quot;hover:cusor-pointer&quot;&gt;&quot;Complete&quot;&lt;/button&gt;<br>                &lt;button class=&quot;hover:cusor-pointer ml-4 sm:ml-0&quot;&gt;&quot;Delete&quot;&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>     }<br>}</pre><p>With the TodoItem component now taking in a prop, we need to update our instance of it within home.rs.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    let task: TodoItem = TodoItem {<br>        id: 0,<br>        task: String::from(&quot;Take out the trash&quot;),<br>        status: false,<br>    };<br><br>    view! { <br>        cx,<br>        &lt;div class=&quot;h-screen&quot;&gt;<br>            &lt;div class=&quot;pt-20 mb-10 mx-auto px-5 w-full lg:px-0 lg:max-w-[90ch]&quot;&gt;<br>                // 👇 New!<br>                &lt;TodoItem todo_item={task} /&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p><em>There are so many more things that can be done with props which you can read all about here: </em><a href="https://leptos-rs.github.io/leptos/view/03_components.html#components-and-props_"><em>https://leptos-rs.github.io/leptos/view/03_components.html#components-and-props</em></a></p><p>Let’s curve away from the TodoItem component for a second and build a new component that will teach us how to use Children. By having a component which takes in children, we can define wrapper components that wrap around some sort of content. To demonstrate this, we’ll build a PageWrapper component which takes in children and wraps it in<br>some styling.</p><p>We’ll start by creating a new file, page_wrapper.rs and register our component within components.rs.</p><pre># todo-leptos/src/components/<br>touch page_wrapper.rs</pre><pre>// todo-leptos/src/components.rs<br>pub mod todo_item;<br>// 👇 New!<br>pub mod page_wrapper;</pre><p>Let’s now define our component and pass in the Children prop.</p><pre>// todo-leptos/src/components/page_wrapper.rs<br>use leptos::*;<br><br>#[component]<br>pub fn PageWrapper(cx: Scope, children: Children) -&gt; impl IntoView {<br>    view! {<br>        cx,<br>        &lt;div class=&quot;h-screen&quot;&gt;<br>            &lt;div class=&quot;pt-20 mb-10 mx-auto px-5 w-full lg:px-0 lg:max-w-[90ch]&quot;&gt;<br>                {children(cx)}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p>Just as we’ve previously embedded code within RSX, we wrap our children() call in curly brackets — {}. When using Children we must also pass in the components Scope, cx in our instance.</p><p>We can now use our PageWrapper component within home.rs and pass in our TodoItem component as a child element.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>// 👇 New!<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    let task: TodoItem = TodoItem {<br>        id: 0,<br>        task: String::from(&quot;Take out the trash&quot;),<br>        status: false,<br>    };<br><br>    view! { <br>        cx,<br>        // 👇 New!<br>        &lt;PageWrapper&gt;<br>            &lt;div id=&quot;todo_items&quot;&gt;<br>                &lt;TodoItem todo_item={task} /&gt;<br>            &lt;/div&gt;<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p>Everything we place inside the PageWrapper tags will be rendered where we<br>specified children(cx).</p><h4>Iteration</h4><p>Displaying one todo item is cool and all but what if we wanted to store more? Let’s go ahead and create a list of TodoItems and find out how we can iterate through them and display them all on the page.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // 👇 New!<br>    let todo_items: Vec&lt;TodoItem&gt; = vec![<br>        TodoItem {<br>            id: 0,<br>            task: String::from(&quot;Take out the trash&quot;),<br>            status: false,<br>        },<br>        TodoItem {<br>            id: 1,<br>            task: String::from(&quot;Make the bed&quot;),<br>            status: false,<br>        },<br>        TodoItem {<br>            id: 2,<br>            task: String::from(&quot;Mow the lawn&quot;),<br>            status: true,<br>        },<br>        TodoItem {<br>            id: 3,<br>            task: String::from(&quot;Wash the dishes&quot;),<br>            status: false,<br>        },<br>    ];<br><br>    view! { <br>        cx,<br>        &lt;PageWrapper&gt;<br>            &lt;div id=&quot;todo_items&quot;&gt;<br>                // Let&#39;s comment this out for the mean time to avoid errors<br>                // &lt;TodoItem todo_item={task} /&gt;<br>            &lt;/div&gt;<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p>There are a few ways we can display a collection of items. One of those ways is via the &lt;For /&gt; component. The &lt;For /&gt; component is a keyed dynamic list and is particularly useful for our use-case as our list of todo items will be changing often as the user creates and deletes items.</p><p>As per the Leptos handbook:</p><blockquote>The &lt;For/&gt; component … takes [in] three props:<br>1. `each`: a function (such as a signal) that returns the items `T` to be iterated over<br> 2. `key`: a key function that takes `&amp;T` and returns a stable, unique key or ID<br> 3. `view`: renders each `T` into a view</blockquote><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    let todo_items: Vec&lt;TodoItem&gt; = vec![<br>        // ...<br>    ];<br><br>    view! { <br>        cx,<br>        &lt;PageWrapper&gt;<br>            &lt;div id=&quot;todo_items&quot;&gt;<br>                // 👇 New!<br>                &lt;For<br>                    each=move || { todo_items.clone() }<br>                    key=|task| task.id<br>                    view=move |cx, task: TodoItem| {<br>                        view! {<br>                            cx,<br>                            &lt;TodoItem todo_item={task} /&gt;<br>                        }<br>                    }<br>                /&gt;<br>            &lt;/div&gt;<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p>And just like that we have a series of todo items being rendered. Don’t worry too much right now why we’re using closures, we’ll go over that in the next section.</p><p><em>Read more about iteration here: </em><a href="https://leptos-rs.github.io/leptos/view/04_iteration.html_"><em>https://leptos-rs.github.io/leptos/view/04_iteration.html</em></a></p><h4>Reactive data</h4><p>A Signal is “the basic unit of reactive change and state management” and is how we make things reactive in Leptos. Using create_signal(), we can create a new reactive signal which we can read and write to.</p><p>create_signal() returns a (getter, setter) tuple. We can use &lt;getter&gt;.get(), or &lt;getter&gt;()r in nightly, to get the value, &lt;setter&gt;.set(), or &lt;setter&gt;() in nightly, to set the value, and &lt;setter&gt;.update() to update the value.</p><p>Let’s go ahead and turn our todo_items vector into a signal using create_signal(). While we’re at it, let’s also update the &lt;For /&gt; tag to take in our signal.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // 👇 New!<br>    // Signals<br>    let (todo_items, set_todo_items) = create_signal(cx, vec![<br>            // ...<br>        ]<br>    );<br>    <br>    view! { <br>        cx,<br>        &lt;PageWrapper&gt;<br>            &lt;div id=&quot;todo_items&quot;&gt;<br>                // 👇 New!<br>                &lt;For<br>                    // We no longer need to use a closure as `todo_items` is now a signal<br>                    each={todo_items}<br>                    key=|task| task.id<br>                    view=move |cx, task: TodoItem| {<br>                        view! {<br>                            cx,<br>                            &lt;TodoItem todo_item={item} /&gt;<br>                        }<br>                    }<br>                /&gt;  <br>            &lt;/div&gt;<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p>One thing you may have noticed is we moved from using a closure to just passing in our signal, why is that? While I won’t try compete with the <a href="https://leptos-rs.github.io/leptos/interlude_functions.html">official handbook which explains why in much more detail</a> the tldr of it all is that closures give Leptos the ability to re-run certain statements allowing certain components to be updated when call to do so.</p><p>Now that we know how to make things reactive, lets get some more practice in and make our TodoItem component responsive to change.</p><p>Let’s start with something simple, changing the todo task from in-progress to done. We’ll start by creating a signal to handle the getter and setter methods.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// …<br><br>/// A todo item component<br>#[component]<br>pub fn TodoItem(<br>    cx: Scope, <br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>) -&gt; impl IntoView {<br>    // 👇 New!<br>    // Signals<br>    let (status, set_status) = create_signal(cx, todo_item.status);<br><br>    view! { <br>        // …<br>    }<br>}</pre><p>Now, we want status to update whenever we press the “complete” button. For this, we’ll need to add an on:click event handler to the button.</p><p><em>Read more about handlers here: </em><a href="https://docs.rs/leptos/latest/leptos/ev/trait.EventDescriptor.html#associatedtype.EventType_"><em>https://docs.rs/leptos/latest/leptos/ev/trait.EventDescriptor.html#associatedtype.EventType</em></a></p><p>Let’s create the logic for when our on:click handler fires. All we want to do is update the status and we can do so with the .update() method on the setter set_status.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// …<br><br>/// A todo item component<br>#[component]<br>pub fn TodoItem(<br>    cx: Scope, <br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>) -&gt; impl IntoView {<br>    // Signals<br>    let (status, set_status) = create_signal(cx, todo_item.status);<br>    <br>    // 👇 New!<br>    // Handlers<br>    let on_click = move |_| {<br>        // Update gives us a `&amp;T` so we must dereference the value to use it<br>        set_status.update(|status| *status = !*status)<br>    };<br><br>    view! { <br>        // …<br>    }<br>}</pre><p>With the on_click handler defined, let’s add it to our buttons callback.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// …<br><br>/// A todo item component<br>#[component]<br>pub fn TodoItem(<br>    cx: Scope, <br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>) -&gt; impl IntoView {<br>    // Signals<br>    let (status, set_status) = create_signal(cx, todo_item.status);<br>    <br>    // Handlers<br>    let on_click = move |_| {<br>        set_status.update(|status| *status = !*status)<br>    };<br><br>    view! { <br>        cx,<br>        &lt;div class=&quot;flex justify-between items-center&quot;&gt;<br>            &lt;span&gt;<br>                {todo_item.task} <br>            &lt;/span&gt;<br><br>            &lt;div class=&quot;flex justify-between w-fit sm:w-1/3&quot;&gt;<br>                // 👇 New!<br>                &lt;button on:click={on_click} class=&quot;hover:cusor-pointer&quot;&gt;&quot;Complete&quot;&lt;/button&gt;<br>                &lt;button class=&quot;hover:cusor-pointer ml-4 sm:ml-0&quot;&gt;&quot;Delete&quot;&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p>Using the same method as above, let’s add some reactive text and button styling.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// …<br><br>/// A todo item component<br>#[component]<br>pub fn TodoItem(<br>    cx: Scope, <br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>) -&gt; impl IntoView {<br>    // Signals<br>    let (status, set_status) = create_signal(cx, todo_item.status);<br><br>    // Handlers<br>    let on_click = move |_| {<br>        set_status.update(|status| *status = !*status)<br>    };<br><br>    // 👇 New!<br>    // Classes<br>    let task_title_style = move || format!(&quot;text-md {}&quot;, if status() { &quot;line-through&quot; } else { &quot;&quot; });<br>    let complete_button_style = move || {<br>        format!(<br>            &quot;hover:cursor-pointer {}&quot;,<br>            if !status() {<br>                &quot;opacity-100&quot;<br>            } else {<br>                &quot;opacity-50&quot;<br>            }<br>        )<br>    };<br><br>    view! { <br>        cx,<br>        &lt;div class=&quot;flex justify-between items-center&quot;&gt;<br>            // 👇 New!<br>            &lt;span class={task_title_style}&gt;<br>                {todo_item.task} <br>            &lt;/span&gt;<br><br>            &lt;div class=&quot;flex justify-between w-fit sm:w-1/3&quot;&gt;<br>                // 👇 New!<br>                &lt;button <br>                    on:click={on_click} <br>                    class={complete_button_style}<br>                &gt;<br>                    {move || if !status() { &quot;Complete&quot; } else { &quot;Undo&quot; }}<br>                &lt;/button&gt;<br><br>                &lt;button <br>                    class=&quot;hover:cusor-pointer ml-4 sm:ml-0&quot;<br>                &gt;<br>                    &quot;Delete&quot;<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p>Look at us go, Reactivity for the win!</p><p>There’s one final thing we need to go over within this section before finishing up with the TodoItem component.</p><p>How would we go about removing a task from our task list? We can’t have the delete logic in the component but we also want the user to click a button within the component. It would be great if our component could call a function external to itself.</p><p>We can achieve this behaviour using callbacks. Callback functions are functions we pass into components and have their internal logic decide when the function is called.</p><p>Let’s jump back into Home and define the function we’ll use to delete a task<br>from our task list.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // Signals<br>    let (todo_items, set_todo_items) = create_signal(cx,<br>        vec![<br>            // …<br>        ],<br>    );<br><br>    // 👇 New!<br>    // Handlers<br>    let delete_todo_item = move |todo_id: u32| {<br>        // Here we use the `retain()` method to filter out all <br>        // elements that don&#39;t match the predicate<br>        set_todo_items.update(move |todo_items| {<br>            todo_items.retain(|todo_item| {<br>                todo_item.id != todo_id<br>            })<br>        });<br>    };<br><br>    view! { <br>        // …<br>    }<br>}</pre><p>Now we need to alter TodoItem to take in a callback function. We do so by defining some generic, F in our instance, that maps out to the callbacks signature. Since we’re here, we’ll also add an on:click method to the delete button using the new callback.</p><pre>// todo-leptos/src/components/todo_item.rs<br>use leptos::*;<br><br>// …<br><br>/// A todo item component<br>#[component]<br>// 👇 New!<br>pub fn TodoItem&lt;F&gt;(<br>    cx: Scope, <br>    /// The todo item the component will use to populate its internal data<br>    todo_item: TodoItem<br>    // 👇 New!<br>    /// A callback to delete a TodoItem<br>    delete_callback: F<br>) -&gt; impl IntoView<br>where<br>    // Remember our delete callback takes in a TodoItem ID<br>    F: Fn(u32) + &#39;static,<br>{<br>    // …<br><br>    view! { <br>        cx,<br>        &lt;div class=&quot;flex justify-between items-center&quot;&gt;<br>            &lt;span class={task_title_style}&gt;<br>                {todo_item.task} <br>            &lt;/span&gt;<br><br>            &lt;div class=&quot;flex justify-between w-fit sm:w-1/3&quot;&gt;<br>                &lt;button <br>                    on:click={on_click} <br>                    class={complete_button_style}<br>                &gt;<br>                    {move || if !status() { &quot;Complete&quot; } else { &quot;Undo&quot; }}<br>                &lt;/button&gt;<br>                &lt;button <br>                    // 👇 New!<br>                    on:click={move |_| delete_callback(todo_item.id)} <br>                    class=&quot;hover:cusor-pointer ml-4 sm:ml-0&quot;<br>                &gt;<br>                    &quot;Delete&quot;<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    }<br>}</pre><p>To close off this section let’s pass in the callback from home.rs and pat<br>ourselves on the back, we’re nearly at the finish line for part 1.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // Signals<br>    let (todo_items, set_todo_items) = create_signal(cx,<br>        vec![<br>            // …<br>        ],<br>    );<br>    <br>    // Handlers<br>    let delete_todo_item = move |todo_id: u32| {<br>        // Here we use the `retain()` method to filter out all <br>        // elements that don&#39;t match the predicate<br>        set_todo_items.update(move |todo_items| {<br>            todo_items.retain(|todo_item| {<br>                todo_item.id != todo_id<br>            })<br>        })<br>    };<br><br>    view! { <br>        cx,<br>        &lt;PageWrapper&gt;<br>            &lt;div id=&quot;todo_items&quot;&gt;<br>                &lt;For<br>                    each={todo_items}<br>                    key=|task| task.id<br>                    view=move |cx, task: TodoItem| {<br>                        view! {<br>                            cx,<br>                            // 👇 New!<br>                            &lt;TodoItem todo_item={item} delete_callback={delete_todo_item} /&gt;<br>                        }<br>                    }<br>                /&gt;<br>            &lt;/div&gt;<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p><em>Read more about callbacks here: </em><a href="https://leptos-rs.github.io/leptos/view/08_parent_child.html#2-use-a-callback_"><em>https://leptos-rs.github.io/leptos/view/08_parent_child.html#2-use-a-callback</em></a></p><h4>Forms</h4><p>With our todo items able to be complete and deleted, all we need to do now is create a way of adding new tasks. To do this, we’ll set up a &lt;form&gt; and learn how to reference nodes and use the on:submit callback.</p><p>To start off, let’s create the HTML for the form.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // …<br><br>    view! { <br>        cx,<br>        &lt;PageWrapper&gt;<br>            // 👇 New!<br>            &lt;div id=&quot;add-task&quot; class=&quot;flex flex-col rounded mb-20 text-black&quot;&gt;<br>                &lt;h2 class=&quot;text-2xl font-medium mb-4&quot;&gt;&quot;Add Task&quot;&lt;/h2&gt;<br>                &lt;form class=&quot;w-full flex flex-col&quot;&gt;<br>                    &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                        &lt;input<br>                            class=&quot;w-2/3 px-2 py-1 border-b-2 border-black focus:outline-none&quot;<br>                            type=&quot;text&quot;<br>                            placeholder=&quot;Add a new task&quot;<br>                        /&gt;<br>                        &lt;input class=&quot;hover:cursor-pointer&quot; type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;<br>                    &lt;/div&gt;<br>                &lt;/form&gt;<br>            &lt;/div&gt;<br><br>            &lt;div id=&quot;todo_items&quot;&gt;<br>                // 👇 New!<br>                &lt;h2 class=&quot;text-2xl font-medium mb-4&quot;&gt;&quot;Tasks&quot;&lt;/h2&gt;<br>                &lt;For<br>                    each={todo_items}<br>                    key=|task| task.id<br>                    view=move |cx, task: TodoItem| {<br>                        view! {<br>                            cx,<br>                            // 👇 New!<br>                            &lt;TodoItem todo_item={item} delete_callback={delete_todo_item} /&gt;<br>                        }<br>                    }<br>                /&gt;<br>            &lt;/div&gt;<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p>Inside our form we have an text input box and a submit button. To get the information from inside the text input box on submit, we’ll need to create a NodeRef.</p><blockquote>“[A] NodeRef to access the input once when we want to get its value.”</blockquote><p>To create a NodeRef, the create_node_ref() function can be used. Let’s also<br>create the function to handle the on:submit callback.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>// 👇 New!<br>use leptos::html::Input;<br>use leptos::ev::SubmitEvent;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // Signals<br>    // 👇 New!<br>    let todo_task_input_ref: NodeRef&lt;Input&gt; = create_node_ref(cx);<br><br>    // 👇 New!<br>    // Helpers<br>    /// Helper function to grab the largest ID.<br>    /// Used to know what the next todo item ID should be<br>    let last_todo_id = move || todo_items().iter().map(|todo_item| todo_item.id).max();<br><br>    // Handlers<br>    // 👇 New!<br>    let on_submit = move |ev: SubmitEvent| {<br>        // Prevent the page from refreshing<br>        ev.prevent_default();<br><br>        // Clone the vector to mutate it<br>        let mut new_todo_items = todo_items();<br><br>        // Get the next node ID<br>        let todo_id = last_todo_id().unwrap_or_default() + 1;<br><br>        // Create a new TodoItem and push it to our new todo_items vector<br>        new_todo_items.push(TodoItem {<br>            id: todo_id,<br>            task: todo_task_input_ref().expect(&quot;&lt;input&gt; to exist&quot;).value(),<br>            status: false,<br>        });<br><br>        // Set our todo_items signal to have the new todo_items vector<br>        set_todo_items.set(new_todo_items);<br>    };<br><br>    // …<br><br>    view! { <br>        // …<br>    }<br>}</pre><p>Now all we need to do is add the on_submit() handler to the submit input button and add the todo_task_input_ref to the text input.</p><pre>// todo-leptos/src/pages/home.rs<br>use leptos::*;<br>// 👇 New!<br>use leptos::html::Input;<br>use leptos::ev::SubmitEvent;<br>use crate::components::todo_item::*;<br>use crate::components::page_wrapper::*;<br><br>#[component]<br>pub fn Home(cx: Scope) -&gt; impl IntoView {<br>    // …<br><br>    view! { <br>        cx,<br>        &lt;PageWrapper&gt;<br>            &lt;div id=&quot;add-task&quot; class=&quot;flex flex-col rounded mb-20 text-black&quot;&gt;<br>                &lt;h2 class=&quot;text-2xl font-medium mb-4&quot;&gt;&quot;Add Task&quot;&lt;/h2&gt;<br>                &lt;form <br>                    class=&quot;w-full flex flex-col&quot;<br>                    // 👇 New!<br>                    on:submit={on_submit}<br>                &gt;<br>                    &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                        &lt;input<br>                            class=&quot;w-2/3 px-2 py-1 border-b-2 border-black focus:outline-none&quot;<br>                            type=&quot;text&quot;<br>                            placeholder=&quot;Add a new task&quot;<br>                            // 👇 New!<br>                            node_ref={todo_task_input_ref}<br>                        /&gt;<br>                        &lt;input<br>                            class=&quot;hover:cursor-pointer&quot; <br>                            type=&quot;submit&quot; <br>                            value=&quot;Submit&quot; <br>                        /&gt;<br>                    &lt;/div&gt;<br>                &lt;/form&gt;<br>            &lt;/div&gt;<br><br>            // …<br>        &lt;/PageWrapper&gt; <br>    }<br>}</pre><p><em>Read more about forms here: </em><a href="https://leptos-rs.github.io/leptos/view/05_forms.html#uncontrolled-inputs_"><em>https://leptos-rs.github.io/leptos/view/05_forms.html#uncontrolled-inputs</em></a></p><p>And we’re done! You can now add, update, and remove todo items.</p><h4>Conclusion</h4><p>Today we covered:<br>- Creating a Leptos project<br>- Creating components<br>- Passing in props<br>- Passing in children<br>- Adding reactivity via signals<br>- Creating and passing callbacks<br>- Creating node references and dealing with forms<br>- And more…</p><p>We covered a lot of important concepts and going forward will be using them and learning even more. To learn more about what we covered today, I’ve linked the Leptos handbook in the “References / Resources” section below which I highly recommend reading along with this guide.</p><p>All the code from this blog post can be found here: <a href="https://github.com/BrookJeynes/todo-leptos">https://github.com/BrookJeynes/todo-leptos</a></p><p>If you liked the post, please star the <a href="https://github.com/BrookJeynes/todo-leptos">GitHub repository</a> and if you have any comments, feel free to leave them below, I always love hearing what you guys have to say.</p><p>Look out for part 2 and 3 where we create a database and API to interact with from our front-end.</p><p>I’d like to end with saying a huge thank you to the team working at Leptos who not only proof-read this blog post but who have also been working incredibly hard to bring such an amazing framework to the community. Your work is appreciated</p><p>Thanks for reading,<br>- Brook ❤</p><h4>References / Resources</h4><p>- <a href="https://leptos-rs.github.io/leptos/">The Leptos Handbook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602d113538d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication for API Routes using Rocket.rs and Rust]]></title>
            <link>https://medium.com/@jeynesbrook/jwt-authentication-for-api-routes-using-rocket-rs-and-rust-fe7529792a70?source=rss-e2e7b4b3e940------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe7529792a70</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Brook Jeynes]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 07:59:32 GMT</pubDate>
            <atom:updated>2022-11-30T07:59:32.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>Adding JWT authentication onto Rocket.rs API routes via request guards and the jsonwebtoken crate.</h4><p>In this guide I’m going to explain to you what JWTs are, why they’re important in API authentication, and how to add JWT authentication to API routes using Rocket.rs + Rust.</p><p>This guide assumes:</p><ul><li>You already have a series of Rocket.rs routes set-up already.</li><li>You have the latest version of Rust (this guide uses v1.65.0).</li><li>You have a basic-to-decent understanding of Rust concepts and the language syntax.</li></ul><p><em>Note: The code in this blog is just an example introduction into how to encode and decode JWTs in Rust. This code is not production ready.</em></p><p>Now that that’s sorted, let’s begin!</p><h3>What are JWTs?</h3><p>JWTs — also know by JSON Web Tokens — are an open standard which allows a secure way to communicate information between two entities, typically consisting of some server and client. The information contained within JWTs can be considered “verified and trusted” — (Okta, n.d.) due to the token being digitally signed via a secret, encoded using a HMAC algorithm, or a public/private key pair using RSA or ECDSA.</p><p>In the following guide we will be using JWTs to verify the integrity of some users claim. When a user logs into their account, a JWT is created containing information related to that user, signed via some secret key only the server knows. The client can then use that token to verify themselves when attempting to do things such as deleting accounts or accessing confidential data.</p><p><em>For more information on JWTs, visit </em><a href="https://jwt.io/"><em>jwt.io</em></a><em>.</em></p><h3>What is a Request Guard?</h3><p>Request guards are a way of guarding an API route from incoming requests based on some validation policy. For example, say we have a route that returns information about a certain user. We only want the user in question to have access to their information. We can use a request guard to verify the integrity of the client making the request, ensuring that only the correct user can gain access.</p><p>Each route can have multiple request guards with them firing from left-to-right. If, at any point, a request guard fails, none of the remaining guards are attempted.</p><p><em>For more information on </em><a href="https://rocket.rs/v0.5-rc/guide/requests/#request-guards"><em>Request Guards</em></a><em>, visit the </em><a href="https://rocket.rs/v0.5-rc/"><em>official Rocket.rs docs</em></a><em>.</em></p><h3>Required Dependencies</h3><p>Here are a list of dependencies and their versions used within this blog.</p><pre>[dependencies]<br>rocket = { version = &quot;0.5.0-rc.2&quot;, features = [&quot;json&quot;] }<br>serde = { version = &quot;1.0.147&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0.88&quot;<br>chrono = &quot;0.4.23&quot;<br>jsonwebtoken = &quot;8.1.1&quot;<br>dotenvy = &quot;0.15&quot;</pre><h3>Building the data Models</h3><p>The first step in this process is defining the types of responses the request guard can throw back at us. We can define a custom enum which derives Responder allowing us to write our own HTTP responses. Along with this, we’ll define a struct and enum to handle our request responses.</p><pre>use rocket::Responder;<br>use rocket::serde::Serialize;<br><br>#[derive(Responder, Debug)]<br>pub enum NetworkResponse {<br>    #[response(status = 201)]<br>    Created(String),<br>    #[response(status = 400)]<br>    BadRequest(String),<br>    #[response(status = 401)]<br>    Unauthorized(String),<br>    #[response(status = 404)]<br>    NotFound(String),<br>    #[response(status = 409)]<br>    Conflict(String),<br>}<br><br>#[derive(Serialize)]<br>pub enum ResponseBody {<br>    Message(String),<br>    AuthToken(String),<br>}<br><br>#[derive(Serialize)]<br>#[serde(crate = &quot;rocket::serde&quot;)]<br>pub struct Response {<br>    pub body: ResponseBody,<br>}</pre><p>We’re also going to need to define a struct for the claims our JWTs will encode and a struct for the token itself. Here subject_id will correspond to the id of the user who created the token and exp will represent how long the token has to live.</p><pre>use rocket::serde::{Deserialize, Serialize};<br><br>#[derive(Debug, Deserialize, Serialize)]<br>pub struct Claims {<br>    pub subject_id: i32,<br>    exp: usize<br>}<br><br>#[derive(Debug)]<br>pub struct JWT {<br>    pub claims: Claims<br>}</pre><p>Finally, a simple user struct will need to be created if you don’t have one already.</p><pre>pub struct User {<br>    pub id: i32,<br>    pub user_name: String,<br>    pub password: String,<br>}</pre><h3>Encoding and Decoding JWTs</h3><p>With the models defined, let’s go ahead and write the functions for generating and decoding the tokens.</p><p>We want to provide a token back to the user whenever they verify who they are (e.g. on login). Let’s create a function create_jwt() which takes in the users id and returns a result of either a JSON string containing the JWT or some jsonwebtoken Error.</p><pre>use jsonwebtoken::errors::Error;<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; {<br>    todo!()<br>}</pre><p>After this, we need to define how long the JWT has before it expires. In a production application, JWTs are meant for long-term usage. However, because this is a local example project, our tokens will expire within 60 seconds. This will allow for easy testing as we won’t have to wait long to check if it has expired.</p><p>Using the chrono library, we can create a variable holding the current time and then add an additional 60 seconds to that.</p><pre>use chrono::Utc; // 👈 New! <br>use jsonwebtoken::errors::ErrorKind;<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; {<br>    // 👇 New!<br>    let expiration = Utc::now().checked_add_signed(chrono::Duration::seconds(60)).expect(&quot;Invalid timestamp&quot;).timestamp();<br>    <br>    todo!()<br>}</pre><p>With the expiration variable defined and the user id passed in, we can now create our claims object. While we’re at it we’ll also create the JWTs header and encode it with HMAC using SHA-512.</p><pre>use chrono::Utc;<br>use jsonwebtoken::{Algorithm, Header}; // 👈 New!<br>use jsonwebtoken::errors::Error;<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; {<br>    let expiration = Utc::now().checked_add_signed(chrono::Duration::seconds(60)).expect(&quot;Invalid timestamp&quot;).timestamp();<br>    <br>    // 👇 New!<br>    let claims = Claims { <br>    subject_id: id,<br>    exp: expiration as usize<br>    };<br><br>    // 👇 New!<br>    let header = Header::new(Algorithm::HS512);<br><br>    todo!()<br>}</pre><p>With all that done, the final thing we need we need to do is use the encode() function provided to us from the jsonwebtoken crate. encode() takes in three arguments:</p><ul><li>The JWT header.</li><li>The claims object.</li><li>The secret key to encode the token.</li></ul><p>It’s important that we keep the secret key private as if someone is able to access it, they can use it to forge a JWT. In this tutorial we will store the JWT secret in an .env file.</p><pre>use chrono::Utc;<br>use jsonwebtoken::{encode, EncodingKey, Algorithm, Header}; // 👈 New!<br>use jsonwebtoken::errors::Error;<br>use std::env; // 👈 New!<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; {<br>    let secret = env::var(&quot;JWT_SECRET&quot;).expect(&quot;JWT_SECRET must be set.&quot;); // 👈 New!<br><br>    let expiration = Utc::now().checked_add_signed(chrono::Duration::seconds(60)).expect(&quot;Invalid timestamp&quot;).timestamp();<br>    <br>    let claims = Claims {<br>        subject_id: id,<br>        exp: expiration as usize<br>    }; <br><br>    let header = Header::new(Algorithm::HS512);<br><br>    // 👇 New!<br>    encode(&amp;header, &amp;claims, &amp;EncodingKey::from_secret(secret.as_bytes()))<br>}</pre><p>In order to access our .env file, we need to load it first. In your main function, add the following code:</p><pre>use dotenvy::dotenv;<br><br>fn main() {<br>    dotenv().ok();<br>}</pre><p>With our encoding functioned defined, we now need a way to decode and authenticate a token when provided one. For this, we will create a function called decode_jwt() which will take in a JWT and return a result of either a Claims object containing the items encoded or some jsonwebtoken ErrorKind.</p><pre>use chrono::Utc;<br>use jsonwebtoken::{encode, EncodingKey, Algorithm, Header};<br>use jsonwebtoken::errors::{Error, ErrorKind}; // 👈 New!<br>use std::env;<br>use dotenvy::dotenv;<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; { // … }<br><br>// 👇 New!<br>fn decode_jwt(token: String) -&gt; Result&lt;Claims, ErrorKind&gt; {<br>    todo!()<br>}</pre><p>When we pass in the token it will be in the format of “Bearer x”, we need to first extract x, the token itself. We can do this using a variety of trimming methods first removing “Bearer” from the start, then trimming all white spaces at the start and end.</p><pre>use chrono::Utc;<br>use jsonwebtoken::{encode, EncodingKey, Algorithm, Header};<br>use jsonwebtoken::errors::{Error, ErrorKind};<br>use std::env;<br>use dotenvy::dotenv;<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; { // … }<br><br>fn decode_jwt(token: String) -&gt; Result&lt;Claims, ErrorKind&gt; {<br>    // 👇 New!<br>    let token = token.trim_start_matches(&quot;Bearer&quot;).trim();<br><br>    todo!()<br>}</pre><p>With the token in a valid format, we can simply decode it now using the decode() function provided to us from the jsonwebtoken crate. decode() takes in three arguments:</p><ul><li>A JWT.</li><li>The secret key used to encode the token.</li><li>The validation algorithm.</li></ul><p>If successful, the decode() function will provide us the claims encoded within the token.</p><pre>use chrono::Utc;<br>use jsonwebtoken::{encode, decode, EncodingKey, Algorithm, Header, Validation}; // 👈 New!<br>use jsonwebtoken::errors::{Error, ErrorKind};<br>use std::env;<br>use dotenvy::dotenv;<br><br>pub fn create_jwt(id: i32) -&gt; Result&lt;String, Error&gt; { // … }<br><br>fn decode_jwt(token: String) -&gt; Result&lt;Claims, ErrorKind&gt; {<br>    let secret = env::var(&quot;JWT_SECRET&quot;).expect(&quot;JWT_SECRET must be set.&quot;);<br>    let token = token.trim_start_matches(&quot;Bearer&quot;).trim();<br><br>    // 👇 New!<br>    match decode::&lt;Claims&gt;(<br>        &amp;token,<br>        &amp;DecodingKey::from_secret(secret.as_bytes()),<br>        &amp;Validation::new(Algorithm::HS512),<br>    ) {<br>        Ok(token) =&gt; Ok(token.claims),<br>        Err(err) =&gt; Err(err.kind().to_owned())<br>    }<br>}</pre><p>That’s it! We can now encode and decode JWTs. In some login route, we could now return the JWT to the user where the browser can store and retrieve it’s value from some private cookie or session storage.</p><p>Below is an example implementation of a login route that returns the JWT. <em>Note: This is a test application and it’s because of this that user passwords are stored un-hashed. Always hash user passwords when storing them anywhere.</em></p><pre>// Example implementation<br><br>pub fn login_user(user: Json&lt;LoginRequest&gt;) -&gt; Result&lt;String, NetworkResponse&gt; {<br>    use domain::schema::users;<br><br>    let user = user.into_inner();<br><br>    let user: User = match users::table.select(users::all_columns)<br>        .filter(users::user_name.eq(&amp;user.user_name))<br>        .filter(users::password.eq(&amp;user.password))<br>        .first::&lt;User&gt;(&amp;mut establish_connection()) {<br>            Ok(user) =&gt; user,<br>            Err(err) =&gt; match err {<br>                diesel::result::Error::NotFound =&gt; {<br>                    let response = Response { body: ResponseBody::Message(format!(&quot;Error - Wrong username or password for user {}&quot;, &amp;user.user_name))};<br>                    return Err(NotFound(serde_json::to_string(&amp;response).unwrap()));<br>                },<br>                _ =&gt; {<br>                    panic!(&quot;Database error - {}&quot;, err);<br>                } <br>            }<br>        };<br><br>    match create_jwt(user.id) {<br>        Ok(token) =&gt; Ok(token),<br>        Err(err) =&gt; Err(NetworkResponse::BadRequest(err.to_string())),<br>    } <br>}<br><br>#[post(&quot;/login&quot;, format = &quot;application/json&quot;, data = &quot;&lt;user&gt;&quot;)]<br>pub fn login_user_handler(user: Json&lt;LoginRequest&gt;) -&gt; Result&lt;String, NetworkResponse&gt; {<br>    let token = login_user(user)?;<br><br>    let response = Response { body: ResponseBody::AuthToken(token) };<br><br>    Ok(serde_json::to_string(&amp;response).unwrap())<br>}</pre><p>Now all we need to do is implement the request guard which validates the token on all routes we want integrity/validation checks on.</p><h3>Implementing the Request Guard</h3><p>Earlier when we created our models we defined a JWT struct, this is what we will use as our request guard type. To use this however, we first need to implement the FromRequest trait. Inside of this trait we’ll define the Error type as our NetworkResponse as well as an async function from_request(), which will take in a request and return an Outcome of either Self (JWT) or NetworkResponse.</p><p>The from_request() function will handle the validation of the JWT and return the claims if successful or a NetworkResponse otherwise.</p><pre>use rocket::serde::{Deserialize, Serialize};<br>use shared::response_models::NetworkResponse; // 👈 New!<br>use rocket::request::{Outcome, Request, FromRequest}; // 👈 New!<br>use rocket::http::Status; // 👈 New!<br><br>#[derive(Debug, Deserialize, Serialize)]<br>pub struct Claims {<br>    pub subject_id: i32,<br>    exp: usize<br>}<br><br>#[derive(Debug)]<br>pub struct JWT {<br>    pub claims: Claims<br>}<br><br>// 👇 New!<br>#[rocket::async_trait]<br>impl&lt;&#39;r&gt; FromRequest&lt;&#39;r&gt; for JWT {<br>    type Error = NetworkResponse;<br><br>    async fn from_request(req: &amp;&#39;r Request&lt;&#39;_&gt;) -&gt; Outcome&lt;Self, NetworkResponse&gt; {<br>        todo!()<br>    }<br>}</pre><p>While we’re at it, lets define a function to check if the token passed in is valid or not.</p><pre>#[rocket::async_trait]<br>impl&lt;&#39;r&gt; FromRequest&lt;&#39;r&gt; for JWT {<br>    type Error = NetworkResponse;<br><br>    async fn from_request(req: &amp;&#39;r Request&lt;&#39;_&gt;) -&gt; Outcome&lt;Self, NetworkResponse&gt; {<br>        // 👇 New!<br>        fn is_valid(key: &amp;str) -&gt; Result&lt;Claims, Error&gt; {<br>            Ok(decode_jwt(String::from(key))?)<br>        }<br>    <br>        todo!()<br>    }<br>}</pre><p>We now need some way of getting the token from the users request. Using the req variable passed in, we can get the headers from the request and search for the “Authorization” header using the get_one() method. This will return an Option we can then match against.</p><pre>#[derive(Debug)]<br>pub struct JWT {<br>    pub claims: Claims<br>}<br><br>#[rocket::async_trait]<br>impl&lt;&#39;r&gt; FromRequest&lt;&#39;r&gt; for JWT {<br>    type Error = NetworkResponse;<br><br>    async fn from_request(req: &amp;&#39;r Request&lt;&#39;_&gt;) -&gt; Outcome&lt;Self, NetworkResponse&gt; {<br>        fn is_valid(key: &amp;str) -&gt; Result&lt;Claims, Error&gt; {<br>            Ok(decode_jwt(String::from(key))?)<br>        }<br><br>        // 👇 New!<br>        match req.headers().get_one(&quot;authorization&quot;) {<br>            None =&gt; {<br>                // …<br>            },<br>            Some(key) =&gt; match is_valid(key) {<br>                Ok(claims) =&gt; {<br>                    // …<br>                },<br>                Err(err) =&gt; match &amp;err.kind() {<br>                    // …<br>                }<br>            },<br>        }<br>    }<br>}</pre><p>In pseudo-code, our match statement will look something like this:</p><pre>Check Authorization header:<br>  - None - 401 Unauthorized (&quot;Error validating JWT - No token provided&quot;)<br>  - Some(key) - validate key using is_valid()<br>    - Ok(claims) - return Outcome::Success(JWT {claims})<br>    - Err(err) - match against the err.kind()<br>      - ErrorKind::ExpiredSignature - 401 Unauthorized (&quot;Error validating JWT - Expired Token&quot;)<br>      - ErrorKind::InvalidToken - 401 Unauthorized (&quot;Error validating JWT - Invalid Token&quot;)<br>      - Anything else - 401 Unauthorized (&quot;Error validating JWT - {err}&quot;)</pre><p>This can be implemented like so:</p><pre>use rocket::serde::{Deserialize, Serialize};<br>use shared::response_models::{Response, ResponseBody, NetworkResponse}; // 👈 New!<br>use rocket::request::{Outcome, Request, FromRequest}; // 👈 New!<br>use rocket::http::Status;<br><br>#[derive(Debug)]<br>pub struct JWT {<br>    pub claims: Claims<br>}<br><br>#[rocket::async_trait]<br>impl&lt;&#39;r&gt; FromRequest&lt;&#39;r&gt; for JWT {<br>    type Error = NetworkResponse;<br><br>    async fn from_request(req: &amp;&#39;r Request&lt;&#39;_&gt;) -&gt; Outcome&lt;Self, NetworkResponse&gt; {<br>        fn is_valid(key: &amp;str) -&gt; Result&lt;Claims, Error&gt; {<br>            Ok(decode_jwt(String::from(key))?)<br>        }<br><br>        match req.headers().get_one(&quot;authorization&quot;) {<br>            None =&gt; {<br>                let response = Response { body: ResponseBody::Message(String::from(&quot;Error validating JWT token - No token provided&quot;))};<br>                Outcome::Failure((Status::Unauthorized, NetworkResponse::Unauthorized(serde_json::to_string(&amp;response).unwrap()))) <br>            },<br>            Some(key) =&gt; match is_valid(key) {<br>                Ok(claims) =&gt; Outcome::Success(JWT {claims}),<br>                Err(err) =&gt; match &amp;err.kind() {<br>                    jsonwebtoken::errors::ErrorKind::ExpiredSignature =&gt; {<br>                        let response = Response { body: ResponseBody::Message(format!(&quot;Error validating JWT token - Expired Token&quot;))};<br>                        Outcome::Failure((Status::Unauthorized, NetworkResponse::Unauthorized(serde_json::to_string(&amp;response).unwrap()))) <br>                    },<br>                    jsonwebtoken::errors::ErrorKind::InvalidToken =&gt; {<br>                        let response = Response { body: ResponseBody::Message(format!(&quot;Error validating JWT token - Invalid Token&quot;))};<br>                        Outcome::Failure((Status::Unauthorized, NetworkResponse::Unauthorized(serde_json::to_string(&amp;response).unwrap()))) <br>                    },<br>                    _ =&gt; {<br>                        let response = Response { body: ResponseBody::Message(format!(&quot;Error validating JWT token - {}&quot;, err))};<br>                        Outcome::Failure((Status::Unauthorized, NetworkResponse::Unauthorized(serde_json::to_string(&amp;response).unwrap()))) <br>                    }<br>                }<br>            },<br>        }<br>    }<br>}</pre><p>With all of this implemented, it’s now as simple as putting our request guard into the request handler. Here we have a route to publish a blog post. We pass the request guard in as a result and match against the key, giving us the encoded claims if successful or the corresponding NetworkResponse otherwise.</p><pre>#[get(&quot;/publish/&lt;post_id&gt;&quot;)]<br>                                          // 👇 New!<br>pub fn publish_post_handler(post_id: i32, key: Result&lt;JWT, NetworkResponse&gt;) -&gt; Result&lt;String, NetworkResponse&gt; {<br>    // 👇 New! <br>    let key = key?;<br><br>    let post = publish::publish_post(post_id, key)?; <br><br>    let response = Response { body: ResponseBody::Post(post) };<br><br>    Ok(serde_json::to_string(&amp;response).unwrap())<br>}</pre><p>With your requests integrity verified, you can now use the items encoded in the token, such as the users id, to verify their access to certain actions.<br>And that’s it! You’ve now implemented JWT authentication for your API routes.</p><h3>Further Improvements</h3><p>There are a few things that could be improved when looking at this projects implementation of JWTs.</p><p>Firstly, the JWT secret used to encode the token is currently static. It doesn’t change throughout the lifetime of the project. In a production application, the secret should be rotated regularly ensuring previous tokens are never reused.</p><h3>Conclusion</h3><p>Today we covered what JWTs, how to encode and decode them, and how to implement JWT authentication onto API routes using Request Guards in Rocket.rs.</p><p>All code along with my implementation of the front-end can be found here: <a href="https://github.com/BrookJeynes/blog-rust/tree/route-authentication">https://github.com/BrookJeynes/blog-rust</a></p><p>I hope you guys learnt something today, and give the process a go yourself! Make sure to star the <a href="https://github.com/BrookJeynes/blog-rust/">Github</a> repository and let me know what I should cover next or any feedback you have.</p><p>Thanks for reading, <br>- Brook ❤</p><h3>References</h3><h4>Crates:</h4><ul><li><a href="https://github.com/SergioBenitez/Rocket/tree/v0.5-rc">Rocket.rs</a></li><li><a href="https://github.com/serde-rs/serde">Serde-rs/serde</a></li><li><a href="https://github.com/serde-rs/json">Serde-rs/json</a></li><li><a href="https://github.com/Keats/jsonwebtoken">jsonwebtoken</a></li><li><a href="https://github.com/chronotope/chrono">Chrono</a></li></ul><h4>Other guides/docs followed:</h4><ul><li><a href="https://rocket.rs/v0.5-rc/guide/">Rocket.rs — Getting started</a></li><li>Fallas, A. U. (2020, October 29). JWT authentication in Rust. LogRocket Blog. Retrieved November 27, 2022, from <a href="https://blog.logrocket.com/jwt-authentication-in-rust/">https://blog.logrocket.com/jwt-authentication-in-rust/</a></li><li>SuperTokens Team. (2022, March 24). What is a JWT? Understanding JSON Web Tokens. SuperTokens. Retrieved November 27, 2022, from <a href="https://supertokens.com/blog/what-is-jwt">https://supertokens.com/blog/what-is-jwt</a></li><li>Okta. (n.d.). JSON Web Token Introduction — jwt.io. JWT.io. Retrieved November 27, 2022, from <a href="https://jwt.io/introduction/">https://jwt.io/introduction/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe7529792a70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an API in Rust with Rocket.rs and Diesel.rs (Clean Architecture)]]></title>
            <link>https://medium.com/@jeynesbrook/building-an-api-in-rust-with-rocket-rs-and-diesel-rs-clean-architecture-8f6092ee2606?source=rss-e2e7b4b3e940------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6092ee2606</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[crud]]></category>
            <dc:creator><![CDATA[Brook Jeynes]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 15:59:24 GMT</pubDate>
            <atom:updated>2022-11-26T05:28:20.510Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a simple blogging application using Rust + Rocket.rs + Diesel.rs following Clean Architecture.</h4><p>In this guide I’m going to walk you through the process of building a simple CRUD API from scratch in Rust using Rocket.rs. I will show you how to create migrations and access a PostgreSQL database using Diesel.rs and connect everything up to a React + Typescript front-end. When building the project we will follow Clean Architecture, although I won’t go into talking too much about what that is as it’s not the focus of this guide.</p><p>This guide assumes:</p><ul><li>You already have a <a href="https://www.postgresql.org/docs/current/tutorial-install.html">PostgreSQL database setup</a></li><li>You have the latest version of Rust (this guide uses v1.65.0)</li><li>You have a basic-to-decent understanding of Rust concepts and the language syntax</li></ul><p>Now that that’s sorted, let’s begin!</p><h3>Building the project architecture</h3><p>The first step is to setup the architecture of the application. Start by creating a overarching Rust project:</p><pre>cargo new rust-blog<br>cd rust-blog</pre><p>After this, delete the src folder as we won’t be needing it. The next thing we’re going to do is generate a new project for each layer in the Clean Architecture model. Our architecture will follow as such that the:</p><ul><li>API Layer will handle the API requests and act as our route handler.</li><li>Application layer will handle the logic behind the API requests.</li><li>Domain layer will hold our database models and schemas.</li><li>Infrastructure layer will hold our migrations and database connections.</li><li>Shared layer will hold any other models our project will need such as response structures.</li></ul><pre>cargo new api --lib<br>cargo new application --lib<br>cargo new domain --lib<br>cargo new infrastructure --lib<br>cargo new shared --lib<br></pre><p>By the end of this, our project should be looking something like this:</p><pre>.<br>├── Cargo.lock<br>├── Cargo.toml<br>├── api<br>│   ├── Cargo.toml<br>│   └── src<br>│       └── lib.rs<br>├── application<br>│   ├── Cargo.toml<br>│   └── src<br>│       └── lib.rs<br>├── domain<br>│   ├── Cargo.toml<br>│   └── src<br>│       └── lib.rs<br>├── infrastructure<br>│   ├── Cargo.toml<br>│   └── src<br>│       └── lib.rs<br>└── shared<br>    ├── Cargo.toml<br>    └── src<br>        └── lib.rs</pre><p>We’re now going to link all of these projects in the top-level Cargo.toml file. Delete everything inside the file and enter the following:</p><pre>[workspace]<br>members = [<br>  &quot;api&quot;,<br>  &quot;domain&quot;,<br>  &quot;infrastructure&quot;,<br>  &quot;application&quot;,<br>  &quot;shared&quot;,<br>]</pre><p>Nice! That’s the majority of our templating finished, now we can get into some actual fun.</p><h3>Migrations</h3><p>Since we’re using Diesel.rs as the database manager, we will need to install the <a href="https://lib.rs/crates/diesel_cli">CLI tool</a>. Diesel CLI has a few dependencies that need to be installed beforehand depending on what database you’re planning on using:</p><ul><li><a href="https://www.postgresql.org/docs/current/libpq.html">libpq</a> for PostgreSQL</li><li><a href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-implementations.html">libmysqlclient</a> for Mysql</li><li><a href="https://www.sqlite.org/index.html">libsqlite3</a> for SQlite</li></ul><p>For this project, we will be using PostgreSQL. This means we only need <a href="https://www.postgresql.org/docs/current/libpq.html">libpq</a> as a dependency. <em>Please refer to the docs for each dependency required to find out how to install it on your operating system.</em></p><p>With libpq installed, we can now run the following command to install Diesel CLI:</p><pre>cargo install diesel_cli --no-default-features --features postgres</pre><p>With that installed, let’s set up a connection string to our database. In the top-level project directory, run the following command with your connections details:</p><pre>echo DATABASE_URL=postgres://username:password@localhost/blog &gt; .env</pre><p>Now, we can use the Diesel CLI to do the heavy lifting for us. Navigate into the infrastructure folder and run the following command:</p><pre>diesel setup</pre><p>This will generate a few things:</p><ul><li>A migrations folder used to store all migrations</li><li>An empty migration we can use to manage our database schema.</li></ul><p>Using the Diesel CLI tool, we can create a new migration to handle the initial setup of our posts table.</p><pre>diesel migration generate create_posts</pre><p>Diesel CLI will generate a new migration consisting of a name similar to 2022–11–18–090125_create_posts. The first part is the date the migration was generated with a unique code followed by the migrations name. Inside this migration folder will be two files: up.sql, telling Diesel CLI what to apply in the migration, and down.sql, telling Diesel CLI how to revert a migration.</p><p>Now, let’s go ahead and write some SQL for the migrations.</p><pre>-- up.sql<br><br>CREATE TABLE posts (<br>  id SERIAL PRIMARY KEY,<br>  title VARCHAR NOT NULL,<br>  body TEXT NOT NULL,<br>  genre VARCHAR NOT NULL,<br>  published BOOLEAN NOT NULL DEFAULT false<br>)</pre><pre>-- down.sql<br><br>DROP TABLE posts</pre><p>Using the Diesel CLI, we can apply the new migration we just created.</p><pre>diesel migration run</pre><p><em>For more information on running migrations with Diesel.rs, visit the official getting started guide </em><a href="https://diesel.rs/guides/getting-started"><em>here</em></a><em>.</em></p><h3>Creating a connection</h3><p>With our first set of migrations finished and our project architecture laid out, let’s finally write some Rust code to connect our application to the database.</p><pre># infrastructure/Cargo.toml<br><br>[package]<br>name = &quot;infrastructure&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>diesel = { version = &quot;2.0.0&quot;, features = [&quot;postgres&quot;] }<br>dotenvy = &quot;0.15&quot;</pre><pre>// infrastructure/src/lib.rs<br><br>use diesel::pg::PgConnection;<br>use diesel::prelude::*;<br>use dotenvy::dotenv;<br>use std::env;<br><br>pub fn establish_connection() -&gt; PgConnection {<br>    dotenv().ok();<br><br>    let database_url = env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set.&quot;);<br><br>    PgConnection::establish(&amp;database_url).unwrap_or_else(|_| panic!(&quot;Error connecting to {}&quot;, database_url))<br>}</pre><p>With our connection made, we need to create some models for our database, namely Post and NewPost.</p><h3>Models and Schemas</h3><p>Start by navigating into domain and adding the following modules to lib.rs.</p><pre>// domain/src/lib.rs<br><br>pub mod models;<br>pub mod schema;</pre><p>We’ll use models to define the structs our database and code will use, while schema will be auto-generated by Diesel CLI. When we generated our migration, a schema.rs file was created in infrastructure. Simply move that to domain/src. If for some reason schema.rs wasn’t generated, you can run diesel print-schema in the terminal to view the schema.</p><pre># domain/Cargo.toml<br><br>[package]<br>name = &quot;domain&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>rocket = { version = &quot;0.5.0-rc.2&quot;, features = [&quot;json&quot;] }<br>diesel = { version = &quot;2.0.0&quot;, features = [&quot;postgres&quot;] }<br>serde = { version = &quot;1.0.147&quot;, features = [&quot;derive&quot;] }</pre><pre>// domain/src/models.rs<br><br>use crate::schema::posts;<br>use diesel::prelude::*;<br>use rocket::serde::{Deserialize, Serialize};<br>use std::cmp::{Ord, Eq, PartialOrd, PartialEq};<br><br>// Queryable will generate the code needed to load the struct from an SQL statement<br>#[derive(Queryable, Serialize, Ord, Eq, PartialEq, PartialOrd)]<br>pub struct Post {<br>    pub id: i32,<br>    pub title: String,<br>    pub body: String,<br>    pub genre: String,<br>    pub published: bool,<br>}<br><br>#[derive(Insertable, Deserialize)]<br>#[serde(crate = &quot;rocket::serde&quot;)]<br>#[diesel(table_name = posts)]<br>pub struct NewPost {<br>    pub title: String,<br>    pub body: String,<br>    pub genre: String,<br>}</pre><pre>// domain/src/schema.rs<br><br>// @generated automatically by Diesel CLI.<br><br>diesel::table! {<br>    posts (id) {<br>        id -&gt; Int4,<br>        title -&gt; Varchar,<br>        body -&gt; Text,<br>        genre -&gt; Varchar,<br>        published -&gt; Bool,<br>    }<br>}</pre><p>The code in schema.rs may vary slightly for you, but the concept still remains. This file will be updated whenever we run or revert a migration. It’s important to note that the order of fields in our Post struct and the posts table must match.</p><p>As well as defining database models, let’s create a model to structure how our API responses are going to be formatted. Navigate to shared/src and create a new file response_models.rs.</p><pre># shared/Cargo.toml<br><br>[package]<br>name = &quot;shared&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>domain = { path = &quot;../domain&quot; }<br><br>rocket = { version = &quot;0.5.0-rc.2&quot;, features = [&quot;json&quot;] }<br>serde = { version = &quot;1.0.147&quot;, features = [&quot;derive&quot;] }</pre><pre>// shared/src/lib.rs<br><br>pub mod response_models;</pre><pre>// shared/src/response_models.rs<br><br>use domain::models::Post;<br>use rocket::serde::Serialize;<br><br>#[derive(Serialize)]<br>pub enum ResponseBody {<br>    Message(String),<br>    Post(Post),<br>    Posts(Vec&lt;Post&gt;)<br>}<br><br>#[derive(Serialize)]<br>#[serde(crate = &quot;rocket::serde&quot;)]<br>pub struct Response {<br>    pub body: ResponseBody,<br>}</pre><p>The ResponseBody enum will be used to define what types of data can be returned from our API and the Response struct will define how the response will be structured.</p><h3>Setting up Rocket.rs</h3><p>Wow! That was a lot of setup just for our database, just so we’re all up-to-date, here’s what the project structure should look like currently:</p><pre>.<br>├── Cargo.lock<br>├── Cargo.toml<br>├── api<br>│   └── ...<br>├── application<br>│   └── ...<br>├── domain<br>│   ├── Cargo.toml<br>│   └── src<br>│       ├── lib.rs<br>│       └── models.rs<br>├── infrastructure<br>│   ├── Cargo.toml<br>│   ├── migrations<br>│   │   └── 2022–11–18–090125_create_posts<br>│   │       ├── up.sql<br>│   │       └── down.sql<br>│   └── src<br>│     ├── lib.rs<br>│     └── schema.rs<br>└── shared<br>    ├── Cargo.toml<br>    └── src<br>        ├── lib.rs<br>        └── response_models.rs</pre><p>With the bulk of our database setup done, let’s begin the setup of the API portion for the project.</p><p>Navigate to api and import the following dependencies:</p><pre># api/Cargo.toml<br><br>[package]<br>name = &quot;api&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>domain = { path = &quot;../domain&quot; }<br>application = { path = &quot;../application&quot; }<br>shared = { path = &quot;../shared&quot; }<br><br>rocket = { version = &quot;0.5.0-rc.2&quot;, features = [&quot;json&quot;] }<br>serde_json = &quot;1.0.88&quot;</pre><p>With our dependencies and references to other folders set, let’s create a bin folder to hold main.rs.</p><pre>.<br>└── api<br>    ├── Cargo.toml<br>    └── src<br>        ├── bin<br>        │   └── main.rs<br>        └── lib.rs</pre><p>main.rs is going to be the entry point of our API, this is where we will define the routes we plan to use. We’ll start by defining a single route at a time as we build the application up.</p><pre>// api/src/lib.rs<br><br>pub mod post_handler;</pre><pre>// api/src/bin/main.rs<br><br>#[macro_use] extern crate rocket;<br>use api::post_handler;<br><br>#[launch]<br>fn rocket() -&gt; _ {<br>    rocket::build()<br>        .mount(&quot;/api&quot;, routes![<br>            post_handler::list_posts_handler, <br>            post_handler::list_post_handler,<br>        ])<br>}</pre><p>We are going to use post_handler.rs to define the routes themselves. To avoid constant errors from our LSP, we’ll use the todo!() macro to let Rust know that these functions/routes are incomplete.</p><p>Create a new file called post_handler.rs in src and write the following template code:</p><pre>// api/src/post_handler.rs<br><br>use shared::response_models::{Response, ResponseBody};<br>use application::post::{read};<br>use domain::models::{Post};<br>use rocket::{get};<br>use rocket::response::status::{NotFound};<br>use rocket::serde::json::Json;<br><br>#[get(&quot;/&quot;)]<br>pub fn list_posts_handler() -&gt; String {<br>    todo!()<br>}<br><br>#[get(&quot;/post/&lt;post_id&gt;&quot;)]<br>pub fn list_post_handler(post_id: i32) -&gt; Result&lt;String, NotFound&lt;String&gt;&gt; {<br>    todo!()<br>}</pre><p>Here we define two requests:</p><ol><li><strong>GET /api/ </strong><em>(used to list all posts)</em></li><li><strong>GET /api/post/&lt;post_id&gt; </strong><em>(used to list a post by id)</em></li></ol><h3>Handling API logic</h3><p>With the request handlers templated, let’s write the logic required for the routes. Inside of application, create a new folder called post. This folder will contain a file for each of our routes logic.</p><pre># application/Cargo.toml<br><br>[package]<br>name = &quot;application&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>domain = { path = &quot;../domain&quot; }<br>infrastructure = { path = &quot;../infrastructure&quot; }<br>shared = { path = &quot;../shared&quot; }<br><br>diesel = { version = &quot;2.0.0&quot;, features = [&quot;postgres&quot;] }<br>serde_json = &quot;1.0.88&quot;<br>rocket = { version = &quot;0.5.0-rc.2&quot;, features = [&quot;json&quot;] }</pre><pre>// application/src/lib.rs<br><br>pub mod post;</pre><pre>// application/src/post/mod.rs<br><br>pub mod read;<br></pre><pre>// application/src/post/read.rs<br><br>use domain::models::Post;<br>use shared::response_models::{Response, ResponseBody};<br>use infrastructure::establish_connection;<br>use diesel::prelude::*;<br>use rocket::response::status::NotFound;<br><br>pub fn list_post(post_id: i32) -&gt; Result&lt;Post, NotFound&lt;String&gt;&gt; {<br>    use domain::schema::posts;<br><br>    match posts::table.find(post_id).first::&lt;Post&gt;(&amp;mut establish_connection()) {<br>        Ok(post) =&gt; Ok(post),<br>        Err(err) =&gt; match err {<br>            diesel::result::Error::NotFound =&gt; {<br>                let response = Response { body: ResponseBody::Message(format!(&quot;Error selecting post with id {} - {}&quot;, post_id, err))};<br>                return Err(NotFound(serde_json::to_string(&amp;response).unwrap()));<br>            },<br>            _ =&gt; {<br>                panic!(&quot;Database error - {}&quot;, err);<br>            }        <br>        }<br>    }<br>}<br><br>pub fn list_posts() -&gt; Vec&lt;Post&gt; {<br>    use domain::schema::posts;<br><br>    match posts::table.select(posts::all_columns).load::&lt;Post&gt;(&amp;mut establish_connection()) {<br>        Ok(mut posts) =&gt; {<br>            posts.sort();<br>            posts<br>        },<br>        Err(err) =&gt; match err {<br>            _ =&gt; {<br>                panic!(&quot;Database error - {}&quot;, err);<br>            }<br>        }<br>    }<br>}</pre><p>It’s important to note that when using Rocket.rs, the panic!() macro will return a 500 InternalServerError and <strong>not </strong>crash your program.</p><p>With the logic for our route written, let’s return back to our post handler to finish off our two GET routes.</p><pre>// api/src/post_handler.rs<br><br>// ...<br><br>#[get(&quot;/&quot;)]<br>pub fn list_posts_handler() -&gt; String {<br>    // 👇 New function body!<br>    let posts: Vec&lt;Post&gt; = read::list_posts();<br>    let response = Response { body: ResponseBody::Posts(posts) };<br><br>    serde_json::to_string(&amp;response).unwrap()<br>}<br><br>#[get(&quot;/post/&lt;post_id&gt;&quot;)]<br>pub fn list_post_handler(post_id: i32) -&gt; Result&lt;String, NotFound&lt;String&gt;&gt; {<br>    // 👇 New function body!<br>    let post = read::list_post(post_id)?;<br>    let response = Response { body: ResponseBody::Post(post) };<br><br>    Ok(serde_json::to_string(&amp;response).unwrap())<br>}</pre><p>Congratulations! You’ve just written your first two routes, hooked them up to a database, and have them both successfully reading content from it. Unfortunately, there isn’t much to read yet as there are no blog posts in our table.</p><p>Let’s change that.</p><h3>Creating Posts</h3><p>Like before, we’ll start by templating out the route handler. This will be a POST request that will accept JSON data.</p><pre>// api/src/post_handler.rs<br><br>use shared::response_models::{Response, ResponseBody};<br>use application::post::{create, read}; // 👈 New!<br>use domain::models::{Post, NewPost}; // 👈 New! <br>use rocket::{get, post}; // 👈 New! <br>use rocket::response::status::{NotFound, Created}; // 👈 New! <br>use rocket::serde::json::Json;<br><br>// ...<br><br>#[post(&quot;/new_post&quot;, format = &quot;application/json&quot;, data = &quot;&lt;post&gt;&quot;)]<br>pub fn create_post_handler(post: Json&lt;NewPost&gt;) -&gt; Created&lt;String&gt; {<br>    create::create_post(post)<br>}</pre><p>With that done, we can start the implementation of the create_post() function.</p><pre>// application/src/post/mod.rs<br><br>pub mod read;<br>pub mod create; // 👈 New!</pre><pre>// application/src/post/create.rs<br><br>use domain::models::{Post, NewPost};<br>use shared::response_models::{Response, ResponseBody};<br>use infrastructure::establish_connection;<br>use diesel::prelude::*;<br>use rocket::response::status::Created;<br>use rocket::serde::json::Json;<br><br>pub fn create_post(post: Json&lt;NewPost&gt;) -&gt; Created&lt;String&gt; {<br>    use domain::schema::posts;<br><br>    let post = post.into_inner();<br><br>    match diesel::insert_into(posts::table).values(&amp;post).get_result::&lt;Post&gt;(&amp;mut establish_connection()) {<br>        Ok(post) =&gt; {<br>            let response = Response { body: ResponseBody::Post(post) };<br>            Created::new(&quot;&quot;).tagged_body(serde_json::to_string(&amp;response).unwrap())<br>        },<br>        Err(err) =&gt; match err {<br>            _ =&gt; {<br>                panic!(&quot;Database error - {}&quot;, err);<br>            }<br>        }<br>    }<br>}</pre><p>The final thing we need to do is register the route so it can be used.</p><pre>// api/src/bin/main.rs<br><br>#[macro_use] extern crate rocket;<br>use api::post_handler;<br><br>#[launch]<br>fn rocket() -&gt; _ {<br>    rocket::build()<br>        .mount(&quot;/api&quot;, routes![<br>            post_handler::list_posts_handler, <br>            post_handler::list_post_handler,<br>            post_handler::create_post_handler, // 👈 New!<br>        ])<br>}</pre><p>Now that’s done, lets finally test the API with some data!</p><h3>CR__ Testing</h3><p>With two of our four letters implemented, let’s give it a small test run. Navigate back to the root directory and run the application.</p><pre>cargo run</pre><p>After the project has built, open up your favourite API testing tool and check the routes work as expected.</p><figure><img alt="API client showing valid GET request" src="https://cdn-images-1.medium.com/max/1024/1*n0C_q0rDGRYBYu7ozJeEvQ.png" /><figcaption><strong>Figure:</strong> GET / working as intended</figcaption></figure><figure><img alt="API client showing valid POST request" src="https://cdn-images-1.medium.com/max/1024/1*MZd6qTwVv7XDA_UmftPYwg.png" /><figcaption><strong>Figure:</strong> POST /new_post working as intended</figcaption></figure><h3>The final two letters</h3><p>The final two operations we need is updating and deleting. We’ll implement updating via “publishing” a post and deleting by, well… deleting a post.</p><p>Like with the past two letters, let’s create our handlers.</p><pre>// api/src/post_handler.rs<br><br>use shared::response_models::{Response, ResponseBody};<br>use application::post::{create, read, publish, delete}; // 👈 New!<br>use domain::models::{Post, NewPost};<br>use rocket::{get, post};<br>use rocket::response::status::{NotFound, Created};<br>use rocket::serde::json::Json;<br><br>// ...<br><br>#[get(&quot;/publish/&lt;post_id&gt;&quot;)]<br>pub fn publish_post_handler(post_id: i32) -&gt; Result&lt;String, NotFound&lt;String&gt;&gt; {<br>    let post = publish::publish_post(post_id)?; <br>    let response = Response { body: ResponseBody::Post(post) };<br><br>    Ok(serde_json::to_string(&amp;response).unwrap())<br>}<br><br>#[get(&quot;/delete/&lt;post_id&gt;&quot;)]<br>pub fn delete_post_handler(post_id: i32) -&gt; Result&lt;String, NotFound&lt;String&gt;&gt; {<br>    let posts = delete::delete_post(post_id)?;<br>    let response = Response { body: ResponseBody::Posts(posts) };<br><br>    Ok(serde_json::to_string(&amp;response).unwrap())<br>}</pre><p>And implement the logic for them.</p><pre>// application/src/post/mod.rs<br><br>pub mod create;<br>pub mod read;<br>pub mod publish; // 👈 New!<br>pub mod delete; // 👈 New!</pre><pre>// application/src/post/publish.rs<br><br>use domain::models::Post;<br>use shared::response_models::{Response, ResponseBody};<br>use infrastructure::establish_connection;<br>use rocket::response::status::NotFound;<br>use diesel::prelude::*;<br><br>pub fn publish_post(post_id: i32) -&gt; Result&lt;Post, NotFound&lt;String&gt;&gt; {<br>    use domain::schema::posts::dsl::*;<br><br>    match diesel::update(posts.find(post_id)).set(published.eq(true)).get_result::&lt;Post&gt;(&amp;mut establish_connection()) {<br>        Ok(post) =&gt; Ok(post),<br>        Err(err) =&gt; match err {<br>            diesel::result::Error::NotFound =&gt; {<br>                let response = Response { body: ResponseBody::Message(format!(&quot;Error publishing post with id {} - {}&quot;, post_id, err))};<br>                return Err(NotFound(serde_json::to_string(&amp;response).unwrap()));<br>            },<br>            _ =&gt; {<br>                panic!(&quot;Database error - {}&quot;, err);<br>            }        <br>        }<br>    }<br>}</pre><pre>// application/src/post/delete.rs<br><br>use shared::response_models::{Response, ResponseBody};<br>use infrastructure::establish_connection;<br>use diesel::prelude::*;<br>use rocket::response::status::NotFound;<br>use domain::models::Post;<br><br>pub fn delete_post(post_id: i32) -&gt; Result&lt;Vec&lt;Post&gt;, NotFound&lt;String&gt;&gt; {<br>    use domain::schema::posts::dsl::*;<br>    use domain::schema::posts;<br><br>    let response: Response;<br><br>    let num_deleted = match diesel::delete(posts.filter(id.eq(post_id))).execute(&amp;mut establish_connection()) {<br>        Ok(count) =&gt; count,<br>        Err(err) =&gt; match err {<br>            diesel::result::Error::NotFound =&gt; {<br>                let response = Response { body: ResponseBody::Message(format!(&quot;Error deleting post with id {} - {}&quot;, post_id, err))};<br>                return Err(NotFound(serde_json::to_string(&amp;response).unwrap()));<br>            },<br>            _ =&gt; {<br>                panic!(&quot;Database error - {}&quot;, err);<br>            }        <br>        }<br>    };<br><br>    if num_deleted &gt; 0 {<br>        match posts::table.select(posts::all_columns).load::&lt;Post&gt;(&amp;mut establish_connection()) {<br>            Ok(mut posts_) =&gt; {<br>                posts_.sort();<br>                Ok(posts_)<br>            },<br>            Err(err) =&gt; match err {<br>                _ =&gt; {<br>                    panic!(&quot;Database error - {}&quot;, err);<br>                }<br>            }<br>        }<br>    } else {<br>        response = Response { body: ResponseBody::Message(format!(&quot;Error - no post with id {}&quot;, post_id))};<br>        Err(NotFound(serde_json::to_string(&amp;response).unwrap()))<br>    } <br>}</pre><p>And finally, register our new routes.</p><pre>// api/src/bin/main.rs<br><br>#[macro_use] extern crate rocket;<br>use api::post_handler;<br><br>#[launch]<br>fn rocket() -&gt; _ {<br>    rocket::build()<br>        .mount(&quot;/api&quot;, routes![<br>            post_handler::list_posts_handler, <br>            post_handler::list_post_handler,<br>            post_handler::create_post_handler,<br>            post_handler::publish_post_handler, // 👈 New!<br>            post_handler::delete_post_handler, // 👈 New!<br>        ])<br>}</pre><p>And that’s it! You now have a fully functioning API written in Rocket.rs, which connects to a PostgreSQL database via Diesel.rs. Not only that, but the application is structured following Clean Architecture.</p><p>Your project should now look close to the following:</p><pre>.<br>├── Cargo.lock<br>├── Cargo.toml<br>├── api<br>│   ├── Cargo.toml<br>│   └── src<br>│       ├── bin<br>│       │   └── main.rs<br>│       ├── lib.rs<br>│       └── post_handler.rs<br>├── application<br>│   ├── Cargo.toml<br>│   └── src<br>│       ├── lib.rs<br>│       └── post<br>│           ├── create.rs<br>│           ├── delete.rs<br>│           ├── mod.rs<br>│           ├── publish.rs<br>│           └── read.rs<br>├── domain<br>│   ├── Cargo.toml<br>│   └── src<br>│       ├── lib.rs<br>│       ├── models.rs<br>│       └── schema.rs<br>├── infrastructure<br>│   ├── Cargo.toml<br>│   ├── migrations<br>│   │   └── 2022–11–18–090125_create_posts<br>│   │       ├── up.sql<br>│   │       └── down.sql<br>│   └── src<br>│       └── lib.rs<br>└── shared<br>    ├── Cargo.toml<br>    └── src<br>        ├── lib.rs<br>        └── response_models.rs</pre><h3>Further Improvements</h3><p>There are a few things that could be improved when looking at the application as a whole.</p><p>Firstly, whenever we want to use the database we open up a new connection. This can become costly and resource intensive when on a larger scale. One way this could be fixed is by using a connection pool, Rocket.rs includes built in support for <a href="https://github.com/sfackler/r2d2">R2D2</a>, a connection pool handler for Rust.</p><p>Secondly, Diesel.rs is not asynchronous — this isn’t too much of an issue on this scale. However, it can become a bigger problem for larger applications. There is, at the time writing, <a href="https://github.com/diesel-rs/diesel/issues/399#issuecomment-357361992">no asynchronous implementation</a> from the official team behind Diesel.rs. As an alternative, an <a href="https://lib.rs/crates/async-diesel">external crate</a> is available to provide this functionality.</p><p>Finally, a front-end UI could be created alongside the Rust API. Inside the root directory you would create a new project called web_ui using your front-end language of choice. All you’d then need to do is run both projects separately, calling the Rust API from your front-end client. Here’s my implementation of a front-end for some inspiration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3UckHdqewMm-Pi3z6uxVA.png" /><figcaption><strong>Figure:</strong> My implementation of the front-end UI</figcaption></figure><h3>Conclusion</h3><p>Phew! What a journey. Not only have we learnt how to use Rocket.rs and Diesel.rs but we’ve learnt how to use them together to create a blogging API in Rust. Along with that, we’ve built a front-end for it and packaged it all together in a single project file following Clean Architecture.</p><p>All code along with my implementation of the front-end can be found here: <a href="https://github.com/BrookJeynes/blog-rust">https://github.com/BrookJeynes/blog-rust</a></p><p>I hope you guys learnt a lot today, and give the process a go yourself and create something new! Make sure to star the <a href="https://github.com/BrookJeynes/blog-rust">Github repository</a> and let me know what I should cover next or any feedback you have.</p><p>Thanks for reading, <br>- Brook ❤</p><h3>References</h3><h4>Crates:</h4><ul><li><a href="https://github.com/diesel-rs/diesel">Diesel.rs</a></li><li><a href="https://github.com/SergioBenitez/Rocket/tree/v0.5-rc">Rocket.rs</a></li><li><a href="https://github.com/serde-rs/serde">Serde-rs/serde</a></li><li><a href="https://github.com/serde-rs/json">Serde-rs/json</a></li></ul><h4>Other guides/docs followed:</h4><ul><li><a href="https://diesel.rs/guides/getting-started">Diesel.rs — Getting started</a></li><li><a href="https://rocket.rs/v0.5-rc/guide/">Rocket.rs — Getting started</a></li><li><a href="https://medium.com/swlh/a-simple-crud-on-rust-with-rocket-rs-and-diesel-rs-e885672cb23d">A Simple Crud on Rust (With Rocket.rs and Diesel.rs)</a> (Uses deprecated packages for current rust version (v1.65.0) 🙁)</li><li>Too many <a href="http://stackoverflow.com/">Stackoverflow</a> posts to mention</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6092ee2606" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>