<?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"><channel><title><![CDATA[Ivan's blog]]></title><description><![CDATA[Ivan's blog]]></description><link>https://ichebykin.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 17 Nov 2026 16:50:50 GMT</lastBuildDate><atom:link href="https://ichebykin.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Writing Mario in sed]]></title><description><![CDATA[Have you ever wondered if you can write games using sed? No? Anyone? Weird. Anyway, here is how it works, and this is the link to the repo:]]></description><link>https://ichebykin.hashnode.dev/writing-mario-in-sed</link><guid isPermaLink="true">https://ichebykin.hashnode.dev/writing-mario-in-sed</guid><category><![CDATA[sed]]></category><category><![CDATA[challenge]]></category><category><![CDATA[extreme programming]]></category><category><![CDATA[Regex]]></category><category><![CDATA[fun]]></category><dc:creator><![CDATA[Ivan Chebykin]]></dc:creator><pubDate>Tue, 08 Aug 2023 01:06:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1691456723484/099d6138-2b1d-4f79-a230-2ea22dbbe202.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWN2NmFsZzM1emo0ajVwa25hY2FtNXI1Y2sxMDNxYzBxdXRlbTZ0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/v5hpawf0kYERgHR9Fg/giphy.gif">https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWN2NmFsZzM1emo0ajVwa25hY2FtNXI1Y2sxMDNxYzBxdXRlbTZ0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/v5hpawf0kYERgHR9Fg/giphy.gif</a></div>
<p> </p>
<p>Have you ever wondered if you can write games using sed? No? Anyone? Weird.</p>
<p>Anyway, here is how it works, and this is the link to the repo: <a target="_blank" href="https://github.com/chebykinn/sedmario">https://github.com/chebykinn/sedmario</a></p>
<h2 id="heading-what-is-sed">What is sed</h2>
<p>Canonically sed is a tool that is used to transform text line by line using regular expressions. Here's an example of some sensible use of it:</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">echo</span> text | sed <span class="hljs-string">'s@\(.*\)@&lt;bold&gt;\1&lt;/bold&gt;@g'</span>                                                                                                                                                                                                    ~
&lt;bold&gt;text&lt;/bold&gt;
</code></pre>
<p>The problem is that this tool can do more than just replace text:</p>
<ul>
<li><p>It has labels and a goto command</p>
</li>
<li><p>There are two buffers for storing data - pattern space and hold space, you can use the second one for storing data in between parsing lines using a special command.</p>
</li>
<li><p>As noted in Wikipedia, the sed language is Turing-complete.</p>
</li>
</ul>
<h2 id="heading-implementation">Implementation</h2>
<h3 id="heading-game-scene">Game scene</h3>
<p>Every game should have a cycle that processes all the logic, movement, and rendering. In sed, everything builds around an input line, and if the user doesn't pass file or pipe data, it will use stdin, so every time you type something and press enter it'll start processing the script.</p>
<p>What do we need in this game cycle?</p>
<ul>
<li><p>Level rendering</p>
</li>
<li><p>Processing of input for movement</p>
</li>
<li><p>Enemies movement</p>
</li>
</ul>
<p>The first part of the script is used to print the level:</p>
<pre><code class="lang-bash">:<span class="hljs-built_in">print</span>
g
 /^$/ { s/.*/\
+--------------------------------+\
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\
IIIIIIIIIIIIx00IIIIIIIIIIIIIIIIIII\
|FFFFFFFFFFFFFFFFFFFFFFXFFFFFFFFFFFFFFFFFFFFFFFFF1\
|FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2\
|FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF3\
|FFFFFFFFFFFFFFFFXFFFSXSXSFFFFFFFFFFFFFFFFFFFTFFF4\
|FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFTFFFFFFTFFF5\
|FFFFPFFFFFFFFFFFFFFFFFFFFFMFTFFFFFFFFTFFFMFFTFFF6\
|SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS7\
|SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS8\
+--------------------------------+\
 /
 }
</code></pre>
<p>Here I replaced the input line buffer with some characters, but this doesn't look really colorful yet because in this buffer I store level map data as characters:</p>
<ul>
<li><p>P - is player</p>
</li>
<li><p>F - air block</p>
</li>
<li><p>S - solid block</p>
</li>
<li><p>T - pipe</p>
</li>
<li><p>M or G - Goomba moving left or right respectively</p>
</li>
<li><p>K or O - Koopa</p>
</li>
</ul>
<p>This allows me to write logic based on the character type. Using mentioned labels and the goto command, it's easy to build some logic to process input:</p>
<pre><code class="lang-bash">/^a/b left
/^d/b right
/^ /b up
/^s/b down
</code></pre>
<p>And then move the player the only way you can do anything in sed - by replacing text:</p>
<pre><code class="lang-bash">:left
 g
<span class="hljs-comment"># replace player block with space block</span>
<span class="hljs-comment"># collision detection is automatic</span>
 s/FP/PF/
 b end
:right
 g
 <span class="hljs-comment"># Prevent screen scrolling at the end of level</span>
 /end/b end
 s/PF/FP/
