<?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[Effective Development - Medium]]></title>
        <description><![CDATA[Software Engineering And Management Blog - Medium]]></description>
        <link>https://medium.com/effective-development?source=rss----5844d61cf31b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Effective Development - Medium</title>
            <link>https://medium.com/effective-development?source=rss----5844d61cf31b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:58:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/effective-development" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Split an Application Into Microservices — and When You Don’t Need Them]]></title>
            <link>https://medium.com/effective-development/how-to-split-an-application-into-microservices-and-when-you-dont-need-them-c3388c9c169e?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/c3388c9c169e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 14:48:01 GMT</pubDate>
            <atom:updated>2024-11-24T15:56:00.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Split an Application Into Microservices — and When You Don’t Need Them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnlhEsxpNF8GWd_vaGFcSg.jpeg" /></figure><p>During my career, as with most developers with enough experience, I have seen bad and very bad microservice architectures and I have made bad decision too because it’s not obvious, everything related to software architecture is quite hard and requires a lot of experience. If you are new to the world of application architecture, this article is for you. Here I will try to show you what measures to use to to divide your application into services, when you need it, and when you don’t.</p><h3>When You Need a Separate Service</h3><p>When we talk about splitting an application into separate services, we have to be very cautious because every new service is a point of failure, an additional headache to the process of QA, deployment, etc.</p><h3>Performance</h3><p>One of the big reasons to have a separate service for some chunk of functionality is performance requirements. You may have your service built in Node.js or Python, but you definitely don’t want to write CPU-intensive calculations in these languages because you will be limited by their nature. In this case, it’s better to make it a separate service. Make a service in a more performant language such as: Rust, Golang. You can make it a service or you can <strong>embed</strong> it into an existing service.</p><h3>Wrong Tool for the Job</h3><p>Another case is if you have your core functionality written in, let’s say, Rust. You don’t want to write an admin portal or client portal in the same Rust service; it will take you ages. In this case, you are better off writing a separate service in Elixir, Ruby, JavaScript, or something that provides a full-stack framework that will save you time.</p><h3>Criticality of the Service or Different Security Standards</h3><p>Another considerable reason to split a piece of functionality into a separate service is the level of criticality of that service. Let’s say you wrote a piece of logic that does some calculations that do not require a lot of CPU or RAM, but these calculations are critical and must not be messed up. I would argue that it’s a serious reason to split that logic into a separate service in order to have a dedicated process for QA, CI/CD, and testing standards. You won’t need to give access to this repository to anyone except people who are responsible for this chunk of code; you will always know what to test and be highly cautious dealing with this service.</p><h3>Infrastructure Cost</h3><p>Another reason to have a separate service is infrastructure costs. Let’s take this example: you have a service A that is replicated into multiple geographical zones, and you have a piece of functionality that has heavy I/O load to and from a source that is located in one place. In this case, it’s better to split the I/O-related functionality into a separate service and place that service near the data source, because almost all cloud providers either provide output traffic for money or have limits. If your data-related service outputs terabytes of data, you have to care about the price that you will pay for this data.</p><h3>When You Don’t Need a Separate Service</h3><p>From my experience, you don’t need to make a separate service if you have one of the following cases.</p><h3>Different Contexts</h3><p>If you have a piece of functionality that has a different context, even if this context looks like a perfect candidate for a separate service — <strong>DON’T DO IT.</strong> Make it a different module and relax; there is nothing wrong with having your user management service as a module in your core monolithic service.</p><h3>Different Scaling Requirements</h3><p>If you have a chunk of code that will require serious scaling and you think that it’s better to make it a separate service, you shouldn’t if you can scale the incorporating service without too much cost. It’s always better to make something a separate module than a service unless you have different performance requirements (see “Performance” section). A module is always easy to split out into a service than do the opposite.</p><h3>Language Preferences of Different Developers</h3><p>No, you should not make a separate service if your developers don’t like the language and want to write in something else. It’s pretty much always better to keep the codebase consistent and in one place. By keeping things consistent, you will avoid a lot of headaches.</p><p>Thank you for reading!</p><p>👏Don’t forget to clap if you liked the article👏</p><p>If you want to <strong>reduce churn and increate conversion</strong> of your business check out my latest product <a href="https://usewidgetform.com/"><strong>Widgetform</strong></a><strong> </strong>💬. It is a highly configurable widget that allows you to collect insights about your users.</p><h3>Contacts</h3><p>If you like this article don’t hesitate to connect on <a href="https://www.linkedin.com/in/sergei-suslov/">LinkedIn</a> and follow me on <a href="https://x.com/sergeysuslovnsk">Twitter</a>.</p><p><strong>Subscribe to my mailing list</strong>: <a href="https://sergedevs.com/">https://sergedevs.com</a></p><p>Be sure to clap and follow 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3388c9c169e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/how-to-split-an-application-into-microservices-and-when-you-dont-need-them-c3388c9c169e">How to Split an Application Into Microservices — and When You Don’t Need Them</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir+Phoenix is a Great Choice for Start-Ups]]></title>
            <link>https://medium.com/effective-development/elixir-phoenix-is-a-great-choice-for-start-ups-93d18b6248f3?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/93d18b6248f3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[enterpreneurship]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[phoenix]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 16:09:09 GMT</pubDate>
            <atom:updated>2024-11-24T15:55:57.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJB36tQK5HVCSWtCzlaDKw.png" /></figure><p>For a Rust/TypeScript/Go developer, Elixir might seem like a strange choice, especially since it has some quirks similar to JavaScript (like == and ===). However, I was always drawn to its syntax and the functional programming aspect was new and intriguing to me.</p><p>The first time I tried Elixir was during Advent of Code. I liked it immediately, but after solving 3–5 problems, I started to dislike it. I didn’t appreciate the lack of types (only type annotations) and the absence of early returns. But now, I realize I was completely wrong about the language.</p><h3>Type System</h3><p>The type system usually determines if I even consider a language. Take Python, for example — it lacks true types and only has type hints. This, along with Python’s other issues (GIL, memory inefficiency, slow execution, async/await complexities, lack of true multithreading, and library inconsistencies), bothers me the most, especially with large codebases.</p><p>Elixir is different. Even though it has dynamic types, it doesn’t cause as much pain as JavaScript or Python due to two features: immutability and pattern matching.</p><h4>Immutability</h4><p>Immutability helps prevent many mistakes common in mutable languages. You can’t accidentally pass something that gets mutated by code elsewhere in the app. You also avoid issues with asynchronous mutations because everything is immutable.</p><pre>immutable = %{foo: &quot;bar&quot;}<br><br>reassigned = Map.put(immutable, :foo1, &quot;foo&quot;)<br>IO.puts(&quot;Reassigned is #{inspect(reassigned)}&quot;)<br><br>Task.async(fn -&gt;<br> :timer.sleep(100)<br> IO.puts(&quot;Immutable is #{inspect(immutable)}&quot;)<br>end)<br><br>mutated = Map.put(immutable, :bar, &quot;foo&quot;)<br>IO.puts(&quot;Mutated is #{inspect(mutated)}&quot;)</pre><p>Result:</p><pre>Reassigned is %{foo: &quot;bar&quot;, foo1: &quot;foo&quot;}<br>Mutated is %{foo: &quot;bar&quot;, bar: &quot;foo&quot;}<br>Immutable is %{foo: &quot;bar&quot;}</pre><p>As you can see, immutable stayed the same while mutated changed. Elixir supports object versioning, which keeps memory usage efficient.</p><h4>Type Guards and Pattern Matching</h4><p>I dislike type guards in languages without pattern matching; they always seem like a crutch. Elixir has both pattern matching and proper type guards built into the language.</p><p>Elixir also does not support early returns. Instead, almost everything is an expression, and the last expression is always the result of a function or parent expression. This encourages splitting logic into smaller functions, which is beneficial.</p><p>In JavaScript, you might have something like:</p><pre>class Human {<br>    iq: number;<br>    constructor(iq: number) {<br>        this.iq = iq;<br>    }<br>}<br><br>interface Bird {<br>    iq: number;<br>    hasWings: boolean;<br>}</pre><p>You can write a function like this:</p><pre>function foo(object: Human | Bird): string {<br>    if (&quot;hasWings&quot; in object) { // you can do this because only Bird has the hasWings field<br>        return `Hi bird. wings=${object.hasWings}`;<br>    }<br>    return `Hello fellow Human! iq=${object.iq}`;<br>}</pre><p>Or you can make runtime checks with instanceof:</p><pre>function foo(object: Human | Bird): string {<br>    if (object instanceof Human) {<br>        return `Hello fellow Human! iq=${object.iq}`;<br>    }<br>    return `Hi bird. wings=${object.hasWings}`;<br>}</pre><p>The Elixir way would be to split them into two functions (Elixir supports function overloading):</p><pre>defmodule Types.Bird do<br>    defstruct iq: 0, has_wings?: true<br>end<br><br>defmodule Types.Human do<br>    defstruct iq: 0<br>end<br><br>defmodule HumanBird do<br>    def foo(%Types.Bird{} = bird), do: &quot;Hi bird. wings=#{bird.has_wings?}&quot;<br>    def foo(%Types.Human{} = human), do: &quot;Hello fellow Human! iq=#{human.iq}&quot;<br>end</pre><p>We can also make runtime checks to match functions:</p><pre>defmodule Types.Bird do<br>    defstruct iq: 0, has_wings?: true<br>end<br><br>defmodule Types.Human do<br>    defstruct iq: 0<br>end<br><br>defmodule HumanBird do<br>    def foo(%Types.Bird{} = bird), do: &quot;Hi bird. wings=#{bird.has_wings?}&quot;<br>    def foo(%Types.Human{iq: iq} = human) when iq &gt; 100, do: &quot;Hello very smart Human! iq=#{human.iq}&quot;<br>    def foo(%Types.Human{} = human), do: &quot;Hello fellow Human! iq=#{human.iq}&quot;<br>end</pre><p>The result would be:</p><pre>iex(1)&gt; HumanBird.foo(%Types.Human{iq: 90})<br>&quot;Hello fellow Human! iq=90&quot;<br>iex(2)&gt; HumanBird.foo(%Types.Human{iq: 101})<br>&quot;Hello very smart Human! iq=101&quot;</pre><h3>Asynchronous Model</h3><p>Elixir’s asynchronous model feels similar to Golang’s. It has green threads (called processes), and all communication is done by sending signals to processes (like channels in Golang, though a process has only one channel). Processes are managed with Supervisors.</p><p>Elixir processes are lightweight and can be spawned by the thousands without significant performance hits. This allows you to design highly concurrent and fault-tolerant systems efficiently. Each process is isolated and has its own memory heap, enabling separate garbage collection and ensuring fault tolerance. If one process fails, others remain unaffected.</p><h4>Processes and Communication</h4><p>Elixir uses green threads, and all communication is done by sending signals. Unlike JavaScript or Python, Elixir does not have async/await syntax, avoiding function coloring (a big advantage). Instead, you create processes and send them signals by PID or wait for signals to your process. This model allows for powerful abstractions and flexible work with async processes.</p><p>Sending a signal to the same process:</p><pre>send(self(), {:message, &quot;Hello from Self&quot;})<br>receive do<br>    {:message, m} -&gt; IO.puts(m)<br>end</pre><p>Prints: Hello from Self</p><h3>Supervisors</h3><p>Supervisors are a key part of Elixir’s fault-tolerance and concurrency model. They are processes designed to monitor and manage other processes, known as child processes. The main purpose of a Supervisor is to ensure that if any of its child processes fail, they are restarted according to a specified strategy, maintaining the overall health and resilience of the application.</p><p>Supervisors use different strategies to handle failures:</p><ul><li>:one_for_one: If a child process terminates, only that process is restarted.</li><li>:one_for_all: If a child process terminates, all other child processes are terminated and then all are restarted.</li><li>:rest_for_one: If a child process terminates, the terminated process and any processes started after it are restarted.</li><li>:simple_one_for_one: A simplified :one_for_one strategy for dynamically attached children.</li></ul><p>A basic example of a Supervisor might look like this:</p><pre>defmodule MyApp.Supervisor do<br>  use Supervisor<br><br>  def start_link(arg) do<br>    Supervisor.start_link(__MODULE__, arg, name: __MODULE__)<br>  end<br><br>  @impl true<br>  def init(_arg) do<br>    children = [<br>      {MyApp.Worker, arg}<br>    ]<br><br>    Supervisor.init(children, strategy: :one_for_one)<br>  end<br>end</pre><p>In this example, MyApp.Supervisor starts and supervises a worker process named MyApp.Worker. If the worker process crashes, the Supervisor will restart it according to the :one_for_one strategy.</p><h4>Process Linking</h4><p>Process linking in Elixir creates a bidirectional relationship between two processes, ensuring that if one process terminates (either normally or abnormally), the linked process is also terminated.</p><h4><strong>Creating a Link</strong></h4><p>A link between processes can be created using the Process.link/1 function or Task.start_link to start a linked process. For example:</p><p>A link between processes can be created using the Process.link/1 function or Task.start_link to start a linked process. For example:</p><pre>spawn_link(fn -&gt;<br>  # Process code here<br>end)<br>Task.start_link(fn -&gt; IO.puts(&quot;Started Linked&quot;) end) # with Task</pre><p>Or by explicitly linking two processes:</p><pre>pid = spawn(fn -&gt;<br>  # Process code here<br>end)<br>Process.link(pid)</pre><h4>Use Cases</h4><ol><li><strong>Supervisors</strong>: Supervisors use process linking to monitor their child processes. If a child process crashes, the supervisor can restart it based on the defined strategy.</li><li><strong>Monitoring</strong>: Processes that need to monitor the health of other processes can use linking to be notified of crashes and take appropriate actions.</li></ol><p>Process linking allows the creation of hierarchies of Supervisors and processes to ensure fault tolerance.</p><h3>Not Everything Should Be JavaScript</h3><p>Another thing that I discovered is that not everything on the client side needs to be JavaScript. For all my latest project, if I needed a UI to interact with users I usually used Next.js or other React.js based solutions. This time, I decided to try Phoenix, the default framework for Elixir projects (similar to Ruby on Rails for Ruby, Django for Python, Spring for Java).</p><p>Initially, writing the backend was smooth, but creating the client-side code was challenging. As someone used to writing everything in tsx files, using Phoenix was a significant lift. I had to use cookies, sessions, and write a lot of styles. However, I learned a few things in the process.</p><h4>We Rely Too Much on JavaScript</h4><p>Many tasks I typically did in JavaScript could be done with CSS, HTML, and maybe a bit of JavaScript. Tabs, dropdowns, forms, and animations that I previously created with JavaScript were possible without it. I realized that as developers, we’ve gotten lazy and often overlook existing solutions. I remember the days of jQuery and how easy it was (not without problems ofc) to use. But then came React, Redux, Redux Saga, and other libraries that were so overcomplicated. Now, it seems we’re returning to more basic solutions that simply get the job done, such as Svelte, HTMX, Solid, and others.</p><h3>Phoenix LiveView</h3><p>Phoenix has a feature called LiveView, and it’s fantastic.</p><p>LiveView allows you to create real-time components with server-rendered HTML that updates in real-time as data changes. It eliminates the need for much of the JavaScript boilerplate we often rely on, keeping logic on the backend.</p><ul><li>Built-in PubSub and Channels</li><li>Scalability thanks to the Erlang VM</li><li>Real-time component updates</li></ul><p>Here’s a small example of a LiveView component that renders a paragraph with “Initial Value” text and a button that changes the content of the paragraph to “Updated Value” on click:</p><pre>defmodule LiveviewExampleWeb.FieldLive do<br>  use Phoenix.LiveView<br><br>  def mount(_params, _session, socket) do<br>    {:ok, assign(socket, :field_value, &quot;Initial Value&quot;)}<br>  end<br><br>  def handle_event(&quot;update_field&quot;, _value, socket) do<br>    new_value = &quot;Updated Value&quot;<br>    {:noreply, assign(socket, :field_value, new_value)}<br>  end<br><br>  def render(assigns) do<br>    ~L&quot;&quot;&quot;<br>    &lt;div&gt;<br>      &lt;p&gt;&lt;%= @field_value %&gt;&lt;/p&gt;<br>      &lt;button phx-click=&quot;update_field&quot;&gt;Update Field&lt;/button&gt;<br>    &lt;/div&gt;<br>    &quot;&quot;&quot;<br>  end<br>end</pre><h3>IEX</h3><p>IEX is Elixir’s interactive shell, similar to Node.js or Python but much more powerful. IEX lets you compile your project and call any function manually.</p><p>If you have a problem with a function that performs complex logic, you can easily test it with IEX:</p><pre>❯ iex -S mix<br>iex(1)&gt; MyApp.ComplexFunctions.Fun(%User{id: &quot;user-id&quot;})</pre><p>This is incredibly convenient. You can do this on a running project.</p><p>Additionally, you can connect to a remote machine running your application, connect with IEX to a running process, test it, modify the code, and debug.</p><h3>Conclusion</h3><p>Writing my project in Elixir was a positive experience. Moving forward, I plan to write all my startup and pet projects in it. Here are several reasons why Elixir + Phoenix is one of the best technologies for general-use projects:</p><ul><li><strong>Dynamic + Strong Typing</strong>: This combination allows you to write code quickly without creating much technical debt.</li><li><strong>Real Asynchronicity</strong>: Elixir enables distributed calculations, parallel connections, periodic tasks, and eliminates the need to write separate services for complex parallel tasks.</li><li><strong>Abundance of Tools in Elixir</strong>: Elixir provides many built-in tools such as key-value stores and scalability features, which reduces the headache of needing separate message brokers or task queues.</li><li><strong>Phoenix Framework</strong>: This Django-like framework has everything built-in, plus LiveView, which is incredibly powerful. While I used to prefer building everything using the best available tools (e.g., React.js, Golang, Redis, PostgreSQL), I’ve come to realize that a $5 WordPress site can generate more revenue than complex setups with multiple microservices and no clients.</li><li><strong>Pattern Matching</strong>: After using languages with pattern matching like Elixir and Rust, it’s hard to return to Golang with its simplicity and directness. I believe that writing smart and elegant code is more important in solo projects than being direct and simple. It provides satisfaction and fuels enthusiasm, which is crucial when developing something on your own, especially considering the potential of discarding your work.</li></ul><p>If you want to reduce churn and increate conversion of your business check out my latest product <a href="https://usewidgetform.com/">Widgetform</a> 💬. It is a highly configurable widget that allows you to collect insights about your users.</p><h3>Contacts</h3><p>If you like this article don’t hesitate to connect on <a href="https://www.linkedin.com/in/sergei-suslov/">LinkedIn</a> and follow me on <a href="https://x.com/sergeysuslovnsk">Twitter</a>.</p><p><strong>Subscribe to my mailing list</strong>: <a href="https://sergedevs.com/">https://sergedevs.com</a></p><p>Checkout my latest <a href="https://usewidgetform.com/">product</a>!</p><p>Be sure to clap and follow 👏<strong>️️</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d18b6248f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/elixir-phoenix-is-a-great-choice-for-start-ups-93d18b6248f3">Elixir+Phoenix is a Great Choice for Start-Ups</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Write Transactional Database Calls in TypeScript]]></title>
            <link>https://medium.com/effective-development/how-to-write-transactional-database-calls-in-typescript-f172a8172150?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/f172a8172150</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 16:09:02 GMT</pubDate>
            <atom:updated>2024-10-28T07:49:49.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaOqDbMwAPrXkkBptilzsA.jpeg" /></figure><p>If you write web services, chances are you interact with a database. Occasionally, you’ll need to make changes that must be applied atomically — either all succeed, or none do. This is where transactions come in. In this article, I’ll show you how to implement transactions in your code to avoid issues with leaky abstractions.</p><h3>Example</h3><p>A common example is processing payments:</p><ul><li>You need to get the user’s balance and check if it’s sufficient.</li><li>Then, you update the balance and save it.</li></ul><h3>Structure</h3><p>Typically, your application will have two modules to separate business logic from database-related code.</p><h4>Repository Module</h4><p>This module handles all database-related operations, such as SQL queries. Below, we define two functions:</p><ol><li><strong>get_balance</strong> — Retrieves the user’s balance from the database.</li><li><strong>set_balance</strong> — Updates the user’s balance.</li></ol><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import postgres from &#39;postgres&#39;;<br><br>@Injectable()<br>export class BillingRepository {<br>  constructor(<br>    private readonly db_connection: postgres.Sql,<br>  ) {}<br><br>  async get_balance(customer_id: string): Promise&lt;number | null&gt; {<br>    const rows = await this.db_connection`<br>      SELECT amount FROM balances <br>      WHERE customer_id=${customer_id}<br>    `;<br>    return (rows[0]?.amount) ?? null;<br>  }<br><br>  async set_balance(customer_id: string, amount: number): Promise&lt;void&gt; {<br>    await this.db_connection`<br>      UPDATE balances <br>      SET amount=${amount} <br>      WHERE customer_id=${customer_id}<br>    `;<br>  }<br>}</pre><h4><strong>Service Module</strong></h4><p>The service module contains business logic, such as fetching the balance, validating it, and saving the updated balance.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { BillingRepository } from &#39;src/billing/billing.repository&#39;;<br><br>@Injectable()<br>export class BillingService {<br>  constructor(<br>    private readonly billing_repository: BillingRepository,<br>  ) {}<br><br>  async bill_customer(customer_id: string, amount: number) {<br>    const balance = await this.billing_repository.get_balance(customer_id);<br><br>    // The balance may change between the time of this check and the update.<br>    if (balance === null || balance &lt; amount) {<br>      return new Error(&#39;Insufficient funds&#39;);<br>    }<br><br>    await this.billing_repository.set_balance(customer_id, balance - amount);<br>  }<br>}</pre><p>In the bill_customer function, we first retrieve the user’s balance using get_balance. Then, we check if the balance is sufficient and update it with set_balance.</p><h3>Transactions</h3><p>The problem with the above code is that the balance could change between the time it is fetched and updated. To avoid this, we need to use <strong>transactions</strong>. You could handle this in two ways:</p><ol><li><strong>Embed business logic in the repository module</strong>: This approach couples business rules with database operations, making testing harder.</li><li><strong>Use a transaction in the service module</strong>: This could lead to <strong>leaky abstractions</strong>, as the service module would need to manage database sessions explicitly.</li></ol><p>Instead, I recommend a cleaner approach.</p><h3>Transactional Code</h3><p>A good way to handle transactions is to create a function that wraps a callback within a transaction. This function provides a session object that doesn’t expose unnecessary internal details, preventing leaky abstractions. The session object is passed to all database-related functions within the transaction.</p><p>Here’s how you can implement it:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import postgres, { TransactionSql } from &#39;postgres&#39;;<br><br>export type SessionObject = TransactionSql&lt;Record&lt;string, unknown&gt;&gt;;<br><br>@Injectable()<br>export class BillingRepository {<br>  constructor(<br>    private readonly db_connection: postgres.Sql,<br>  ) {}<br><br>  async run_in_session&lt;T&gt;(cb: (sql: SessionObject) =&gt; T | Promise&lt;T&gt;) {<br>    return await this.db_connection.begin((session) =&gt; cb(session));<br>  }<br><br>  async get_balance(<br>    customer_id: string, <br>    session: postgres.TransactionSql | postgres.Sql = this.db_connection<br>  ): Promise&lt;number | null&gt; {<br>    const rows = await session`<br>      SELECT amount FROM balances <br>      WHERE customer_id=${customer_id}<br>    `;<br>    return (rows[0]?.amount) ?? null;<br>  }<br><br>  async set_balance(<br>    customer_id: string, <br>    amount: number, <br>    session: postgres.TransactionSql | postgres.Sql = this.db_connection<br>  ): Promise&lt;void&gt; {<br>    await session`<br>      UPDATE balances <br>      SET amount=${amount} <br>      WHERE customer_id=${customer_id}<br>    `;<br>  }<br>}</pre><p>In this example, the run_in_session function starts a transaction and executes a callback within it. The SessionObject type abstracts the database session to prevent leaking internal details. All database-related functions now accept a session object, ensuring they can participate in the same transaction.</p><h3>Updated Service Module</h3><p>The service module is updated to leverage transactions. Here’s what it looks like:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { BillingRepository } from &#39;src/billing/billing-transactional.repository&#39;;<br><br>@Injectable()<br>export class BillingService {<br>  constructor(<br>    private readonly billing_repository: BillingRepository,<br>  ) {}<br><br>  async bill_customer(customer_id: string, amount: number) {<br>    const balance = await this.billing_repository.get_balance(customer_id);<br><br>    if (balance === null || balance &lt; amount) {<br>      return new Error(&#39;Insufficient funds&#39;);<br>    }<br><br>    await this.billing_repository.set_balance(customer_id, balance - amount);<br>  }<br><br>  async bill_customer_transactional(customer_id: string, amount: number) {<br>    return await this.billing_repository.run_in_session(async (session) =&gt; {<br>      const balance = await this.billing_repository.get_balance(customer_id, session);<br><br>      if (balance === null || balance &lt; amount) {<br>        return new Error(&#39;Insufficient funds&#39;);<br>      }<br><br>      await this.billing_repository.set_balance(customer_id, balance - amount, session);<br>    });<br>  }<br>}</pre><p>In the bill_customer_transactional function, we call run_in_session and pass a callback with the session object as a parameter, then we pass this parameter to every function of the repository that we call. This ensures that both get_balance and set_balance run within the same transaction. If the balance changes between the two calls, the transaction will fail, maintaining data integrity.</p><h3>Conclusion</h3><p>Using transactions effectively ensures your database operations remain consistent, especially when multiple steps are involved. The approach I’ve outlined helps you manage transactions without leaking abstractions, making your code more maintainable. Try implementing this pattern in your next project to keep your logic clean and your data safe!</p><h3>Contacts</h3><p>If you like this article don’t hesitate to connect on <a href="https://www.linkedin.com/in/sergei-suslov/">LinkedIn</a> and follow me on <a href="https://x.com/sergeysuslovnsk">Twitter</a>.</p><p>Here is my personal website: <a href="https://sergedevs.com/">https://sergedevs.com</a></p><p>Be sure to clap and follow 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f172a8172150" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/how-to-write-transactional-database-calls-in-typescript-f172a8172150">How To Write Transactional Database Calls in TypeScript</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Elixir/Phoenix And Struggle With Forms or UI? LiveSvelte To The Rescue]]></title>
            <link>https://medium.com/effective-development/using-elixir-phoenix-and-struggle-with-forms-or-ui-livesvelte-to-the-rescue-7933eceed68e?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/7933eceed68e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 15:05:46 GMT</pubDate>
            <atom:updated>2024-10-29T13:42:00.866Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVIOju50aIeDHAf1rsCryw.jpeg" /></figure><p>If you use Elixir/Phoenix and struggle with forms and complex UI, you are not alone. In this article I will show you how to solve these problems with LiveSvelte.</p><h3>What Is LiveSvelte</h3><p>LiveSvelte is a library that allows you to use Svelte components inside your Phoenix code not loosing any of the Phoenix jazz (SSR, state change, etc).</p><h4>Alternatives?</h4><p>LiveSvelte is not alone in this space there are alternatives to run React and Vue code.</p><h3>LiveSvelte In Action</h3><p>Basic LiveView component that has counter property in its state and increase_counter event handler that increases the counter:</p><pre>defmodule LiveviewpreviewWeb.CaseLive.Index do<br>  use LiveviewpreviewWeb, :live_view<br><br>  @impl true<br>  def mount(_params, _session, socket) do<br>    {:ok, socket |&gt; assign(counter: 0)}<br>  end<br><br>  @impl true<br>  def handle_event(&quot;increase_counter&quot;, _params, socket),<br>    do:<br>      {:noreply,<br>       socket |&gt; assign(counter: socket.assigns.counter + 1)}<br>end</pre><p>Layout for this component that renders counter variable natively and another component — SvelteCounter:</p><pre>&lt;div class=&quot;w-full&quot;&gt;<br>  &lt;div class=&quot;flex flex-col w-full gap-2 items-center justify-center mb-4&quot;&gt;<br>    &lt;div class=&quot;flex flex-col w-1/2 gap-2 justify-center text-center&quot;&gt;<br>      &lt;p class=&quot;text-lg font-bold&quot;&gt;Counter:&lt;/p&gt;<br>      &lt;p class=&quot;font-bold&quot;&gt;&lt;%= @counter %&gt;&lt;/p&gt;<br>      &lt;.button phx-click=&quot;increase_counter&quot;&gt;<br>        Increase On The Server<br>      &lt;/.button&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;w-full h-[2px] bg-gray-200 my-4&quot; /&gt;<br>  &lt;LiveSvelte.svelte<br>    name=&quot;SvelteCounter&quot;<br>    props={%{counter: @counter}}<br>  /&gt;<br>&lt;/div&gt;</pre><p>SvelteCounter component looks like this:</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br> import { Live } from &quot;live_svelte&quot;;<br><br> export let live: Live;<br> export let counter: number;<br> let local_counter: number = 0;<br><br> const increase_counter = () =&gt; {<br>    live.pushEvent(&quot;increase_counter&quot;);<br> };<br> $: increase_local_counter = () =&gt; {<br>    local_counter++;<br> };<br>&lt;/script&gt;<br><br>&lt;div class=&quot;flex flex-row w-full gap-2 justify-center&quot;&gt;<br>   &lt;div<br>    class=&quot;flex flex-col w-1/3 gap-2 justify-center align-center text-center&quot;<br>   &gt;<br>      &lt;p class=&quot;text-lg font-bold&quot;&gt;Svelte Counter:&lt;/p&gt;<br>      &lt;p class=&quot;font-bold&quot;&gt;{counter}&lt;/p&gt;<br>      &lt;button<br>         class=&quot;phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-700 py-2 px-3 text-sm font-semibold leading-6 text-white active:text-white/80&quot;<br>         on:click={increase_counter}&gt;Increase On The Server&lt;/button<br>      &gt;<br>   &lt;/div&gt;<br>   &lt;div<br>    class=&quot;flex flex-col w-1/3 gap-2 justify-center align-center text-center&quot;<br>   &gt;<br>      &lt;p class=&quot;text-lg font-bold&quot;&gt;Svelte Local Counter:&lt;/p&gt;<br>      &lt;p class=&quot;font-bold&quot;&gt;{local_counter}&lt;/p&gt;<br>      &lt;button<br>         class=&quot;phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-700 py-2 px-3 text-sm font-semibold leading-6 text-white active:text-white/80&quot;<br>         on:click={increase_local_counter}&gt;Increase Local Counter&lt;/button<br>      &gt;<br>   &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Let’s look at the code above in SvelteCounter component more closely. In the script tag we have several external variables:</p><ul><li>live — inserted in every component, holds LiveView callbacks</li></ul><pre>export type Live = {<br>    pushEvent(event: string, payload?: object, onReply?: (reply: any, ref: number) =&gt; void): number<br>    pushEventTo(phxTarget: any, event: string, payload?: object, onReply?: (reply: any, ref: number) =&gt; void): number<br><br>    handleEvent(event: string, callback: (payload: any) =&gt; void): Function<br>    removeHandleEvent(callbackRef: Function): void<br><br>    upload(name: string, files: any): void<br>    uploadTo(phxTarget: any, name: string, files: any): void<br>}</pre><ul><li>counter — LiveView state variable passed from LiveView layout of LiveviewpreviewWeb.CaseLive.Index</li></ul><p>Additionally, we have local_counter variable that holds internal component state.</p><p>In the HTML section we display two counters:</p><ul><li>Svelte Counter — counter variable passed from the LiveView component with corresponding button “Increase On The Server” that calls increase_counter function that uses live.pushEvent to send increase_counter event back to the LiveView component (LiveviewpreviewWeb.CaseLive.Index)</li><li>Svelte Counter Local — local_counter variable created within this Svelte component with corresponding button “Increase Local Counter” that calls increase_local_counter function that simply increases the local_counter variable’s value</li></ul><h3>Demo</h3><p>In the demo below you can see how the state of the LiveView component is correctly rendered in LiveView’ layout and in Svelte component, with both buttons working exactly the same keeping the local state variable untouched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jdh9nWafM3_BAw3gTJKCQ.gif" /></figure><p>Thank you for reading!</p><p>👏Don’t forget to clap if you liked the article👏</p><h3>Contacts</h3><p>If you like this article don’t hesitate to connect on <a href="https://www.linkedin.com/in/sergei-suslov/">LinkedIn</a> and follow me on <a href="https://x.com/sergeysuslovnsk">Twitter</a>.</p><p>Here is my personal website: <a href="https://sergedevs.com/">https://sergedevs.com</a></p><p>Be sure to clap and follow 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7933eceed68e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/using-elixir-phoenix-and-struggle-with-forms-or-ui-livesvelte-to-the-rescue-7933eceed68e">Using Elixir/Phoenix And Struggle With Forms or UI? LiveSvelte To The Rescue</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building better software in Go with DI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/effective-development/building-better-software-in-go-with-di-faf8301a9f84?source=rss----5844d61cf31b---4"><img src="https://cdn-images-1.medium.com/max/1502/1*e65utKdZdF07nPWJkqxGfA.png" width="1502"></a></p><p class="medium-feed-snippet">Using Dependency Injection to follow SOLID principles</p><p class="medium-feed-link"><a href="https://medium.com/effective-development/building-better-software-in-go-with-di-faf8301a9f84?source=rss----5844d61cf31b---4">Continue reading on Effective Development »</a></p></div>]]></description>
            <link>https://medium.com/effective-development/building-better-software-in-go-with-di-faf8301a9f84?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/faf8301a9f84</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 04:40:46 GMT</pubDate>
            <atom:updated>2020-07-28T04:40:46.741Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How To Write Modern React App Using gRPC And Envoy]]></title>
            <link>https://medium.com/effective-development/how-to-write-modern-react-app-using-grpc-and-envoy-a9d9a4f2785e?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/a9d9a4f2785e</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 13:10:55 GMT</pubDate>
            <atom:updated>2020-06-05T13:10:55.727Z</atom:updated>
            <content:encoded><![CDATA[<h4>Save your time, use gRPC in you next frontend app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dg-CEFVxCtizENgbVoLbBA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@punttim">Tim Gouw</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><blockquote>If you lose a bunch of time every time, adjusting your client app to the backend REST API, this article is here to save you.</blockquote><h3>What is wrong?</h3><p>One of the big problems with REST API is a specification. If you develop a frontend app in React/Angular/Vue, most of the time you use an API. And most of the time, this API is written by another developer.</p><p>The specification for this API must be elaborated in advance, in order to develop client-side and server-side in parallel. Elaborated specification is hard to modify. Because you have to notify all other developers about changes, not to mention the probability of mistypes in an implementation.</p><p>Here are two main problems:</p><ul><li>Complexity of modification</li><li>The probability of mistypes in an implementation</li></ul><h3>Our savior gRPC</h3><p><a href="https://grpc.io/">GRPC</a> is an open-source universal RPC framework. It is used to build communications between services in a microservice architecture. This technology uses <a href="https://developers.google.com/protocol-buffers">Protobuf</a> as a serializer.</p><p>GRPC has many various advantages and features. We, as frontend developers, care only about these two for now:</p><ul><li>Code generation</li><li><a href="https://developers.google.com/protocol-buffers">Proto</a> files</li></ul><h4>Code generation</h4><p>This feature extinguishes the probability of mistypes on the implementation stage. There are tools to generate concrete methods and interfaces in multiple programming languages. This feature makes possible implementation of business logic 100% accurate according to a proto specification.</p><h4>Proto files</h4><p>Proto file is a single source of truth for an API. They are easy to modify, and can be stored near to project files in order to keep a version history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3ukkkdaQcRYck7yD_Bsug.png" /><figcaption>.proto file example</figcaption></figure><h3>Building an Example</h3><p>Below, we will try to build a frontend app using gRPC. This pretty simple app will be able to sum two numbers. The server from the <a href="https://medium.com/effective-development/building-grpc-api-in-nest-with-typescript-95e1915abc15"><strong>previous article</strong></a> will be used as a backend to provide an API for our client-side application.</p><p><a href="https://github.com/sergey-suslov/gRPC-nest-js-ar">Server code can be found here</a></p><h3>Interface</h3><p>Let’s start with UI. And build a very simple interface with two input fields for number A and number B. Also, we have to add a button to trigger API calls and a result field.</p><p>It will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*pvCiIIAPiJSVyaHjq7cQww.png" /></figure><p>Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b57d339a9eca1c190bfe6dd11a866b49/href">https://medium.com/media/b57d339a9eca1c190bfe6dd11a866b49/href</a></iframe><h3>Code generation</h3><p>We built the UI part of the application. It’s time to get to work on code generation. We will use the .proto file of the backend application. It can be found <a href="https://github.com/sergey-suslov/gRPC-nest-js-ar/blob/master/api/api.proto">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62877c29de60c3ff317eff07e261e6a4/href">https://medium.com/media/62877c29de60c3ff317eff07e261e6a4/href</a></iframe><p>We will use <strong>GatewayService</strong> and its method <strong>Add,</strong> to sum the numbers A and B.</p><p>To generate some code from this .proto you should have <a href="https://github.com/protocolbuffers/protobuf/releases"><strong>protoc</strong></a><strong> </strong>installed on your computer. We will use <a href="https://github.com/grpc/grpc-web"><strong>grpc-web</strong></a><strong> </strong>plugin in order to generate typescript code for usage in a browser.</p><p>Generated files may not meet the rules of your eslint configuration. In this case, you can insert /* eslint-disable */ at the beginning of every generated file. I wrote a script for typescript code generation with insertion of the rule/* eslint-disable */:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245ecb40eedf9246eb7b7f9293b5eb1d/href">https://medium.com/media/245ecb40eedf9246eb7b7f9293b5eb1d/href</a></iframe><p>This script generates files using <strong>protoc</strong>. The .proto file is located at src/proto/sum.proto.</p><h3>API calling</h3><p>From now, when all required files are generated and the UI is ready, we can start API calling implementation.</p><p>Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b72afba90d09703d2170bacd48ec5cd6/href">https://medium.com/media/b72afba90d09703d2170bacd48ec5cd6/href</a></iframe><p>On line 12 I create <strong>gatewayServiceClient</strong>, from the generated sum_pb.ts,<strong> </strong>to call the <strong>Add </strong>method of the <strong>GatewayService</strong>.</p><p>On line 15 I create <strong>AddRequest</strong>, then set A and B numbers.</p><p>Unary call methods are created in callback style. In order to work with the API in promise style, I create <strong>sumNumbers</strong> function using <strong>promisify</strong>.</p><p>On line 19 I perform an API call to the <strong>GatewayService </strong>and get the result object.</p><h3>API call integration into the UI</h3><p>This API calling style is an anti-pattern. But for educational purposes, I thought it would be acceptable.</p><p>I extended the App component with the API call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d31ae7ce92223456af633a13fc375a/href">https://medium.com/media/e6d31ae7ce92223456af633a13fc375a/href</a></iframe><p>On line 7 I create a callback that is used as an onClick handler for the button Sum. The handler takes the value of A and B input fields and calls <strong>sum</strong>. When the call ended, it sets the result.</p><h3>Envoy</h3><p>Unfortunately, the browser API is not enough to fully implement gRPC on the client-side. To get around this restriction Envoy server can be used.</p><p>Envoy can be used as a proxy server. And it has built-in support for transforming web gGRPC to the server-friendly gRPC.</p><p>I use docker-compose to set up a local environment. Here is my setup for Envoy container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*j8C7xG3Mi57SvCtpKbRUEA.png" /></figure><p>So you have to create docker-compose.yml with config directory. Then put Dockerfile-gateway and gateway-envoy.yaml files into the config directory.</p><p>Here is docker-compose.yml :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f7ba5b9c87b2b5aee5003a69a9ef2d/href">https://medium.com/media/c3f7ba5b9c87b2b5aee5003a69a9ef2d/href</a></iframe><p>That is Dockerfile-gateway :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df8c41a6aeb4416effe446db029fa6a0/href">https://medium.com/media/df8c41a6aeb4416effe446db029fa6a0/href</a></iframe><p>And, finally, gateway-envoy.yaml :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a79782a015810df3416bb2c6cdef004a/href">https://medium.com/media/a79782a015810df3416bb2c6cdef004a/href</a></iframe><p>This Envoy configuration contains <strong>envoy.grpc_web </strong>HTTP filter, that transforms gRPC-web into server-friendly gRPC.</p><p>Now you can run this Envoy configuration with this command:</p><p>docker-compose up — build -d</p><p>When the Envoy server is running, it will proxy every response from the port <em>8080 (the client app should send in here) </em>to the <em>50051 (the server app should listen to this port)</em> port.</p><h3>Demonstration</h3><p>When the Envoy server is running, you can start the <a href="https://github.com/sergey-suslov/gRPC-nest-js-ar">backend services</a> and the frontend application. Enter two numbers into the fields and press Sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*pvCiIIAPiJSVyaHjq7cQww.png" /></figure><p>The result will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*msVgDKeCcbc_CJjMfJQEGA.gif" /></figure><p>I hope it was helpful for you.</p><p>🚀 Check out the <a href="https://medium.com/effective-development/building-grpc-api-in-nest-with-typescript-95e1915abc15">First Part — Building gRPC API in Nest with Typescript</a>.</p><p>💻 Subscribe on <a href="https://medium.com/effective-development">Effective Development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9d9a4f2785e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/how-to-write-modern-react-app-using-grpc-and-envoy-a9d9a4f2785e">How To Write Modern React App Using gRPC And Envoy</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Stopped Worrying and Loved Vim]]></title>
            <link>https://medium.com/effective-development/how-i-stopped-worrying-and-loved-vim-51e89fc2d15f?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/51e89fc2d15f</guid>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[ide]]></category>
            <category><![CDATA[editor]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 14:27:18 GMT</pubDate>
            <atom:updated>2020-06-03T00:43:04.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCNATa3bXX6torARFsXVmg.png" /></figure><p>Most likely, if you are reading this, you can’t grasp, why would someone ever use Vim as a primary code editor? And if someone really does use it, there must be a good reason. I was in your shoes once. When I found out that someone really preferred Vim as their code editor over an IDE, a lot of questions started bothering me.</p><h3>Beginning</h3><p>I knew about Vim’s existence since college, but I could not imagine that it could be something suitable for coding. I thought of Vim as a last resort — as a tool for minor changing text somewhere on a server via ssh. Nothing more.</p><h3>Excitement</h3><p>Things changed when I heard that one of my colleges used Vim for coding. It is important to clarify that the colleague was a very skillful developer with a more than ten years experience in production. I was curious about that and couldn’t imagine that Vim was suitable for coding. So I asked him why he was using Vim instead of Jetbrains IDE or VSCode. IDEs have so many useful tools and features.</p><blockquote>I have the most useful of them on my Vim configuration. Also, most IDEs are so resource-intensive to provide all the features that I usually don’t use. When I use a code editor 8 hours every day, I want to be able to configure every single part of it and then keep it. — Developer</blockquote><p>I thought about his words and tried to configure my first Vim that evening. The feeling of coding without a mouse in a fully customizable environment was something new and attractive.</p><h3>Disappointment</h3><p>Unfortunately, I used the very first Typescript Vim config that I was lucky to find on the Internet instead of configuring one on my own.</p><p>Of course, it was not the best one. I didn’t know how to work with that configuration. It was slow and looked unpleasant — not how I wanted it to look. That is how my typical day was like: I started coding using Vim, my productivity dropped, I got disappointed, I returned to VSCode. Repeat. My overall efficiency dropped. I had to use third-party tools to replace some of the IDE’s features.</p><p>After a week of constant tries, I gave up and returned to VSCode.</p><h3>Second Chance</h3><blockquote>“He remembered what the old man had said” — The Alchemist</blockquote><p>A month later, I remembered that my colleague had said earlier that Vim was the tool you could configure as you liked. So, I decided to give it a second chance and make my own Vim configuration this time.</p><blockquote>I started coding a simple app, and every time, I felt that I needed something. And I got that “something” after configuring or adding plugins.</blockquote><p>I strongly recommend you to do the same before looking up for someone else’s configuration.</p><p>After I had configured Vim as I liked it, I started working in it permanently. It was hard. There were things like multi cursor, or integrated git that I missed. But Vim always ended up having a way to do those things.</p><blockquote>If you find all these problems that bother you while coding in Vim and then solve them, you will love it.</blockquote><h3>Things that irritated me</h3><p>Here, I will give you a short description of things that were bothering me at the beginning. And the solutions I have found.</p><h4>File tree</h4><p>It sounds silly, but you don’t need a file tree most of the time. It is useful for manipulating files of a project, creation, removing, etc.</p><p>Using an IDE, I repeatedly found myself jumping between files thoughtlessly. When I was accustomed to a permanent switching between files, I was losing my focus. I stopped thinking about the next move I have to do and started clicking on tabs.</p><blockquote>Programming is about thinking not writing. Think, then write and not vice versa.</blockquote><p>Vim has a built-in tool for viewing and manipulating files. It is called explorer. Or you can use <a href="https://github.com/preservim/nerdtree">NERDtree</a>, in case you want some more features. But most of the time, I prefer navigating using file search (I use <a href="https://github.com/kien/ctrlp.vim">ctrlp</a> plugin), jumping using go-to-definition/go-to-reference features, or jumplist Ctrl-O/Ctrl-I.</p><h4>Buffers</h4><p>Vim has a thing that is called buffers. They are files that you opened, and that were loaded into your Vim memory. You can use them to navigate as well. They are like tabs in VSCode or an IDE. To work with them efficiently you can use <a href="https://github.com/jeetsukumaran/vim-buffergator">vim-buffergator</a> plugin or configure key mappings.</p><h4>Code Completion</h4><p>That is one of the main reasons people use IDEs. But for most popular programming languages, at this time, language servers exist. In a word, LSP (Language Server Protocol) is a tool that can provide code analysis. And it is editor agnostic. You only need a client to work with LSP. In the Vim world, you can use <a href="https://github.com/neoclide/coc.nvim">coc.nvim</a>. It is an Intellisense engine that can provide Vim with all the code analysis that VSCode can. You can install a plugin for the language you use and <a href="https://github.com/neoclide/coc.nvim">coc.nvim</a> will do the rest.</p><p>Code completion looks like this in my case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDIob4s3cMGOzi_vAqe6mg.png" /><figcaption>Nvim completion using coc.nvim TSC</figcaption></figure><h4>Searching</h4><p>Vim has a built-in tool for searching, but I prefer using <a href="https://github.com/junegunn/fzf.vim">fzf.vim</a>. It is a wrapper for the fzf search tool. I use it with <a href="https://github.com/BurntSushi/ripgrep">ripgrep</a> search tool. This thing is written in rust and it is really fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tRZcvKjZxASzqahwBVoEQ.png" /></figure><h4>Git</h4><p>There is a really good tool for working with git from Vim. It is called <a href="https://github.com/tpope/vim-fugitive">vim-fugitive</a>. This tool is a wrapper for git commands, and it can provide all you need to work with git.</p><p>But, if you are a casual user, like me, check out an awesome tool called <a href="https://github.com/jesseduffield/lazygit">lazygit</a>. It is a terminal-UI tool for git manipulations. And there is a plugin to integrate <a href="https://github.com/jesseduffield/lazygit">lazygit</a> into Vim — <a href="https://github.com/kdheepak/lazygit.vim">lazygit.vim</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVkdc3Nk54_vckduTU1Yww.png" /><figcaption>lazygit integrated into Vim</figcaption></figure><p>This tool will let you work with git and make things like cherry-picking, merging, etc. in the usual way.</p><h3>Summary</h3><p>If you write code on a daily basis, I definitely recommend you trying Vim. Start with vimtutor, and then try coding.</p><p>It’s hard to start, but if you go through it, you will love Vim.</p><p>Some articles that helped me:</p><ul><li><a href="https://medium.com/actualize-network/how-to-learn-vim-a-four-week-plan-cd8b376a9b85">How To Learn Vim: A Four Week Plan</a></li><li><a href="https://medium.com/@schtoeffel/you-don-t-need-more-than-one-cursor-in-vim-2c44117d51db">You don’t need more than one cursor in vim</a></li></ul><p>P.S. I use Neovim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e89fc2d15f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/how-i-stopped-worrying-and-loved-vim-51e89fc2d15f">How I Stopped Worrying and Loved Vim</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building gRPC API in Nest with Typescript]]></title>
            <link>https://medium.com/effective-development/building-grpc-api-in-nest-with-typescript-95e1915abc15?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/95e1915abc15</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[nest]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 14:27:00 GMT</pubDate>
            <atom:updated>2020-06-02T14:27:00.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBW6mryj24q6KYjboM0TZA.png" /></figure><p>You must have heard about gRPC and its advantages. Here, I will show you how to build a modern API with <strong>Nest.js</strong> and <strong>gRPC</strong> in typescript.</p><h3>Why gRPC is cool</h3><p>Why use gRPC? It has a ton of advantages like performance, code generation, streaming, etc. But, for me, the main one is a strict specification. GRPC forces you to write .proto files that describe your API. This feature let me and my team retain a lot of time. Proto-files are specifications that can be written before the development start, and it may be a single source of truth for API implementors.</p><h3>Overview</h3><p>In the first part we will build an API using gRPC as a main communication mechanism.</p><h3>API specification</h3><p>Let’s start with composing a .proto file. In this article, API will be able to sum two numbers. The .proto files consist of two services. The first one is a <strong>GatewayService</strong> service. The service will be an entry point to the backend API, it can retrieve requested, by client, information from other services. The second service is a <strong>SummatorService</strong>. This one will provide a Sum method, that sum all numbers it receives.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52759fcbcd4e222771b0516f0f8efded/href">https://medium.com/media/52759fcbcd4e222771b0516f0f8efded/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe9629119ea24f3fb83a5684b4d6378f/href">https://medium.com/media/fe9629119ea24f3fb83a5684b4d6378f/href</a></iframe><h3>Summator</h3><p>This service must provide a function called Sum, that can sum all the given numbers and return the result. Let’s start with defining the bootstrap function to start up the app.</p><h4>Bootstrap</h4><p>To start a microservice in Nest.js, it has to be configured with a transport type, an URL it will be host on, a path to a .proto file with a specification of the service, and a package name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92c516b5366456efe82d6ed871bd2779/href">https://medium.com/media/92c516b5366456efe82d6ed871bd2779/href</a></iframe><h4>Controller</h4><p>The controller, in our case, contains only one method called Sum. To make a method a gRCP handler, the GrpcMethod annotation should be used with parameters of a name of a service (SummatorService) in a .proto specification file and a name of a method (Sum) that is intended to be implemented.<br> sum method sum all the numbers from the request:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d93695c2aeb7548090334ab9e03d47c/href">https://medium.com/media/6d93695c2aeb7548090334ab9e03d47c/href</a></iframe><p>The Summator service is ready. Let’s move on to the Gateway service.</p><h3>Gateway</h3><p>The Gateway service is the front part of the whole API. The part which communicates with the outer world. The service will use gRPC to communicate with the client as well as with the Summator service.</p><h4>Bootstrap</h4><p>The service configuration is the same as for the Summator service except the url field. The url’s port differs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95f505826be045a766e5e5400740602/href">https://medium.com/media/a95f505826be045a766e5e5400740602/href</a></iframe><h4>Module</h4><p>To get access to the Summator service client object, it has to be registered first. Client module registration is performed using the register method of the ClientsModule class of the @nestjs/microservices package. It requires a name (any name, used in injection), a transport (GRPC in this case), a path to the .proto specification file of a service that is being injected, and an URL to the service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50f3c32296d6ee0cbdea6478dbe9e446/href">https://medium.com/media/50f3c32296d6ee0cbdea6478dbe9e446/href</a></iframe><p>Now, we can inject a ClientGrpc instance using <em>SUMMATOR_PACKAGE</em> as a name of an entity being injected.</p><h4>Controller</h4><p>In this case, the controller will provide only one method Add. This method should take a and b numbers from the request body and call the sum method of the Summator service client instance, that has been configured in the module file.<br>Unfortunately, all interfaces of requests and gRPC clients that are used are left to define manually. For example, the Add method’s request type is defined in its .proto file, but the request’s interface (AddRequest) in the controller, still should be defined manually. In any big project, you should use tools to generate such interfaces automatically, to avoid all kinds of typos. <a href="https://github.com/protobufjs/protobuf.js">Protobuf.js</a> is a good one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dffc32f853aa5dc780f6b8ddf715cdf/href">https://medium.com/media/1dffc32f853aa5dc780f6b8ddf715cdf/href</a></iframe><p>In the constructor, ClientGrpc is injected, which was imported in the module file earlier. On module initialization, we get a SummatorServiceClient object from the injected ClientGrpc.</p><p><strong>It’s important to clarify</strong>, that the SummatorServiceClient interface, is defined as a separate interface manually. It maps .proto Summator service into typescript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d99608c108dc762502dc13881fbefcbc/href">https://medium.com/media/d99608c108dc762502dc13881fbefcbc/href</a></iframe><p>Mostly, Nest.js gRPC methods return rxjs Observables. You can work with them reactively, or cast into a promise using toPromise method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eunLIrxj-IOMrCgOakF1Ig.png" /><figcaption>Screenshot from BloomRPC. Result.</figcaption></figure><h3>Summary</h3><p>I hope, this article helps you to get how easy and useful gRPC is. I totally recommend you to try it out and dive into it.</p><p>In <strong>part two</strong>, I will show you how to integrate a gRPC API with the client app in <strong>React</strong>.</p><p><a href="https://github.com/sergey-suslov/gRPC-nest-js-ar">Github Repository with Source Code</a></p><p>Part Two — <em>Will be here soon</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95e1915abc15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/building-grpc-api-in-nest-with-typescript-95e1915abc15">Building gRPC API in Nest with Typescript</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go auth with JWT]]></title>
            <link>https://medium.com/effective-development/https-medium-com-sergey-suslov-go-auth-api-using-jwt-47a4ef91f158?source=rss----5844d61cf31b---4</link>
            <guid isPermaLink="false">https://medium.com/p/47a4ef91f158</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Sergei]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 14:25:14 GMT</pubDate>
            <atom:updated>2019-11-26T14:16:55.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1RqeEgX2teHulo6P0w_GLQ@2x.jpeg" /></figure><h3>What will we be building?</h3><p>In this article, we will try to build a simple Golang API for authorization and authentication. We will use JWT to store a user to reduce database calls and <a href="https://echo.labstack.com/">Echo</a> framework to build routing. PostreSQL and <a href="https://github.com/jackc/pgx">pgx</a> will be used to handle the database part.</p><h3>Building</h3><p>So, let’s start with designing the service API. We need an authentication route, which compare given login and password with ones in the database. If login and password match we will generate a JWT token for a user and store it in the cookies.<br>To authorize a user, we have to register one. So, we will also make a registration API.</p><h4>Database</h4><p>So, let’s create a user table in the database. We will use <a href="https://github.com/jackc/tern">tern</a> package to perform migration. Firstly, we have to specify a config file with DB credentials in the migration directory and call it tern.conf:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92ae070ff67759c6e57d3a6d22269ef1/href">https://medium.com/media/92ae070ff67759c6e57d3a6d22269ef1/href</a></iframe><p>Secondly, we need to specify the user’s migration itself. Tern package can generate migration file for you. Use tern new create_users command to generate file and fill it with user table creation code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/290291a98e30ae6475ecee6e530fbc2b/href">https://medium.com/media/290291a98e30ae6475ecee6e530fbc2b/href</a></iframe><p>Finally, we can perform migration using command tern migratein the migration directory.</p><p>Now, we need to write some code that will let us connect to the DB and perform queries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e394e38e47452151bb2eb8e8b061861/href">https://medium.com/media/6e394e38e47452151bb2eb8e8b061861/href</a></iframe><h4>API</h4><p>Let’s write the routing skeleton using Echo framework. We need to create new Echo instance and define an API group(with name /v1for example). We also pass the group to InitAPI method which we will consider later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82de7387ef8f5a609c38b7210a6c568b/href">https://medium.com/media/82de7387ef8f5a609c38b7210a6c568b/href</a></iframe><p>Now, we can initialize the v1 api handlers, using Echo group that we passed to InitAPIbefore. users.SignUpand users.Authare controllers from the user package that we consider next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bd1b8dba4e2ab6b73a3484a3fc848b8/href">https://medium.com/media/6bd1b8dba4e2ab6b73a3484a3fc848b8/href</a></iframe><h4>SignUp</h4><p>While registration, we need two additional functions. First is a function, that performs searching in the users table by login. The function is used to validate uniqueness of the given login. Second is a function, to create a user in users table by given parameters. We will define these functions in the user model later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72896b38d9aec8ab9adae7101dea352f/href">https://medium.com/media/72896b38d9aec8ab9adae7101dea352f/href</a></iframe><p>Let’s define the models package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d28f35df68207d5489e5a48793dfeb22/href">https://medium.com/media/d28f35df68207d5489e5a48793dfeb22/href</a></iframe><h4>Auth</h4><p>Auth controller try to find the user by given login and compare passwords if user will be found. If user was found and password matched, it will created JWT token and add it to cookies. Let’s add the controller’s code to the users package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e941c406e6eacd4e0f24b56c305adf7b/href">https://medium.com/media/e941c406e6eacd4e0f24b56c305adf7b/href</a></iframe><p>We have to add two additional functions in the models package. First is the models.VerifyPassword function, that compare a given password with user’s hashed password. Second is the user.GetJWT function, that can create JWT token for a user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2501b09b75e74439fcc30624f27685c0/href">https://medium.com/media/2501b09b75e74439fcc30624f27685c0/href</a></iframe><p>Now, a JWT token contains the user model and we can extract it from the token. Let’s write the middlewares, one that can get a user from a JWT token and another one that will check the token and return Not Authorizederror if it is invalid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5f47f5de64fa8951933fb9f11e139b/href">https://medium.com/media/3d5f47f5de64fa8951933fb9f11e139b/href</a></iframe><p>Now, we can get a user from the echo.Context in next handlers with code like this user:= e.Get(”user”).(*models.UserClaims). For example, GetProfile handler, that returns the dencoded user:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf64b196ebf12af9c4f9f1e18a80f4b/href">https://medium.com/media/dcf64b196ebf12af9c4f9f1e18a80f4b/href</a></iframe><h3>Improvements</h3><p>You can generate two tokens. First one to store a user’s data and user’s authorization, this token must expire in a short time span. Second token is a refresh token, which you can use to generate new token pair. Refresh token lifetime must be longer, so a user will be able to refresh tokens and continue using your API. Authorization token’s lifetime is short due to the fact that the token is sent to a server along with each request and can be intercepted. So it needs to be refreshed regularly.</p><p><a href="https://github.com/sergey-suslov/go-auth-jwt">You can find the code of this project here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a4ef91f158" width="1" height="1" alt=""><hr><p><a href="https://medium.com/effective-development/https-medium-com-sergey-suslov-go-auth-api-using-jwt-47a4ef91f158">Go auth with JWT</a> was originally published in <a href="https://medium.com/effective-development">Effective Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>