</code></pre>
<h3 id="heading-rendering-the-level">Rendering the level</h3>
<p>Okay, so the previous code draws only the first screen, but the game needs to draw new parts of the level as the player goes further to the right. This is done with two tricks:</p>
<ol>
<li><p>When the player moves to the right I need to shift the screen to the left, this is done by appending <code>#</code> to every line.</p>
</li>
<li><p>I used the last line for storing metadata - when the player jumps it stores the jump states as 1u, 2u, 3u. Same with the next level segments, once the number of <code>#</code> goes to 16 (I just used that for the round number, and to have fewer segments), I replace those #s with the segment based on zone number in metadata (z1, z2, z3).</p>
</li>
</ol>
<p>Here's how it looks under the hood:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExYndzeDRlZmwwZWxobGR6ZjZ0NGZmbG9jbW5uMDZnYjNjbjRvOWdhcyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/mJx8be140VXgqANf5I/giphy.gif">https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExYndzeDRlZmwwZWxobGR6ZjZ0NGZmbG9jbW5uMDZnYjNjbjRvOWdhcyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/mJx8be140VXgqANf5I/giphy.gif</a></div>
<p> </p>
<p>The header is not part of the level data, it's just two constant rows of characters with the score counter.</p>
<h3 id="heading-coloring-the-output">Coloring the output</h3>
<p>After user input is processed and enemies are moved we can use the second, hold buffer to store the level data. Then it's easy to color output, I just need to replace all characters with ANSI escape codes for colors.</p>
<h3 id="heading-running-the-game-loop">Running the game loop</h3>
<p>To make the game actually playable I needed to write a simple wrapper shell script that sends enter every second, thus driving the game loop forward.</p>
<p>That's it! There are of course some improvements that are needed to be made, for example instead of sending enter every time it is better to come up with a special sync character to maintain a constant speed when you hold the move buttons, but that's for another time. It was a fun challenge at the university and it was nice to remember what I wrote back then :).</p>
<p>Now that people know how it works, I wonder if someone can continue this challenge, for instance, write Doom or The Legend of Zelda...</p>
]]></content:encoded></item><item><title><![CDATA[Beyond API Service: Adding a React Frontend]]></title><description><![CDATA[In the previous tutorials, we were only focused on the backend side of the app, but calling API from Postman or curl is no fun for a to-do app, so let's…]]></description><link>https://ichebykin.hashnode.dev/beyond-api-service-adding-a-react-frontend</link><guid isPermaLink="true">https://ichebykin.hashnode.dev/beyond-api-service-adding-a-react-frontend</guid><category><![CDATA[Go Language]]></category><category><![CDATA[React]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[tools]]></category><category><![CDATA[infrastructure]]></category><dc:creator><![CDATA[Ivan Chebykin]]></dc:creator><pubDate>Thu, 06 Apr 2023 13:30:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680738821048/5f6d884c-170e-4ff4-94d2-f9545161c7f4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-previously">Previously</h1>
<p>In the previous tutorials, we were only focused on the backend side of the app, but calling API from Postman or curl is no fun for a to-do app, so let's move on to the frontend.</p>
<p>Granted, the app we'll build in this article is pretty basic, both design and functionality-wise, but this would still be a good starter from which you can later expand on your own.</p>
<h1 id="heading-prerequisites">Prerequisites</h1>
<p>Assuming that you already have everything installed from <a target="_blank" href="https://ichebykin.hashnode.dev/building-api-service-with-mify-part-2-adding-postgres#heading-prerequisites">the previous article</a> for the backend, as we need to update and run it as well, here's what's needed for frontend development:</p>
<ul>
<li><p>Node JS &gt;= 18.12.1, Yarn</p>
</li>
<li><p>Get Mify from our GitHub: <a target="_blank" href="https://github.com/mify-io/mify">https://github.com/mify-io/mify</a></p>
</li>
</ul>
<p>Obligatory link for the complete example: <a target="_blank" href="https://github.com/mify-io/todo-app-example/tree/03-react-frontend">https://github.com/mify-io/todo-app-example/tree/03-react-frontend</a></p>
<h1 id="heading-plan">Plan</h1>
<p>What should a sensible to-do app have? Let's write a to-do list for that:</p>
<ol>
<li><p>List of notes</p>
</li>
<li><p>Form to add a new note</p>
</li>
<li><p>Button to mark note as completed</p>
</li>
<li><p>Edit and delete note buttons</p>
</li>
</ol>
<p>In the end, we want to get something like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680569585481/69db144f-b666-4124-a599-694b282bab00.png" alt class="image--center mx-auto" /></p>
<p>Looking at our backend from the previous tutorials, we have an API with the basic handlers for creating, updating, and retrieving to-do notes. Huh, something is missing. Oh, right, we need to be able to list notes.</p>
<h1 id="heading-adding-list-method-to-backend">Adding List method to backend</h1>
<p>Let's start with that, after our backend is ready then we can move to the frontend side. It's pretty easy to add it, first we need to update the OpenAPI schema at <code>schemas/todo-backend/api/api.yaml</code>:</p>
<pre><code class="lang-yaml">  <span class="hljs-string">/todos:</span>
    <span class="hljs-attr">post:</span>
      <span class="hljs-string">...</span>
    <span class="hljs-attr">get:</span>
      <span class="hljs-attr">summary:</span> <span class="hljs-string">Get</span> <span class="hljs-string">list</span> <span class="hljs-string">of</span> <span class="hljs-string">todo</span> <span class="hljs-string">notes</span>
      <span class="hljs-attr">responses:</span>
        <span class="hljs-attr">'200':</span>
          <span class="hljs-attr">description:</span> <span class="hljs-string">OK</span>
          <span class="hljs-attr">content:</span>
            <span class="hljs-attr">application/json:</span>
              <span class="hljs-attr">schema:</span>
                <span class="hljs-string">$ref:</span> <span class="hljs-string">'#/components/schemas/TodoNoteList'</span>
        <span class="hljs-attr">'500':</span>
          <span class="hljs-attr">description:</span> <span class="hljs-string">Unknown</span> <span class="hljs-string">error</span>
          <span class="hljs-attr">content:</span>
            <span class="hljs-attr">application/json:</span>
              <span class="hljs-attr">schema:</span>
                <span class="hljs-string">$ref:</span> <span class="hljs-string">'#/components/schemas/Error'</span>
<span class="hljs-attr">components:</span>
  <span class="hljs-attr">schemas:</span>
    <span class="hljs-string">...</span>
    <span class="hljs-attr">TodoNoteList:</span>
      <span class="hljs-attr">type:</span> <span class="hljs-string">array</span>
      <span class="hljs-attr">items:</span>
        <span class="hljs-string">$ref:</span> <span class="hljs-string">'#/components/schemas/TodoNote'</span>
</code></pre>
<p>Then add a new SQL query to select all notes at <code>go-services/sql-queries/todo_backend/queries.sql</code>:</p>
<pre><code class="lang-sql">...
<span class="hljs-comment">-- name: SelectTodoNotes :many</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> todos <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> created_at <span class="hljs-keyword">DESC</span>;
...
</code></pre>
<p>After that, we need to regenerate the code, so that the handler and query functions would appear:</p>
<pre><code class="lang-bash">$ mify generate
</code></pre>
<h3 id="heading-wiring-stuff-together">Wiring stuff together</h3>
<p>Alright, now we need to wire the database method to the new API handler, so we need to update multiple layers: TodoDBStorage, and TodoApplication, and then implement the handler.</p>
<p>First, update the TodoStorage interface to add the new list method in file <code>go-services/internal/todo-backend/domain/todo.go</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> TodoStorage <span class="hljs-keyword">interface</span> {
    InsertTodoNote(ctx *core.MifyRequestContext, todoNote TodoNote) (TodoNote, error)
    UpdateTodoNote(ctx *core.MifyRequestContext, todoNote TodoNote) (TodoNote, error)
    SelectTodoNote(ctx *core.MifyRequestContext, id <span class="hljs-keyword">int64</span>) (TodoNote, error)
    SelectTodoNotes(ctx *core.MifyRequestContext) ([]TodoNote, error)
    DeleteTodoNote(ctx *core.MifyRequestContext, id <span class="hljs-keyword">int64</span>) error
}
</code></pre>
<p>After that, go to the <code>go-services/internal/todo-backend/storage/todo_db.go</code> and add implementation:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">SelectTodoNotes</span><span class="hljs-params">(ctx *core.MifyRequestContext)</span> <span class="hljs-params">([]domain.TodoNote, error)</span></span> {
    res, err := s.querier.SelectTodoNotes(ctx)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &amp;&amp; errors.Is(err, pgx.ErrNoRows) {
        <span class="hljs-keyword">return</span> []domain.TodoNote{}, <span class="hljs-literal">nil</span>
    }
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> []domain.TodoNote{}, err
    }
    outList := <span class="hljs-built_in">make</span>([]domain.TodoNote, <span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(res))
    <span class="hljs-keyword">for</span> _, dbNote := <span class="hljs-keyword">range</span> res {
        outList = <span class="hljs-built_in">append</span>(outList, makeDomainTodoNode(dbNote))
    }
    <span class="hljs-keyword">return</span> outList, <span class="hljs-literal">nil</span>
}
</code></pre>
<p>And in Application layer we just need to wrap the call to this method:</p>
<p><code>go-services/internal/todo-backend/application/todo.go</code></p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoService)</span> <span class="hljs-title">ListTodos</span><span class="hljs-params">(ctx *core.MifyRequestContext)</span> <span class="hljs-params">([]domain.TodoNote, error)</span></span> {
    <span class="hljs-keyword">return</span> s.storage.SelectTodoNotes(ctx)
}
</code></pre>
<p>Just a reminder, this Application layer is pretty thin in this tutorial, but in a real application you would have logic beyond the storage layer, so it's better to add it from the beginning.</p>
<p>Finally, moving to the handler. Right now Mify doesn't automatically add TodosGet method boilerplate, but we're planning to add that in the future, so for the time being we need to get signature of the GET handler from <code>openapi.TodosApiServicer</code> interface and implement it:</p>
<p><code>go-services/internal/todo-backend/handlers/todos/service.go</code></p>
<pre><code class="lang-go"><span class="hljs-comment">// TodosGet - List todo notes</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodosApiService)</span> <span class="hljs-title">TodosGet</span><span class="hljs-params">(ctx *core.MifyRequestContext)</span> <span class="hljs-params">(openapi.ServiceResponse, error)</span></span> {
    todoSvc := apputil.GetServiceExtra(ctx.ServiceContext()).TodoService

    notes, err := todoSvc.ListTodos(ctx)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> openapi.Response(http.StatusInternalServerError, openapi.Error{
            Code:    strconv.Itoa(http.StatusInternalServerError),
            Message: <span class="hljs-string">"Failed to list todo notes"</span>,
        }), err
    }

    responseList := <span class="hljs-built_in">make</span>([]openapi.TodoNote, <span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(notes))
    <span class="hljs-keyword">for</span> _, note := <span class="hljs-keyword">range</span> notes {
        responseList = <span class="hljs-built_in">append</span>(responseList, handlers.MakeAPITodoNote(note))
    }

    <span class="hljs-keyword">return</span> openapi.Response(http.StatusOK, responseList), <span class="hljs-literal">nil</span>
}
</code></pre>
<h3 id="heading-running-and-testing">Running and testing</h3>
<p>Alright, now we're ready to run and test the backend, make sure that Postgres is <a target="_blank" href="https://ichebykin.hashnode.dev/building-api-service-with-mify-part-2-adding-postgres#heading-running-postgres-in-docker">running</a>, and start the service via <code>go run ./cmd/todo-backend</code>.</p>
<p>Using curl and port from the service startup logs we can test the new handler:</p>
<pre><code class="lang-bash">$ curl -s <span class="hljs-string">'http://localhost:38437/todos'</span> | jq .                                                                                                                                                                           
[
  {
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"second description"</span>,
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"second"</span>,
    <span class="hljs-string">"created_at"</span>: <span class="hljs-string">"2023-04-02 23:48:09"</span>,
    <span class="hljs-string">"id"</span>: 7,
    <span class="hljs-string">"updated_at"</span>: <span class="hljs-string">"2023-04-03 02:31:14"</span>
  },
  {
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"first desc"</span>,
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"first"</span>,
    <span class="hljs-string">"created_at"</span>: <span class="hljs-string">"2023-04-02 23:48:01"</span>,
    <span class="hljs-string">"id"</span>: 6,
    <span class="hljs-string">"updated_at"</span>: <span class="hljs-string">"2023-04-03 01:22:50"</span>
  }
]
</code></pre>
<h1 id="heading-building-frontend">Building Frontend</h1>
<p>Now after we have a prepared backend with the complete API, let's just move to the frontend already! Adding it to the Mify Workspace shouldn't be a surprise at this point, it's the simple command:</p>
<pre><code class="lang-bash">$ mify add frontend --template react-ts todo-app
</code></pre>
<p>Although there is an extra one, we need to wire it to the backend:</p>
<pre><code class="lang-bash">$ mify add client todo-app --to todo-backend
</code></pre>
<p>Now the frontend is ready for implementation, last command will add a client with all generated classes and methods, so from the frontend perspective calling <code>todo-backend</code> would be no different from a local call. Here's the structure that was generated by Mify:</p>
<pre><code class="lang-bash">js-services
├── package.json
├── todo-app
│   ├── Dockerfile
│   ├── package.json
│   ├── public
│   │   ├── index.html
│   │   ├── manifest.json
│   │   └── robots.txt
│   ├── src
│   │   ├── app
│   │   │   ├── hooks.ts
│   │   │   └── store.ts
│   │   ├── App.css
│   │   ├── App.test.tsx
│   │   ├── App.tsx
│   |   ├── generated
│   │   │   ├── api
│   │   │   │   └── clients
│   │   │   │       └── todo-backend
│   │   │   │           ├── ApiClient.js
│   │   │   │           ├── handlers
│   │   │   │           │   └── Api.js
│   │   │   │           ├── index.js
│   │   │   │           ├── models
│   │   │   │           │   ├── Error.js
│   │   │   │           │   ├── TodoNoteAllOf.js
│   │   │   │           │   ├── TodoNoteCreateRequest.js
│   │   │   │           │   ├── TodoNote.js
│   │   │   │           │   ├── TodoNoteUpdateRequestAllOf.js
│   │   │   │           │   └── TodoNoteUpdateRequest.js
│   │   │   │           └── package.json
│   │   └── core
│   │       ├── clients.js
│   │       ├── context.js
│   │       └── state.ts
│   │   ├── index.css
│   │   ├── index.tsx
│   │   ├── react-app-env.d.ts
│   │   ├── reportWebVitals.ts
│   │   └── setupTests.ts
│   └── tsconfig.json
└── yarn.lock
</code></pre>
<p>Essentially that's a simple React+Redux template with additional generated code for calling backend service.</p>
<h3 id="heading-libraries">Libraries</h3>
<p>Before starting to write code, let's install some libraries that would help to write less of it:</p>
<ul>
<li><p><code>yarn add styled-components</code> - This allows defining styles as components in React instead of CSS, leveraging the type system in Typescript.</p>
</li>
<li><p><code>yarn add react-hook-form</code> - A quite elegant library for wiring forms without hassle.</p>
</li>
<li><p><code>yarn add moment</code> - Just format the date to display something like "a few hours ago" instead of the dry ISO format.</p>
</li>
</ul>
<h2 id="heading-creating-components">Creating components</h2>
<p>Before even adding the logic to call backend let's first create a mockup UI. This way you can freely experiment with design before having to debug some interaction issues.</p>
<p>To start the frontend app first install all the missing libraries with <code>yarn install</code> and then run <code>yarn start</code> and the app should be available at http://localhost:3000. The default template should be an almost blank page suggesting you to edit <code>src/App.tsx</code>.</p>
<p>Let's start with the CSS, in this tutorial we wouldn't use separate CSS files, instead we'll define styled blocks using the <code>styled-components</code> library.</p>
<p>We would still need to define global styles like the font size and family, CSS reset to remove all unnecessary margins, so let's put it in <code>js-services/todo-app/src/index.css</code>:</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">'Segoe UI'</span>, <span class="hljs-string">'Roboto'</span>, <span class="hljs-string">'Oxygen'</span>,
    <span class="hljs-string">'Ubuntu'</span>, <span class="hljs-string">'Cantarell'</span>, <span class="hljs-string">'Fira Sans'</span>, <span class="hljs-string">'Droid Sans'</span>, <span class="hljs-string">'Helvetica Neue'</span>,
    sans-serif;
  <span class="hljs-attribute">-webkit-font-smoothing</span>: antialiased;
  <span class="hljs-attribute">-moz-osx-font-smoothing</span>: grayscale;

  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#282c34</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
}

<span class="hljs-selector-tag">code</span> {
  <span class="hljs-attribute">font-family</span>: source-code-pro, Menlo, Monaco, Consolas, <span class="hljs-string">'Courier New'</span>,
    monospace;
}
</code></pre>
<p>Also remove <code>js-services/todo-app/src/App.css</code> as we wouldn't need it.</p>
<h3 id="heading-notes-list">Notes list</h3>
<p>We'll split the mockup in a few milestones, just to be able to see what would we get in between. First we're going to make some simple list like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680654243504/a4f92f4b-3115-417e-a37c-f4148f4a2b39.png" alt class="image--center mx-auto" /></p>
<p>For a single note entry define component <code>EntryItem</code> in <code>js-services/todo-app/src/components/EntryItem.tsx</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">"styled-components"</span>;

<span class="hljs-keyword">const</span> EntryItem = styled.div<span class="hljs-string">`
    background-color: #17191e;
    text-align: left;
    padding: 10px;
    margin: 10px;
    border-radius: 2px;
`</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> EntryItem
</code></pre>
<p>In <code>js-services/todo-app/src/App.tsx</code>, remove most of the stuff that was generated initially and use this <code>EntryItem</code> to make a list:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
<span class="hljs-keyword">import</span> EntryItem <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/EntryItem'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"App"</span>&gt;
            &lt;Container&gt;
                &lt;h1&gt;Mify To-Do List&lt;/h1&gt;

                &lt;EntryItem&gt;
                    todo1
                &lt;/EntryItem&gt;
                &lt;EntryItem&gt;
                    todo2
                &lt;/EntryItem&gt;
                &lt;EntryItem&gt;
                    todo3
                &lt;/EntryItem&gt;
            &lt;/Container&gt;
        &lt;/div&gt;
    );
}

<span class="hljs-keyword">const</span> Container = styled.div<span class="hljs-string">`
  position: relative;
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  margin-top: 30px;
  padding: 0 2rem;
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h3 id="heading-adding-new-note-form">Adding new note form</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680654664827/48aba156-bd56-4c78-a91b-893f1ad7c7d8.png" alt class="image--center mx-auto" /></p>
<p>The form would be a more complex component, but using <code>react-hook-form</code> will simplify things for us, here the code for the form, put it in the <code>src/components/TodoNoteForm.tsx</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> {useForm} <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;
<span class="hljs-keyword">import</span> TodoNote <span class="hljs-keyword">from</span> <span class="hljs-string">'../generated/api/clients/todo-backend/models/TodoNote'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
<span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./Button'</span>;

<span class="hljs-keyword">type</span> FormValues = {
    title: <span class="hljs-built_in">string</span>;
    description: <span class="hljs-built_in">string</span>;
    serverError: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">interface</span> TodoNoteFormProps {
    note?: TodoNote;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoNoteForm</span>(<span class="hljs-params">props: TodoNoteFormProps</span>) </span>{
    <span class="hljs-keyword">let</span> defaultValues = {}
    <span class="hljs-keyword">if</span> (props.note) {
        defaultValues = {
            title: props.note.title,
            description: props.note.description,
        }
    }

    <span class="hljs-keyword">const</span> {register, handleSubmit, setError, formState: {errors}} = useForm&lt;FormValues&gt;({
        defaultValues: defaultValues,
    });

    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSubmit</span>(<span class="hljs-params">data: FormValues</span>) </span>{
    }

    <span class="hljs-keyword">return</span> (
        &lt;form onSubmit={handleSubmit(onSubmit)}&gt;
            &lt;div&gt;{errors.serverError &amp;&amp; errors.serverError.message}&lt;/div&gt;
            &lt;TitleInput placeholder=<span class="hljs-string">"Title"</span> <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> {...register(<span class="hljs-string">"title"</span>)} /&gt;
            &lt;DescriptionInput
                placeholder=<span class="hljs-string">"What to do you want to do today?"</span>
                {...register(<span class="hljs-string">"description"</span>)}
            /&gt;
            &lt;Button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;{props.note ? <span class="hljs-string">"Update"</span> : <span class="hljs-string">"Add"</span>} note&lt;/Button&gt;
        &lt;/form&gt;
    );
}

<span class="hljs-keyword">const</span> TitleInput = styled.input<span class="hljs-string">`
    display: block;
    font-size: 18px;
    background-color: #282c34;
    color: white;
    border: none;
    border-radius: 2px;
    padding: 5px;
    margin-top: 10px;
    width: 100%;
`</span>;

<span class="hljs-keyword">const</span> DescriptionInput = styled.textarea<span class="hljs-string">`
    display: block;
    background-color: #282c34;
    color: white;
    border: none;
    border-radius: 2px;
    padding: 5px;
    margin-top: 10px;
    min-height: 100px;
    width: 100%;
`</span>;
</code></pre>
<p><code>react-hook-form</code> allows us to connect form values to inputs via the simple <code>register</code> function call. Also as you can see we're passing note as a property for the form, so that later on we can reuse this form for updating existing notes.</p>
<p>Now, add this form to <code>App.tsx</code>:</p>
<pre><code class="lang-typescript">...
    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"App"</span>&gt;
            &lt;Container&gt;
                &lt;h1&gt;Mify To-Do List&lt;/h1&gt;

                &lt;EntryItem&gt;
                    &lt;TodoNoteForm /&gt;
                &lt;/EntryItem&gt;
                &lt;EntryItem&gt;
                    todo1
                &lt;/EntryItem&gt;
                &lt;EntryItem&gt;
                    todo2
                &lt;/EntryItem&gt;
                &lt;EntryItem&gt;
                    todo3
                &lt;/EntryItem&gt;
            &lt;/Container&gt;
        &lt;/div&gt;
    );
</code></pre>
<h3 id="heading-creating-todonoteentry">Creating TodoNoteEntry</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680655104451/bf96ae66-5403-4b85-b680-587908036674.png" alt class="image--center mx-auto" /></p>
<p>Now that's looks really close to the final version. Here's the code for <code>src/components/TodoNoteEntry.tsx</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> {useState} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
<span class="hljs-keyword">import</span> TodoNote <span class="hljs-keyword">from</span> <span class="hljs-string">'../generated/api/clients/todo-backend/models/TodoNote'</span>;
<span class="hljs-keyword">import</span> EntryItem <span class="hljs-keyword">from</span> <span class="hljs-string">'./EntryItem'</span>;
<span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./Button'</span>;
<span class="hljs-keyword">import</span> moment <span class="hljs-keyword">from</span> <span class="hljs-string">'moment'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> TodoNoteEntryProps {
    content: TodoNote;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoNoteEntry</span>(<span class="hljs-params">props: TodoNoteEntryProps</span>) </span>{
    <span class="hljs-keyword">var</span> [isCompleted, setCompleted] = useState(<span class="hljs-literal">false</span>);
    <span class="hljs-keyword">const</span> note = props.content

    <span class="hljs-keyword">return</span> (
        &lt;EntryItem&gt;
            &lt;EntryData&gt;
                &lt;Content&gt;
                    &lt;Title&gt;{note.title}&lt;/Title&gt;
                    &lt;Description&gt;{note.description}&lt;/Description&gt;
                    &lt;<span class="hljs-built_in">Date</span>&gt;{moment(note.updated_at).fromNow()}&lt;/<span class="hljs-built_in">Date</span>&gt;
                &lt;/Content&gt;
                &lt;Buttons&gt;
                    &lt;CompleteButton
                        isCompleted={isCompleted}
                        onClick={<span class="hljs-function">() =&gt;</span> {
                            setCompleted(!isCompleted)
                        }}
                        &gt;
                        {isCompleted ? <span class="hljs-string">"Uncomplete"</span> : <span class="hljs-string">"Complete"</span>}
                    &lt;/CompleteButton&gt;
                    &lt;Button&gt;Edit&lt;/Button&gt;
                    &lt;DeleteButton&gt;Delete&lt;/DeleteButton&gt;
                &lt;/Buttons&gt;
            &lt;/EntryData&gt;
        &lt;/EntryItem&gt;)

}

<span class="hljs-keyword">const</span> EntryData = styled.div<span class="hljs-string">`
    display: flex;
`</span>;

<span class="hljs-keyword">const</span> Content = styled.div<span class="hljs-string">`
    flex: 1;
`</span>;

<span class="hljs-keyword">const</span> Title = styled.h2<span class="hljs-string">``</span>;

<span class="hljs-keyword">const</span> Description = styled.div<span class="hljs-string">`
    font-size: 16px;
    margin: 5px 0px;
`</span>;

<span class="hljs-keyword">const</span> <span class="hljs-built_in">Date</span> = styled.div<span class="hljs-string">``</span>;

<span class="hljs-keyword">const</span> Buttons = styled.div<span class="hljs-string">`
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;

    button {
        margin-right: 5px;
    }
`</span>;

<span class="hljs-keyword">interface</span> CompleteButtonProps {
    isCompleted: <span class="hljs-built_in">boolean</span>;
}

<span class="hljs-keyword">const</span> CompleteButton = styled(Button)&lt;CompleteButtonProps&gt;<span class="hljs-string">`
    background-color: #<span class="hljs-subst">${props =&gt; props.isCompleted ? <span class="hljs-string">"006400"</span> : <span class="hljs-string">"8b8000"</span>}</span>;
`</span>;

<span class="hljs-keyword">const</span> DeleteButton = styled(Button)<span class="hljs-string">`
    background-color: #8b0000;
`</span>;
</code></pre>
<p>Here in some cases <code>styled-components</code> were used just to create a separate type for the block, but that's not the case for the <code>CompleteButton</code>, it would change color to green when you click it, that is a really powerful feature of this library. Let's also update the list in App.tsx:</p>
<pre><code class="lang-typescript">    <span class="hljs-keyword">let</span> note1 = <span class="hljs-keyword">new</span> TodoNote(<span class="hljs-string">"todo1"</span>, <span class="hljs-string">"2023-04-05"</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"2023-04-05"</span>)
    note1.description = <span class="hljs-string">"todo1 desc"</span>
    <span class="hljs-keyword">let</span> note2 = <span class="hljs-keyword">new</span> TodoNote(<span class="hljs-string">"todo2"</span>, <span class="hljs-string">"2023-04-05"</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"2023-04-05"</span>)
    note2.description = <span class="hljs-string">"todo2 desc"</span>
    <span class="hljs-keyword">let</span> note3 = <span class="hljs-keyword">new</span> TodoNote(<span class="hljs-string">"todo3"</span>, <span class="hljs-string">"2023-04-05"</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"2023-04-05"</span>)
    note3.description = <span class="hljs-string">"todo3 desc"</span>
    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"App"</span>&gt;
            &lt;Container&gt;
                &lt;h1&gt;Mify To-Do List&lt;/h1&gt;

                &lt;EntryItem&gt;
                    &lt;TodoNoteForm /&gt;
                &lt;/EntryItem&gt;
                &lt;TodoNoteEntry content={note1} /&gt;
                &lt;TodoNoteEntry content={note2} /&gt;
                &lt;TodoNoteEntry content={note3} /&gt;
            &lt;/Container&gt;
        &lt;/div&gt;
    );
</code></pre>
<p>We're using the generated <code>TodoNote</code> class to pass the note data for simplicity.</p>
<h3 id="heading-adding-edit-support-for-a-note">Adding edit support for a note</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680655885890/176347fd-c5a2-4075-b51f-88d7cce3587b.png" alt class="image--center mx-auto" /></p>
<p>Now we want to replace the TodoNoteEntry content with the form when we click the Edit button. Here's the update component code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoNoteEntry</span>(<span class="hljs-params">props: TodoNoteEntryProps</span>) </span>{
    <span class="hljs-keyword">var</span> [isEdit, setEdit] = useState(<span class="hljs-literal">false</span>);
    <span class="hljs-keyword">var</span> [isCompleted, setCompleted] = useState(<span class="hljs-literal">false</span>);
    <span class="hljs-keyword">const</span> note = props.content
    <span class="hljs-keyword">const</span> updateList = <span class="hljs-function">() =&gt;</span> {
        setEdit(<span class="hljs-literal">false</span>);
    }

    <span class="hljs-keyword">return</span> (
        &lt;EntryItem&gt;
            {!isEdit &amp;&amp; &lt;EntryData&gt;
                &lt;Content&gt;
                    &lt;Title&gt;{note.title}&lt;/Title&gt;
                    &lt;Description&gt;{note.description}&lt;/Description&gt;
                    &lt;<span class="hljs-built_in">Date</span>&gt;{moment(note.updated_at).fromNow()}&lt;/<span class="hljs-built_in">Date</span>&gt;
                &lt;/Content&gt;
                &lt;Buttons&gt;
                    &lt;CompleteButton
                        isCompleted={isCompleted}
                        onClick={<span class="hljs-function">() =&gt;</span> {
                            setCompleted(!isCompleted)
                        }}
                        &gt;
                        {isCompleted ? <span class="hljs-string">"Uncomplete"</span> : <span class="hljs-string">"Complete"</span>}
                    &lt;/CompleteButton&gt;
                    &lt;Button onClick={<span class="hljs-function">() =&gt;</span> setEdit(<span class="hljs-literal">true</span>)}&gt;Edit&lt;/Button&gt;
                    &lt;DeleteButton&gt;Delete&lt;/DeleteButton&gt;
                &lt;/Buttons&gt;
            &lt;/EntryData&gt;}
            {isEdit &amp;&amp; &lt;TodoNoteForm note={note} updateList={updateList} /&gt;}
        &lt;/EntryItem&gt;)

}
</code></pre>
<p>We're added <code>isEdit</code> state variable which is toggled by Edit button. But how can we close the form after the editing is finished? In React you can't just modify any arbitrary component, all the state changes are propagated from root to the child component. This means we need to add a callback <code>updateList</code> which will update <code>isEdit</code> state variable and close the form. Here are the changes you need to do to add this parameter to the <code>TodoNoteForm</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> TodoNoteFormProps {
    note?: TodoNote;
    updateList: UpdateListFunc
}
...
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoNoteForm</span>(<span class="hljs-params">props: TodoNoteFormProps</span>) </span>{
...
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSubmit</span>(<span class="hljs-params">data: FormValues</span>) </span>{
        props.updateList()
    }
...
}
</code></pre>
<p>Also add an empty <code>updateList</code> callback on the main <code>App.tsx</code> page:</p>
<pre><code class="lang-typescript">&lt;EntryItem&gt;
   &lt;TodoNoteForm updateList={<span class="hljs-function">() =&gt;</span> {}} /&gt;
&lt;/EntryItem&gt;
</code></pre>
<p>If you run the app right now, you should see TodoNoteEntry showing the form when you click the Edit button. It looks like everything is ready for adding calls to backend.</p>
<h2 id="heading-adding-backend-calls">Adding backend calls</h2>
<p>Note: Make sure that your <code>todo-backend</code> is running somewhere, otherwise you won't be able to test it.</p>
<p>First let's use the list method we implemented in this tutorial, update App.tsx with the following things:</p>
<pre><code class="lang-typescript">...
<span class="hljs-keyword">import</span> {useEffect, useState} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> {useAppSelector} <span class="hljs-keyword">from</span> <span class="hljs-string">'./app/hooks'</span>;
<span class="hljs-keyword">import</span> Context <span class="hljs-keyword">from</span> <span class="hljs-string">'./generated/core/context'</span>;
...

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> [notes, setNotes] = useState([]);
    <span class="hljs-keyword">var</span> ctx = useAppSelector(<span class="hljs-function">(<span class="hljs-params">rootState</span>) =&gt;</span> rootState.mifyState.value)
    <span class="hljs-keyword">const</span> updateList = <span class="hljs-keyword">async</span> (ctx: Context) =&gt; {
        setNotes(<span class="hljs-keyword">await</span> ctx.clients.todoBackend().todosGet())
    }
    useEffect(<span class="hljs-function">() =&gt;</span> {updateList(ctx)}, [ctx])
    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"App"</span>&gt;
            &lt;Container&gt;
                &lt;h1&gt;Mify To-Do List&lt;/h1&gt;

                &lt;EntryItem&gt;
                    &lt;TodoNoteForm updateList={<span class="hljs-function">() =&gt;</span> {}} /&gt;
                &lt;/EntryItem&gt;
                {notes.map(<span class="hljs-function">(<span class="hljs-params">note: TodoNote, idx</span>) =&gt;</span> &lt;TodoNoteEntry key={idx} content={note} /&gt;)}
            &lt;/Container&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<p>Mify generated a Context class with the list of clients inside the default Redux state. To make a request to the backend service you just need to call <code>await ctx.clients.todoBackend().todosGet()</code> and it will automatically route it to the locally running service.</p>
<p>Next, make the TodoNoteForm call add and update handlers when the form is submitted:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> {useForm} <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;
<span class="hljs-keyword">import</span> {useAppSelector} <span class="hljs-keyword">from</span> <span class="hljs-string">'../app/hooks'</span>;
<span class="hljs-keyword">import</span> Context <span class="hljs-keyword">from</span> <span class="hljs-string">'../generated/core/context'</span>;
<span class="hljs-keyword">import</span> TodoNote <span class="hljs-keyword">from</span> <span class="hljs-string">'../generated/api/clients/todo-backend/models/TodoNote'</span>;
<span class="hljs-keyword">import</span> TodoNoteCreateRequest <span class="hljs-keyword">from</span> <span class="hljs-string">'../generated/api/clients/todo-backend/models/TodoNoteCreateRequest'</span>;
<span class="hljs-keyword">import</span> TodoNoteUpdateRequest <span class="hljs-keyword">from</span> <span class="hljs-string">'../generated/api/clients/todo-backend/models/TodoNoteUpdateRequest'</span>;
...

<span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> UpdateListFunc = <span class="hljs-function">(<span class="hljs-params">ctx: Context</span>) =&gt;</span> <span class="hljs-built_in">void</span>;
...
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoNoteForm</span>(<span class="hljs-params">props: TodoNoteFormProps</span>) </span>{
    <span class="hljs-keyword">var</span> ctx = useAppSelector(<span class="hljs-function">(<span class="hljs-params">rootState</span>) =&gt;</span> rootState.mifyState.value)
...
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSubmit</span>(<span class="hljs-params">data: FormValues</span>) </span>{
        <span class="hljs-keyword">if</span> (props.note) {
            <span class="hljs-keyword">let</span> req = TodoNoteUpdateRequest.constructFromObject(data, <span class="hljs-literal">null</span>);
            req.is_completed = props.note.is_completed;
            <span class="hljs-keyword">await</span> ctx.clients.todoBackend().todosIdPut(props.note.id, req)
                .catch(<span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> setError(<span class="hljs-string">'serverError'</span>,
                    {<span class="hljs-keyword">type</span>: <span class="hljs-string">"server"</span>, message: <span class="hljs-string">"Failed to update note"</span>}))
            props.updateList(ctx)
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-keyword">const</span> req = TodoNoteCreateRequest.constructFromObject(data, <span class="hljs-literal">null</span>);
        <span class="hljs-keyword">await</span> ctx.clients.todoBackend().todosPost(req)
            .catch(<span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> setError(<span class="hljs-string">'serverError'</span>,
                {<span class="hljs-keyword">type</span>: <span class="hljs-string">"server"</span>, message: <span class="hljs-string">"Failed to add note"</span>}))
        props.updateList(ctx)
    }
...
}
</code></pre>
<p>Also we need to pass <code>updateList</code> to the form from App.tsx:</p>
<pre><code class="lang-typescript">&lt;TodoNoteForm updateList={updateList} /&gt;
</code></pre>
<p>Even though it's unoptimal, we call the <code>updateList</code> callback on every change, but for the simplicity and reliability it would be better like than, otherwise half of this tutorial will be about supporting the state of the to-do notes list.</p>
<p>Finally, implement CompleteButton and DeleteButton in TodoNoteEntry:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> TodoNoteEntryProps {
    content: TodoNote;
    updateList: UpdateListFunc
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoNoteEntry</span>(<span class="hljs-params">props: TodoNoteEntryProps</span>) </span>{
    <span class="hljs-keyword">var</span> [isEdit, setEdit] = useState(<span class="hljs-literal">false</span>);
    <span class="hljs-keyword">const</span> note = props.content
    <span class="hljs-keyword">const</span> updateList = <span class="hljs-function">(<span class="hljs-params">ctx: Context</span>) =&gt;</span> {
        props.updateList(ctx);
        setEdit(<span class="hljs-literal">false</span>);
    }

    <span class="hljs-keyword">var</span> ctx = useAppSelector(<span class="hljs-function">(<span class="hljs-params">rootState</span>) =&gt;</span> rootState.mifyState.value)
    <span class="hljs-keyword">const</span> deleteNote = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">await</span> ctx.clients.todoBackend().todosIdDelete(note.id)
            .catch(<span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> alert(<span class="hljs-string">"Failed to delete note"</span>))
        props.updateList(ctx);
    }

    <span class="hljs-keyword">const</span> toggleCompleteNote = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> req = <span class="hljs-keyword">new</span> TodoNoteUpdateRequest(note.title)
        req.description = note.description
        req.is_completed = !note.is_completed

        <span class="hljs-keyword">await</span> ctx.clients.todoBackend().todosIdPut(note.id, req)
            .catch(<span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> alert(<span class="hljs-string">"Failed to delete note"</span>))
        props.updateList(ctx);
    }
...
                &lt;Buttons&gt;
                    &lt;CompleteButton
                        isCompleted={note.is_completed}
                        onClick={toggleCompleteNote}&gt;
                        {note.is_completed ? <span class="hljs-string">"Uncomplete"</span> : <span class="hljs-string">"Complete"</span>}
                    &lt;/CompleteButton&gt;
                    &lt;Button onClick={<span class="hljs-function">() =&gt;</span> setEdit(<span class="hljs-literal">true</span>)}&gt;Edit&lt;/Button&gt;
                    &lt;DeleteButton onClick={deleteNote}&gt;Delete&lt;/DeleteButton&gt;
                &lt;/Buttons&gt;
...
</code></pre>
<p>And since we're calling <code>updateList</code> in here as well, pass it from the App.tsx:</p>
<pre><code class="lang-typescript">{notes.map(<span class="hljs-function">(<span class="hljs-params">note: TodoNote, idx</span>) =&gt;</span> &lt;TodoNoteEntry key={idx} content={note} updateList={updateList}/&gt;)}
</code></pre>
<p>Great, everything should be implemented now. Check your backend service log to see how the frontend app makes requests.</p>
<h1 id="heading-whats-next">What's next</h1>
<p>With this tutorial we have a basic end-to-end cloud application ready for deployment. From here we can add stuff, which actually makes writing apps a complex task:</p>
<ul>
<li><p>Authentication</p>
</li>
<li><p>Static and dynamic configuration for multiple environments</p>
</li>
<li><p>Feature flags or how to deploy without breaking things (or only if you want it)</p>
</li>
</ul>
<p>Write in comments what would you want to learn more about and we'll be back with it next time.</p>
]]></content:encoded></item><item><title><![CDATA[Building API service with Mify Part 2: Adding Postgres]]></title><description><![CDATA[This is the second part in the series of building API service without the trouble of gluing stuff together. In the last article we have created a Mify…]]></description><link>https://ichebykin.hashnode.dev/building-api-service-with-mify-part-2-adding-postgres</link><guid isPermaLink="true">https://ichebykin.hashnode.dev/building-api-service-with-mify-part-2-adding-postgres</guid><category><![CDATA[Go Language]]></category><category><![CDATA[backend]]></category><category><![CDATA[SaaS]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Ivan Chebykin]]></dc:creator><pubDate>Wed, 01 Mar 2023 23:11:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677109010872/e3bed53a-6b45-48ae-a538-2a8a10682d74.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is the second part in the series of building API service without the trouble of gluing stuff together.</p>
<h1 id="heading-previously">Previously</h1>
<p>In the <a target="_blank" href="https://ichebykin.hashnode.dev/how-to-build-a-restful-api-service-in-go-without-repetitive-boilerplate">last article</a> we have created a Mify backend service for to-do app. But we used memory as a storage for to-do notes, this is for creating a quick mock-up, but for real app we would want our notes to survive restarts.</p>
<p>So, now we're going to add the Postgres storage.</p>
<h1 id="heading-prerequisites">Prerequisites</h1>
<p>Same as in previous tutorial:</p>
<ul>
<li><p>Install <a target="_blank" href="https://go.dev/doc/install">Go</a> 1.18+, <a target="_blank" href="https://docs.docker.com/get-docker/">Docker</a></p>
</li>
<li><p>Get Mify from our GitHub: <a target="_blank" href="https://github.com/mify-io/mify">https://github.com/mify-io/mify</a></p>
</li>
<li><p>Install <a target="_blank" href="https://www.postman.com/downloads/">Postman</a> or curl to test endpoints</p>
</li>
<li><p>And also install <a target="_blank" href="https://docs.docker.com/compose/install/">Docker Compose</a> for running Postgres locally (in new versions of Docker, it comes bundled)</p>
</li>
</ul>
<p>Obligatory link for the complete example before we start: <a target="_blank" href="https://github.com/mify-io/todo-app-example/tree/02-adding-postgres">https://github.com/mify-io/todo-app-example/tree/02-adding-postgres</a></p>
<h1 id="heading-adding-postgres-to-the-service">Adding Postgres to the service</h1>
<p>Mify CLI supports generation of boilerplate for SQL databases (Postgres for now) in a few ways:</p>
<ul>
<li><p>Migrations helper using <a target="_blank" href="https://github.com/amacneil/dbmate">dbmate</a></p>
</li>
<li><p>Automatic connection creation during the service startup, config for the connection can be set via enviroment variable</p>
</li>
<li><p>Querying and database models layer generation via <a target="_blank" href="https://github.com/kyleconroy/sqlc">sqlc</a></p>
</li>
</ul>
<p>To add Postgres support for the <code>todo-backend</code> service run this command:</p>
<pre><code class="lang-bash">$ mify add database todo-backend
</code></pre>
<h2 id="heading-running-postgres-in-docker">Running Postgres in Docker</h2>
<p>Before writing and applying migrations, first you need to start up instance locally. We recommend you to use Docker Compose. You can organise Compose configs for multiple services inside Mify Workspace, just put <code>docker-compose.yaml</code> in <code>go-services/docker/localenv/docker-compose.yaml</code>, here is recommended config:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>
<span class="hljs-attr">services:</span>
  <span class="hljs-attr">postgres:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres:13</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">POSTGRES_USER:</span> <span class="hljs-string">user</span>
      <span class="hljs-attr">POSTGRES_PASSWORD:</span> <span class="hljs-string">passwd</span>
      <span class="hljs-attr">POSTGRES_DB:</span> <span class="hljs-string">todo_backend</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">~/.cache/mify-db:/var/lib/postgresql/data</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-number">5432</span><span class="hljs-string">:5432</span>
</code></pre>
<p>Note: Mify assumes these credentials locally, so you wouldn't have to manually set environment variable, but if you prefer different setup, just set the correct connection URI in <code>DATABASE_URL</code> variable. You can check the default value in generated config at <code>go-services/internal/todo-backend/generated/postgres/config.go</code>.</p>
<p>Run <code>docker compose up</code> inside directory with <code>docker-compose.yaml</code> to start the Postgres instance.</p>
<p>Now we can start defining our database schema.</p>
<h2 id="heading-writing-migrations">Writing migrations</h2>
<p>After running <code>mify add database</code> command you should see two new directories - <code>go-services/migrations</code> and <code>go-services/sql-queries</code>, for migrations and queries respectfully, let's begin with migrations.</p>
<p>We need to have a table for to-do notes, so to create a migration for adding this table, run command:</p>
<pre><code class="lang-bash">$ mify tool migrate todo-backend new todos
</code></pre>
<p><code>todos</code> is the name of migration, you can choose any other name for convenience.</p>
<p>This command will create a migration in <code>go-services/migrations/todo_backend/&lt;date&gt;_&lt;migration_name&gt;.sql</code>. When you open this file you'll see two blocks, one for forward migration, other for rollback:</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- migrate:up</span>

<span class="hljs-comment">-- migrate:down</span>
</code></pre>
<p>Back in the previous tutorial, we defined our todo-note model in domain layer with these fields:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> TodoNote <span class="hljs-keyword">struct</span> {
    ID          <span class="hljs-keyword">int64</span>
    Title       <span class="hljs-keyword">string</span>
    Description <span class="hljs-keyword">string</span>
    IsCompleted <span class="hljs-keyword">bool</span>
    CreatedAt   time.Time
    UpdatedAt   time.Time
}
</code></pre>
<p>Now we'll translate this model to SQL table definition and write migration to create it:</p>
<pre><code class="lang-sql"> <span class="hljs-comment">-- migrate:up</span>

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> todos (
    <span class="hljs-keyword">id</span> bigserial <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    title <span class="hljs-built_in">varchar</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    description <span class="hljs-built_in">text</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    is_completed <span class="hljs-built_in">boolean</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-literal">false</span>,
    created_at <span class="hljs-built_in">timestamp</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NOW</span>(),
    updated_at <span class="hljs-built_in">timestamp</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NOW</span>()
);

<span class="hljs-comment">-- migrate:down</span>

<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> todos;
</code></pre>
<p>To apply this migration run:</p>
<pre><code class="lang-bash">$ mify tool migrate todo-backend up
</code></pre>
<p>You can use DataGrip or psql command to connect to the database and check if the table is created. Usually it's a good practice to check rollback migration as well, there is also a command for that - <code>mify tool migrate todo-backend down</code> , when migration is not as trivial as this, you can do up-down-up check by running these commands consequently.</p>
<h1 id="heading-writing-crud-queries">Writing CRUD queries</h1>
<p>As we said before Mify uses sqlc for generating database layer queries and models. This removes a lot of pain compared to writing queries without it, as it would first check SQL syntax and, because of database models, you'll have type-safe parameters for these queries. Sqlc generation is optional, you can use other libraries or ORMs for making queries, but for now this is what we have included in Mify.</p>
<p>So, in <code>go-services/sql-queries/todo_backend</code> directory, create a file <code>queries.sql</code> and write queries for adding, updating, selecting and deleting to-do notes:</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- name: SelectTodoNote :one</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> todos
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = $<span class="hljs-number">1</span> <span class="hljs-keyword">LIMIT</span> <span class="hljs-number">1</span>;

<span class="hljs-comment">-- name: InsertTodoNote :one</span>
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> todos (
  title, description
) <span class="hljs-keyword">VALUES</span> (
  $<span class="hljs-number">1</span>, $<span class="hljs-number">2</span>
)
<span class="hljs-keyword">RETURNING</span> *;

<span class="hljs-comment">-- name: UpdateTodoNote :one</span>
<span class="hljs-keyword">UPDATE</span> todos
<span class="hljs-keyword">SET</span> title = $<span class="hljs-number">2</span>, description = $<span class="hljs-number">3</span>,
is_completed = $<span class="hljs-number">4</span>, updated_at = $<span class="hljs-number">5</span>
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = $<span class="hljs-number">1</span>
<span class="hljs-keyword">RETURNING</span> *;

<span class="hljs-comment">-- name: DeleteTodoNote :exec</span>
<span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> todos <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = $<span class="hljs-number">1</span>;
</code></pre>
<p>Then, run <code>mify generate</code> and you will see models and queries being generated at <code>go-services/internal/todo-backend/generated/postgres</code>. Now we can use these to write our storage layer.</p>
<h1 id="heading-writing-a-new-storage-layer">Writing a new storage layer</h1>
<h3 id="heading-tododbstorage-skeleton">TodoDBStorage Skeleton</h3>
<p>We have defined a separate <code>TodoStorage</code> interface in domain layer specifically to decouple it from the Service layer, so we could replace in-memory storage later. Leveraging that, all we have to do now is to create another class <code>TodoDBStorage</code> in our storage layer in <code>go-services/internal/todo-backend/storage/todo_db.go</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> storage

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"errors"</span>

    <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/domain"</span>
    <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/core"</span>
    <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/postgres"</span>
    <span class="hljs-string">"github.com/jackc/pgx/v4"</span>
    <span class="hljs-string">"github.com/jackc/pgx/v4/pgxpool"</span>

)

<span class="hljs-keyword">type</span> TodoDBStorage <span class="hljs-keyword">struct</span> {
    pool *pgxpool.Pool
    querier *postgres.Queries
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewTodoDBStorage</span><span class="hljs-params">(ctx *core.MifyServiceContext)</span> *<span class="hljs-title">TodoDBStorage</span></span> {
    <span class="hljs-keyword">return</span> &amp;TodoDBStorage{
        pool: ctx.Postgres(),
        querier: postgres.New(ctx.Postgres()),
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">InsertTodoNote</span><span class="hljs-params">(
    ctx *core.MifyRequestContext, todoNote domain.TodoNote)</span> <span class="hljs-params">(domain.TodoNote, error)</span></span> {
    <span class="hljs-keyword">return</span> domain.TodoNode{}, <span class="hljs-literal">nil</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">SelectTodoNote</span><span class="hljs-params">(ctx *core.MifyRequestContext, id <span class="hljs-keyword">int64</span>)</span> <span class="hljs-params">(domain.TodoNote, error)</span></span> {
    <span class="hljs-keyword">return</span> domain.TodoNode{}, <span class="hljs-literal">nil</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">UpdateTodoNote</span><span class="hljs-params">(
    ctx *core.MifyRequestContext, todoNote domain.TodoNote)</span> <span class="hljs-params">(domain.TodoNote, error)</span></span> {
    <span class="hljs-keyword">return</span> domain.TodoNode{}, <span class="hljs-literal">nil</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">DeleteTodoNote</span><span class="hljs-params">(ctx *core.MifyRequestContext, id <span class="hljs-keyword">int64</span>)</span> <span class="hljs-title">error</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
}
</code></pre>
<p>Here we pass Postgres pool from <code>MifyServiceContext</code> which would be created at the service startup. Before implementing actual methods, here's the helper for converting database layer model to domain one:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeDomainTodoNode</span><span class="hljs-params">(res postgres.Todo)</span> <span class="hljs-title">domain</span>.<span class="hljs-title">TodoNote</span></span> {
    <span class="hljs-keyword">return</span> domain.TodoNote{
        ID: res.ID,
        Title: res.Title,
        Description: res.Description,
        IsCompleted: res.IsCompleted,
        CreatedAt: res.CreatedAt,
        UpdatedAt: res.UpdatedAt,
    }
}
</code></pre>
<p>It will be used in Insert, Update, Select methods, although it's straightforward, we should avoid unnecessary code duplication, and in more complex cases there should be some conversion or transformation logic involved.</p>
<h3 id="heading-crud-operations">CRUD operations</h3>
<p>Let's begin implementing operations, starting with <code>InsertTodoNode</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">InsertTodoNote</span><span class="hljs-params">(
    ctx *core.MifyRequestContext, todoNote domain.TodoNote)</span> <span class="hljs-params">(domain.TodoNote, error)</span></span> {
    <span class="hljs-comment">// Create transaction</span>
    tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-comment">// Don't forget to rollback in case of error</span>
    <span class="hljs-keyword">defer</span> tx.Rollback(ctx)
    res, err := s.querier.WithTx(tx).InsertTodoNote(ctx, postgres.InsertTodoNoteParams{
        Title: todoNote.Title,
        Description: todoNote.Description,
    })
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-keyword">if</span> err := tx.Commit(ctx); err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-keyword">return</span> makeDomainTodoNode(res), <span class="hljs-literal">nil</span>
}
</code></pre>
<p>In this method we just need to create transaction, and call the generated <code>InsertTodoNode</code> function with the correct paramers. Same idea with <code>UpdateTodoNote</code> and <code>DeleteTodoNote</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">UpdateTodoNote</span><span class="hljs-params">(
    ctx *core.MifyRequestContext, todoNote domain.TodoNote)</span> <span class="hljs-params">(domain.TodoNote, error)</span></span> {
    tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-keyword">defer</span> tx.Rollback(ctx)
    res, err := s.querier.WithTx(tx).UpdateTodoNote(ctx, postgres.UpdateTodoNoteParams{
        ID: todoNote.ID,
        Title: todoNote.Title,
        Description: todoNote.Description,
        IsCompleted: todoNote.IsCompleted,
        UpdatedAt: todoNote.UpdatedAt,
    })
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-keyword">if</span> err := tx.Commit(ctx); err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-keyword">return</span> makeDomainTodoNode(res), <span class="hljs-literal">nil</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">DeleteTodoNote</span><span class="hljs-params">(ctx *core.MifyRequestContext, id <span class="hljs-keyword">int64</span>)</span> <span class="hljs-title">error</span></span> {
    tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> err
    }
    <span class="hljs-keyword">defer</span> tx.Rollback(ctx)
    <span class="hljs-keyword">if</span> err := s.querier.WithTx(tx).DeleteTodoNote(ctx, id); err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> err
    }
    <span class="hljs-keyword">return</span> tx.Commit(ctx)
}
</code></pre>
<p>In <code>SelectTodoNote</code> we don't really need transaction, so it would be just a simple proxy with error handling for returning error 404:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *TodoDBStorage)</span> <span class="hljs-title">SelectTodoNote</span><span class="hljs-params">(ctx *core.MifyRequestContext, id <span class="hljs-keyword">int64</span>)</span> <span class="hljs-params">(domain.TodoNote, error)</span></span> {
    res, err := s.querier.SelectTodoNote(ctx, id)
    <span class="hljs-comment">// Handle that no rows can be returned, so we can correctly return 404</span>
    <span class="hljs-comment">// to user instead of obscure 500 error.</span>
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &amp;&amp; errors.Is(err, pgx.ErrNoRows) {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, ErrTodoNoteNotFound
    }
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> domain.TodoNote{}, err
    }
    <span class="hljs-keyword">return</span> makeDomainTodoNode(res), <span class="hljs-literal">nil</span>
}
</code></pre>
<h3 id="heading-updating-service-to-use-tododbstorage">Updating Service to use TodoDBStorage</h3>
<p>Let's go back to a place, where we wire all the service dependencies - `go-services/internal/todo-backend/app/service_extra.go`. Here we just need to replace TodoMemStorage with TodoDBStorage:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewServiceExtra</span><span class="hljs-params">(ctx *core.MifyServiceContext)</span> <span class="hljs-params">(*ServiceExtra, error)</span></span> {
    dbStorage := storage.NewTodoDBStorage(ctx)
    todoService := application.NewTodoService(dbStorage)
    extra := &amp;ServiceExtra{
        TodoService: todoService,
    }
    <span class="hljs-keyword">return</span> extra, <span class="hljs-literal">nil</span>
}
</code></pre>
<h1 id="heading-testing">Testing</h1>
<p>Now you can run service with <code>go run ./cmd/todo-backend</code> and see if storage is persistent.</p>
<p>First make a GET query:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677711104621/0e02c73a-edaa-4de5-bc8e-0a182e718ab3.png" alt class="image--center mx-auto" /></p>
<p>404, as expected. Then add a note with POST method:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677711127341/7ea3d2e5-6531-4699-886b-5e87397b5802.png" alt class="image--center mx-auto" /></p>
<p>Check again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677711145565/da355a56-baea-4936-abe8-040d762c8ed1.png" alt class="image--center mx-auto" /></p>
<p>Successfully added, now you can restart and see that it's still there or check the table in database directly.</p>
<h1 id="heading-whats-next">What's next</h1>
<p>After this tutorial this service is looking more or less ready for real-life usage, at least it can be deployed <a target="_blank" href="https://mify.io/docs/cloud/overview">somewhere</a>. But we can still add more to it, for instance frontend, so you wouldn't have to use postman all the time. And, naturally for a frontend we need to have some authentication.</p>
<p>So, until next time, we'll be back.</p>
]]></content:encoded></item><item><title><![CDATA[How to build a RESTful API service in Go without repetitive boilerplate]]></title><description><![CDATA[There are a lot of materials about how to write services, where at first you need to choose some framework to use, then comes wiring of handlers, configs…]]></description><link>https://ichebykin.hashnode.dev/how-to-build-a-restful-api-service-in-go-without-repetitive-boilerplate</link><guid isPermaLink="true">https://ichebykin.hashnode.dev/how-to-build-a-restful-api-service-in-go-without-repetitive-boilerplate</guid><category><![CDATA[SaaS]]></category><category><![CDATA[backend]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ivan Chebykin]]></dc:creator><pubDate>Mon, 20 Feb 2023 22:00:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676931757396/042b59f7-623c-4989-ba5e-6dfaa51f8e5f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are a lot of materials about how to write services, where at first you need to choose some framework to use, then comes wiring of handlers, configs, logs, storage, etc, not to mention deploying that service somewhere. We’ve been writing services for quite some time and more often than not you’d just want to skip all this tedious process of gluing stuff together and just write some useful code.</p>
<p>That’s why we created a tool, called Mify — it’s an open-source infrastructure boilerplate generator, which would help you build a service, taking the best practices used to date. So in this tutorial, we’ll show how to create a simple service using Mify with a classic example — a to-do app.</p>
<h1 id="heading-prerequisites">Prerequisites</h1>
<ul>
<li><p>Install <a target="_blank" href="https://go.dev/doc/install">Go</a> 1.18+, <a target="_blank" href="https://docs.docker.com/get-docker/">Docker</a></p>
</li>
<li><p>Get Mify from our GitHub: <a target="_blank" href="https://github.com/mify-io/mify">https://github.com/mify-io/mify</a></p>
</li>
<li><p>Install <a target="_blank" href="https://www.postman.com/downloads/">Postman</a> or curl to test endpoints</p>
</li>
</ul>
<p>Before starting this tutorial, here’s the link to the complete example: <a target="_blank" href="https://github.com/mify-io/todo-app-example">https://github.com/mify-io/todo-app-example</a></p>
<h1 id="heading-creating-project">Creating Project</h1>
<p>After installing Mify, to start the project you need to create the workspace:</p>
<pre><code class="lang-bash">$ mify init todo-app
$ <span class="hljs-built_in">cd</span> todo-app
</code></pre>
<p>After getting into the new workspace, run:</p>
<pre><code class="lang-bash">$ mify add service todo-backend
</code></pre>
<p>Now, this will create a Go template for your to-do backend. Here’s a simplified tree of the workspace with all generated files:</p>
<pre><code class="lang-bash">.
├── go-services
│   ├── cmd
│   │   ├── dev-runner
│   │   │   └── main.go
│   │   └── todo-backend
│   │       ├── Dockerfile
│   │       └── main.go
│   ├── go.mod
│   ├── go.sum
│   └── internal
│       ├── pkg
│       │   └── generated
│       │       ├── configs
│       │       │   └── ...
│       │       ├── consul
│       │       │   └── ...
│       │       ├── logs
│       │       │   └── ...
│       │       └── metrics
│       │           └── ...
│       └── todo-backend
│           ├── app
│           │   ├── request_extra.go
│           │   ├── router
│           │   │   └── router.go
│           │   └── service_extra.go
│           └── generated
│               ├── api
|               |   └── ...
│               ├── app
│               │   └── ...
│               ├── apputil
│               │   └── ...
│               └── core
│                   └── ...
├── schemas
│   └── todo-backend
│       ├── api
│       │   └── api.yaml
│       └── service.mify.yaml
└── workspace.mify.yaml
</code></pre>
<p>Mify loosely follows one of the common Go layouts, which is suitable for multiple services in one repository. In <code>internal/pkg/generated</code> there are common libraries for configs, logs, and metrics that can be reused for multiple services. Your service go-to directory is in <code>internal/todo-backend</code> .</p>
<p>At this point this service is pretty bare, so we need to add API to it.</p>
<h1 id="heading-defining-api">Defining API</h1>
<p>You can find the OpenAPI schema for the todo-backend in <code>schemas/todo-backend/api/api.yaml</code> file. Schemas directory in the root of the workspace is a place where all service configs related to Mify are stored.</p>
<p>Let’s create a simple CRUD API for your todo backend:</p>
<ul>
<li><p><code>POST /todos</code> for adding new to-do notes.</p>
</li>
<li><p><code>PUT,GET,DELETE /todos/{id}</code> for updating, retrieving, and deleting them.</p>
</li>
</ul>
<p>Here’s how your OpenAPI schema would look for this API:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="5dc7b30a2a57a1ab4584895131295e1f"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/5dc7b30a2a57a1ab4584895131295e1f" class="embed-card">https://gist.github.com/chebykinn/5dc7b30a2a57a1ab4584895131295e1f</a></div><p> </p>
<p>Replace the previous schema with this one and run <code>mify generate</code> . You can run it each time you update the schema and it will regenerate all the changed stuff.</p>
<h1 id="heading-building-and-testing">Building and Testing</h1>
<pre><code class="lang-bash">$ <span class="hljs-built_in">cd</span> go-services
$ go mod tidy
$ go run ./cmd/todo-backend
</code></pre>
<p>You should see startup logs like that:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676929933564/269936cf-8fff-4254-a392-f06b07f814f7.png" alt class="image--center mx-auto" /></p>
<p>You can see the service port in <code>starting api server</code> log message, copy it to Postman, and try calling some API handler:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676929918768/9c373b2e-027d-4009-8fea-abfbae477d97.png" alt class="image--center mx-auto" /></p>
<p>You can see that the handler returned nothing, which is expected because as the error suggests, it’s not implemented yet.</p>
<h1 id="heading-adding-models-and-mock-storage">Adding Models and Mock Storage</h1>
<p>First, we need to create a model for the todo note, we’ll put it in the <code>domain</code> package</p>
<p>in <code>go-services/internal/todo-backend/domain/todo.go</code> :</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="0c2905f07d76082bd9d63a56a720371c"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/0c2905f07d76082bd9d63a56a720371c" class="embed-card">https://gist.github.com/chebykinn/0c2905f07d76082bd9d63a56a720371c</a></div><p> </p>
<p>This is also a good place to define the interface for storage, which is useful for decoupling persistence logic from the application. In this tutorial, we’ll use mock storage, in memory, but Mify also supports Postgres, which we can add later in a follow-up article. Let’s put storage in <code>go-services/internal/todo-backend/storage/todo_mem.go:</code></p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="1769d6881e929bfb225fc203c48e1496"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/1769d6881e929bfb225fc203c48e1496" class="embed-card">https://gist.github.com/chebykinn/1769d6881e929bfb225fc203c48e1496</a></div><p> </p>
<p>That’s all for logic, we just need to add it to handlers.</p>
<h1 id="heading-implementing-handlers">Implementing Handlers</h1>
<p><code>go-services/internal/todo-backend/handlers/todos/service.go</code> for POST method, and</p>
<p><code>go-services/internal/todo-backend/handlers/todos/id/service.go</code> for others.</p>
<p>Here’s an example of a stub of the POST method:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="e49b483330ea7c84a1b8082b0a86fc01"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/e49b483330ea7c84a1b8082b0a86fc01" class="embed-card">https://gist.github.com/chebykinn/e49b483330ea7c84a1b8082b0a86fc01</a></div><p> </p>
<p>Now, let’s implement all handlers.</p>
<p><code>go-services/internal/todo-backend/handlers/todos/service.go</code> :</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="6f88c03680167c4dc286f1b6226341f9"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/6f88c03680167c4dc286f1b6226341f9" class="embed-card">https://gist.github.com/chebykinn/6f88c03680167c4dc286f1b6226341f9</a></div><p> </p>
<p>Don’t forget to update imports:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
 <span class="hljs-string">"net/http"</span>
 <span class="hljs-string">"strconv"</span>

 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/domain"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/api"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/apputil"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/core"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/handlers"</span>
)
</code></pre>
<p><code>go-services/internal/todo-backend/handlers/todos/id/service.go</code> :</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="98d2d051671dfbefb464b1f59b159d15"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/98d2d051671dfbefb464b1f59b159d15" class="embed-card">https://gist.github.com/chebykinn/98d2d051671dfbefb464b1f59b159d15</a></div><p> </p>
<p>And here are imports for them as well:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
 <span class="hljs-string">"errors"</span>
 <span class="hljs-string">"fmt"</span>
 <span class="hljs-string">"net/http"</span>
 <span class="hljs-string">"strconv"</span>

 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/domain"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/api"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/apputil"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/generated/core"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/handlers"</span>
 <span class="hljs-string">"example.com/namespace/todo-app/go-services/internal/todo-backend/storage"</span>
)
</code></pre>
<p>The handler’s logic is pretty simple, we’re just converting generated OpenAPI models to our application one and back, and to avoid duplication in code, here’s a helper for creating a TodoNode response, which is used in these implementations:</p>
<p><code>go-services/internal/todo-backend/handlers/common.go</code> :</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="702f24abe035cd99dbc06c4447ecc755"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/chebykinn/702f24abe035cd99dbc06c4447ecc755" class="embed-card">https://gist.github.com/chebykinn/702f24abe035cd99dbc06c4447ecc755</a></div><p> </p>
<h1 id="heading-testing-again">Testing Again</h1>
<p>First, we can add a new todo note with a POST request:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676930128913/0be28483-5575-49ee-94c5-33efbbcf899f.png" alt class="image--center mx-auto" /></p>
<p>Check if it is added with a GET request:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676930141547/db6b8ad7-e017-4f8f-a26b-e49589146273.png" alt class="image--center mx-auto" /></p>
<p>Update it with a PUT request:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676930154236/6016de94-ea13-4ce1-905e-dc6dbb3586d2.png" alt class="image--center mx-auto" /></p>
<p>Delete it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676930241027/a7a5cbc8-ecdf-4c94-845c-38232b5d8dd4.png" alt class="image--center mx-auto" /></p>
<p>And run GET once again to check if it was deleted:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676930255647/bf64838e-2318-4840-91e3-feaf77da16e2.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-whats-next">What’s Next</h1>
<ul>
<li><p>Persistent storage, like Postgres,</p>
</li>
<li><p>Configuration,</p>
</li>
<li><p>Authentication middleware,</p>
</li>
<li><p>Deployment to the cloud.</p>
</li>
</ul>
<p>Most of this stuff is covered in our docs, so check them out: <a target="_blank" href="https://mify.io/docs">https://mify.io/docs</a>, but stay tuned for the next articles.</p>
]]></content:encoded></item></channel></rss>