<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sagar Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Sagar Shrestha on Medium]]></description>
        <link>https://medium.com/@sgstlife?source=rss-478e5829a8d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BTTAJm1bWiIxEnzB</url>
            <title>Stories by Sagar Shrestha on Medium</title>
            <link>https://medium.com/@sgstlife?source=rss-478e5829a8d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:02:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sgstlife/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Basic CRUD Operation in Ruby on Rails]]></title>
            <link>https://sgstlife.medium.com/basic-crud-operation-in-ruby-on-rails-faf9c6112dc3?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf9c6112dc3</guid>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[simple]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 15:18:03 GMT</pubDate>
            <atom:updated>2023-11-05T15:18:03.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zak8ECHT5JwCFmlkYofzpQ.png" /></figure><p>This tutorial will cover the basic operation we need to know for developing an application in Ruby on Rails in MVC and step-by-step guide on how to do it.</p><p><strong>MVC</strong><br>A software design pattern called Model-View-Controller divides the program logic into three interrelated pieces and is specifically suited for creating user interfaces.</p><ul><li><em>Models</em> — It is a place for handling business logic and all code related to database for validating data is done here. This layer is in charge of upholding the data and making sure it is accessible and intact.</li><li><em>Views — </em>It is template files typically formed of a mix of HTML and Ruby code. It renders the data from the models and handle logic for presentation for users.</li><li><em>Controller</em> — It is an intermediate module between models and view that controls flow of the application. They handle the requests and responses. Sometimes thought of as the application’s brains, the controller keeps everything running smoothly and in unison.</li></ul><p><strong>Let’s start with the application.<br></strong> We will not be covering about the installation process of ruby on rails.</p><pre>rails new blog   #setting up the project blog<br>bin/rails server        # starting up the server<br>  </pre><p>Now, Create a model Article</p><pre>bin/rails generate model Article title:string body:text</pre><p>It will result on a file <em>article.rb </em>in path<em> app/models and a file in db/migrate. </em>First one of our model that handle communication with database and second one is about the migration with database.</p><p>Adding controller and view</p><pre>bin/rails generate controller Articles index show new edit</pre><p>It will add controller, views and helper into our application. Since we are working on CRUD application, we need to add index, show ,new and edit views and controller to the application. This line of code will automatically create methods on the controller and add new view files.</p><p>Since we are working on CRUD, we can replace the routes with shortcut in <em>config/routes.rb. </em>Additionally, you can see the routes using this command<em> rails routes . </em>It will list all the routes for you.</p><pre>  #get &#39;articles/index&#39;<br>  #get &#39;articles/show&#39;<br>  #get &#39;articles/new&#39;<br>  #get &#39;articles/edit&#39;<br>  resources :articles</pre><p><strong>Understanding Migration</strong></p><pre>class CreateArticles &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :articles do |t|<br>      t.string :title<br>      t.text :body<br><br>      t.timestamps<br>    end<br>  end<br>end</pre><p>This is migration file we can see on<em> migrate/[date_time]_create_articles.rb . </em>It represents the changes in database structure so that it can be applied to our database schema. Since our code is about creating a table,<em> rake db:migrate </em>will create a table on our database. Then we can see schema file on <em>config</em> folder.</p><p>Now Let’s add few data to our database from seeds at <em>config/db/seeds.rb</em> . Then, we can seed the data with command <em>rake db:seed</em></p><pre>Article.create(title: &#39;Heading!!&#39;, body: &#39;This is an article about my webpage&#39;)<br>Article.create(title: &#39;Heading2!!&#39;, body: &#39;This is an article about my webpage2&#39;)</pre><p><strong>CRUD</strong></p><p>CRUD stands for Create Read Update Delete. Let’s start with reading the operations. For it we need following alterations.</p><p>On <em>app/views/articles/index.html.erb</em></p><pre>&lt;h1&gt;Articles&lt;/h1&gt;<br><br>&lt;ul&gt;<br>  &lt;% @article.each do |article| %&gt;<br>    &lt;li&gt;&lt;%= link_to article.title, article_path(article)  %&gt;&lt;/li&gt;<br>  &lt;% end %&gt;<br>&lt;/ul&gt;</pre><p>Similary on <em>app/controller/articles_controller.rb</em></p><pre>...<br>  def index<br>    @article = Article.all<br>  end<br>...</pre><p>It should look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*EXQ_lBPBS0CA5G1huEgTDg.png" /></figure><p>It is similar for Create, Read one, Update and delete. I’ll list all the files with an explanation on code.</p><p>Controller file</p><pre>class ArticlesController &lt; ApplicationController<br>  def index #it will list all the article<br>    @article = Article.all<br>  end<br><br>  def show #it will show all the articles with corresponding to it&#39;s id<br>    @article = Article.find(params[:id])<br>  end<br><br>  def new  #instantiating article so that POST operation can be done<br>    @article=Article.new<br>  end<br><br>  def edit # it will fetch one article with the id. It is just for showing the content<br>    @article = Article.find(params[:id])<br>  end<br><br>  def update # It will find article and update the article<br>    @article = Article.find(params[:id])<br>    @article.update(article_params)<br><br>    redirect_to article_path(@article)<br>  end<br><br>  def create #Create new article i.e. POST Operation<br>    article = Article.create(article_params)<br><br>    redirect_to articles_path<br>  end<br><br>  def destroy # it will find the article and delete it i.e. DELETE operation<br>    @article = Article.find(params[:id])<br>    @article.destroy<br><br>    redirect_to articles_path # redirect to index<br>  end<br><br>  private<br>  def article_params #The .permit method is used to specify which attributes of the &quot;article&quot; parameters are allowed to be updated. In this case, it allows the &quot;title&quot; and &quot;body&quot; attributes to be updated and rejects any other attributes not listed here.<br>    params.require(:article).permit(:title, :body)<br>  end<br>end</pre><p>Similarly for views</p><p><em>edit.html.erb</em></p><pre>&lt;h3&gt;Update Article &lt;/h3&gt;<br>&lt;%= form_with model: @article do |form| %&gt;<br>  &lt;%= form.text_field :title, placeholder: &quot;title&quot; %&gt;<br>  &lt;%= form.text_field :body, placeholder: &quot;body&quot; %&gt;<br>  &lt;%= form.submit %&gt;<br>&lt;% end %&gt;</pre><p><em>index.html.erb</em></p><pre>&lt;h1&gt;Articles&lt;/h1&gt;<br><br>&lt;ul&gt;<br>  &lt;% @article.each do |article| %&gt;<br>    &lt;li&gt;&lt;%= link_to article.title, article_path(article)  %&gt;&lt;/li&gt;<br>  &lt;% end %&gt;<br>&lt;/ul&gt;</pre><p><em>new.html.erb</em></p><pre>&lt;h3&gt;Create an Article&lt;/h3&gt;<br>&lt;%= form_with model: @article do |form| %&gt;<br>  &lt;%= form.text_field :title, placeholder: &quot;title&quot; %&gt;<br>  &lt;%= form.text_field :body, placeholder: &quot;body&quot; %&gt;<br>  &lt;%= form.submit %&gt;<br>&lt;% end %&gt;</pre><p><em>show.html.erb</em></p><pre>&lt;h1&gt;&lt;%= @article.title %&gt;&lt;/h1&gt;<br><br>&lt;%= @article.body %&gt;<br>&lt;%= button_to &#39;Remove&#39;, article_path(@article), method: &#39;delete&#39;, data: { confirm: &#39;Are you sure?&#39; } %&gt;<br><br>&lt;-- Last line is for delete operation&gt;</pre><p>It should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*avfHPoHSQXAnG2_ylxaCFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*IH8Q_xsEplbBn--xQ8SEWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*8bygjyp703_xYekJaiqijg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*buV8UQfOeoDyoqPDsIsxOw.png" /><figcaption>CRUD operation</figcaption></figure><p>Now let’s refractor the controller</p><pre>class ArticlesController &lt; ApplicationController<br>  before_action :find_one, only: [:show, :edit, :update, :destroy] # this allows to add  find_one in the beginning of the methods mentioned<br>  def index<br>    @article = Article.all<br>  end<br><br>  def show<br>  end<br><br>  def new<br>    @article=Article.new<br>  end<br><br>  def edit<br>  end<br><br>  def update<br>    @article.update(article_params)<br><br>    redirect_to article_path(@article)<br>  end<br><br>  def create<br>    article = Article.create(article_params)<br><br>    redirect_to articles_path<br>  end<br><br>  def destroy<br>    @article.destroy<br><br>    redirect_to articles_path<br>  end<br><br>  private<br>  def article_params<br>    params.require(:article).permit(:title, :body)<br>  end<br><br>  def find_one<br>    @article = Article.find(params[:id])<br>  end<br>end</pre><p>Hurray!! CRUD operation is complete. You can check out the code in <a href="https://github.com/Znerf/blog-ruby">Github</a> or you want to connect then you can go to <a href="http://sagarshrestha1999.com.np/">my website</a> and say Hi!</p><p>Happy Coding !! 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf9c6112dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Go: Flexibility and Reusability]]></title>
            <link>https://articles.readytowork.jp/generics-in-go-flexibility-and-reusability-49207f7b0994?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/49207f7b0994</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 16:41:05 GMT</pubDate>
            <atom:updated>2023-08-16T16:41:05.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsr6z48qd4iQO5OC0sMrqA.png" /></figure><p>Generics, a long-awaited feature of the Go programming language, debuted with the release of Go 1.18. This represents a significant advancement in Go’s evolution, allowing developers to write more flexible and reusable code. We’ll look at the concept of generics in Go, how they work, and how they improve the language’s capabilities in this article.</p><p>Generics are a programming language feature that allows developers to write code that can be reused across multiple types. Go has long been known for its minimalism and simplicity, but it has lacked the ability to create truly generic functions and data structures. Because of generics, Go programmers can now write functions, interfaces, and data structures that operate on multiple types without sacrificing type safety.</p><p><strong>Why Generics in Go</strong></p><p>One of the main reasons for introducing generics in Go was to improve code reuse and eliminate code duplication. Previously, to achieve generic-like behavior, developers had to rely on interface (the empty interface) and type assertions. This approach, however, frequently resulted in less readable and type-safe code.</p><p>Generics in Go allow us to define functions and data structures that can work with a variety of types while maintaining type safety. This improves not only code readability but also maintainability by reducing the need for boilerplate code.</p><p><strong>Generic Functions</strong></p><p>Let’s look at an example to see how to write generic functions in Go. Consider the following scenario: we want to write a function that returns the highest value from a given slice. This is how we can do it with generics:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func Max[T int64 | float64](values []T) T {<br>    max := values[0]<br>    for _, value := range values {<br>        if value &gt; max {<br>            max = value<br>        }<br>    }<br>    return max<br>}<br><br>func main() {<br>    fmt.Println(Max([]int64{1, 2, 3})) // 3<br>    fmt.Println(Max([]float64{1.1, 2.2, 3.3})) // 3.3<br>}</pre><p>In the example above, the Max function is defined with a type parameter T, which represents the type of the elements in the slice. The int64 | float64 constraint ensures that the type T can be compared using the comparison operator (&gt; in this case). The function iterates over the slice and compares each element with the current maximum value, updating it if a larger value is found.</p><p>The use of generics allows us to invoke this function with different types, that satisfy the or constraint. The compiler ensures type safety at compile time, preventing us from passing incompatible types to the function.</p><p><strong>Writing Generic Data Structures</strong></p><p>Generics in Go also allow us to build generic data structures like linked lists, trees, and queues. These data structures can be designed to work with a variety of types while maintaining type safety and avoiding the need for excessive type assertions.</p><p>Consider the following example of a generic linked list:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Node[T comparable] struct {<br>    value T<br>    next  *Node[T]<br>}<br><br>type LinkedList[T comparable] struct {<br>    head *Node[T]<br>}<br><br>func (list *LinkedList[T]) Add(value T) {<br>    newNode := &amp;Node[T]{value: value, next: list.head}<br>    list.head = newNode<br>}<br><br>func main() {<br>    list := &amp;LinkedList[int]{}<br>    list.Add(1)<br>    list.Add(2)<br>    list.Add(3)<br><br>    for node := list.head; node != nil; node = node.next {<br>        fmt.Println(node.value)<br>    }<br>}</pre><p>In the above example, the Node and LinkedList types are defined with a type parameter T. The any constraint allows any type to be used with the linked list. The Add method adds a new node to the head of the linked list, with the value specified by the caller.</p><p><strong>Final Note</strong></p><p>The addition of generics to the Go programming language provides increased flexibility and code reuse. Go becomes more expressive without sacrificing its simplicity and readability by allowing developers to write generic functions and data structures.</p><p>Generics in Go allow developers to create reusable components that work across multiple types. This opens up a world of possibilities for creating more concise, efficient, and maintainable libraries, frameworks, and applications.</p><p>As Go evolves, the use of generics is expected to result in significant advancements in the Go ecosystem. It’s an exciting time to be a Go developer, as we open up new horizons of code flexibility and reusability.</p><p>Happy coding! <a href="https://prod.emojipedia.org/laptop/">💻</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49207f7b0994" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/generics-in-go-flexibility-and-reusability-49207f7b0994">Generics in Go: Flexibility and Reusability</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write Clean Code in Go]]></title>
            <link>https://articles.readytowork.jp/write-clean-code-in-go-6ebcd7bca4f6?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ebcd7bca4f6</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[clean]]></category>
            <category><![CDATA[efficient]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[practice]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 23:37:10 GMT</pubDate>
            <atom:updated>2023-07-09T23:37:10.273Z</atom:updated>
            <content:encoded><![CDATA[<p>Major concerning thing while writing your code is how clean is your code. Let’s see how to write code in best practices while coding in organizational enterprises. The primary aim is to make the code usable, readable, and maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00JxPpyrtcKkLOaEPAE5dg.png" /></figure><h3>GoFmt</h3><p>Starting from Readability, GoFmt is a package that automatically formats Go program. It uses a camel case and manages spacing/ tabs for clean code. It automatically formats the go program and if it’s disabled, you can use this command:</p><pre>go fmt path/to/your/file<br>gofmt -w yourfile.go //if you are using different tools, it fmt only if there is no error</pre><p>It doesn’t mean you can’t use other practices. You can disable this and work with different practices. This package is particularly inconsistent and bad with swagger fmt.</p><h3>Test-Driven Development</h3><blockquote>Test Driven Development (TDD) is a software development practice that focuses on creating unit test cases before developing the actual code. It is an iterative approach combining programming, unit test creation, and refactoring.</blockquote><p>Test-driven development consists of the following cycle:</p><ol><li>Write (or execute) a test</li><li>If the test fails, make it pass</li><li>Refactor your code accordingly</li><li>Repeat</li></ol><h3>Naming Convention</h3><p>The naming convention is a necessity for clean code. A clear name pattern itself is the documentation for a project. Now let’s see how can we write clearly.</p><h4>Comments</h4><p>While writing comments, you need to verify if the code needs comments. If the coding pattern is complex and if a comment is helpful, comments are necessary to clarify what’s going on.</p><p>In GoFmt, all public variables and functions should be annotated with comments.</p><p>You should make comments short and comprehensive. The reviewer won’t read long comments. For instance:</p><pre>// It iterate from 0 to 99 <br>// and call the do()<br>// for each iteration<br>for i := 0; i &lt; 100; i++ {<br>  do(i)<br>}</pre><p>This is a tutorial comment. It explains what it’s doing. The programmer doesn’t need how it is doing but why it has been done. So, try to explain why rather than how.</p><pre>// instantiate 10 threads to handle upcoming workload<br>for i := 0; i &lt; 10; i++ {<br>  doSomething(i)<br>}</pre><p>Now, Let&#39;s think about code. The comment might actually be unnecessary when you use a variable name that is specific to that piece of code. That’s why we need to give meaningful names.</p><pre>for workerID := 0; workerID &lt; 10; workerID++ {<br>  instantiateThread(workerID)<br>}</pre><h4>Function Naming</h4><p>The more specific the function, the more general its name. We want to start with a very broad and short function name that describes the general functionality. It’s better to start the function name with a verb such that we know the functionality. Try to make them as short as possible as long names are often confusing</p><pre>func BeerService(beerBrands []BeerBrand) []Beer { // moreGeneral Name<br>    return GetBeerList(beerBrands)<br>}<br><br>func GetBeerList (beerBrands []BeerBrand) []Beer{ // more specific starting with verb<br>  var beerList []Beer<br>    for _, brand := range beerBrands {<br>        for _, beer := range brand {<br>            beerList = append(beerList, beer)<br>        }<br>    }<br>  return beerList<br>}</pre><h4>Variable Naming</h4><p>Our variable names should become less specific as we travel deeper into a function’s scope. Better not use a, b, c literal which doesn’t explain our functionality.</p><pre>func BeerBrandListToBeerList(beerBrands []BeerBrand) []Beer {<br>    var beerList []Beer<br>    for _, brand := range beerBrands {<br>        for _, beer := range brand {<br>            beerList = append(beerList, beer)<br>        }<br>    }<br>    return beerList<br>}<br>// we can see the variable got less specific as we go down the scope</pre><h3>Clean Functions</h3><p>Try to make smaller functions as possible. It makes our code digestible (understandable). It is not necessarily for avoiding duplication.</p><p>It also prevents indentation hell. Try to use a single if- statement and avoid using an else-if statement for better readability. Indentation hell is particularly common when working with interface{} and using type casting:</p><p>Instead of nesting, we can do something like this</p><pre>func GetItem(extension string) (Item, error) {<br>    refIface, ok := db.ReferenceCache.Get(extension)<br>    if !ok {<br>        return EmptyItem, errors.New(&quot;reference not found in cache&quot;)<br>    }<br><br>    ref, ok := refIface.(string)<br>    if !ok {<br>        // return cast error on reference <br>    }<br><br>    itemIface, ok := db.ItemCache.Get(ref)<br>    if !ok {<br>        // return no item found in cache by reference<br>    }<br><br>    item, ok := itemIface.(Item)<br>    if !ok {<br>        // return cast error on item interface<br>    }<br><br>    if !item.Active {<br>        // return no item active<br>    }<br><br>    return Item, nil<br>}</pre><p>Then make simpler functions like this.</p><pre>func GetItem(extension string) (Item, error) {<br>    ref, ok := getReference(extension)<br>    if !ok {<br>        return EmptyItem, ErrReferenceNotFound<br>    }<br>    return getItemByReference(ref)<br>}<br><br>func getReference(extension string) (string, bool) {<br>    refIface, ok := db.ReferenceCache.Get(extension)<br>    if !ok {<br>        return EmptyItem, false<br>    }<br>    return refIface.(string), true<br>}<br><br>func getItemByReference(reference string) (Item, error) {<br>    item, ok := getItemFromCache(reference)<br>    if !item.Active || !ok {<br>        return EmptyItem, ErrItemNotFound<br>    }<br>    return Item, nil<br>}<br><br>func getItemFromCache(reference string) (Item, bool) {<br>    if itemIface, ok := db.ItemCache.Get(ref); ok {<br>        return EmptyItem, false<br>    }<br>    return itemIface.(Item), true<br>}</pre><p>Our main function must be just an abstraction of what needs to be done. The short function doesn’t mean you can add everything in one line. It can sometimes reduce readability.</p><pre>func GetItemIfActive(extension string) (Item, error) {<br>    if refIface,ok := db.ReferenceCache.Get(extension); ok {if ref,ok := refIface.(string); ok { if itemIface,ok := db.ItemCache.Get(ref); ok { if item,ok := itemIface.(Item); ok { if item.Active { return Item,nil }}}}} return EmptyItem, errors.New(&quot;reference not found in cache&quot;)<br>}</pre><h3>Function Signature</h3><p>Function signatures should only contain one or two input parameters. In certain exceptional cases, three can be acceptable, but this is where we should start considering refactoring. If we need to pass more than that, we need to create a struct and pass it as it is more readable than sending all data at once.</p><pre>type QueueOptions struct {<br>    Name string<br>    Durable bool<br>    DeleteOnExit bool<br>    Exclusive bool<br>    NoWait bool<br>    Arguments []interface{} <br>}<br><br>q, err := ch.QueueDeclare(QueueOptions{<br>    Name: &quot;hello&quot;,<br>    Durable: false,<br>    DeleteOnExit: false,<br>    Exclusive: false,<br>    NoWait: false,<br>    Arguments: nil,<br>})</pre><p>This solves these problems: misusing comments, accidentally labeling the variables incorrectly, and mistake ordering. We can also use default values as well.</p><h3>Variable Scope</h3><p>One problem with short functions is more global variables. Global variables are problematic and don’t belong in clean code. If global variables are mutable, it is hard to trace the content.</p><p>Other than avoiding issues with variable scope and mutability, we can also improve readability by declaring variables as close to their usage as possible. Also, it is recommended to declare the return type in the function as figuring out the eventually returned value can be a nightmare. It is better to use it directly after a declaration.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type MyStruct struct {<br> ID   int<br> Name string<br>}<br><br>func main() {<br>   // Declare and initialize variables close to their usage<br>   count := 0<br>   message := &quot;Hello, world!&quot;<br>  <br>   // Use variables directly after declaration<br>   fmt.Println(count)<br>   fmt.Println(message)<br>  <br>   // Declare return type in function signature<br>   result := calculateResult()<br>   fmt.Println(result)<br>  <br>   // Use pointers to limit mutability<br>   myStruct := &amp;MyStruct{ID: 1, Name: &quot;John&quot;}<br>   updateName(myStruct)<br>   fmt.Println(myStruct.Name)<br>}<br><br>func calculateResult() int {<br>   // Perform some calculations and return the result<br>   return 42<br>}<br><br>func updateName(s *MyStruct) {<br>   // Modify the name of the struct<br>   s.Name = &quot;Jane&quot;<br>}</pre><p>As there is no way of declaring a const struct or static variable in Go, it is hard to limit the mutability in Go. This means that we&#39;ll have to restrain ourselves from modifying this variable at a later point in the code. You can use pointers to limit some level of immutability.</p><h4>Returning Defined Errors</h4><p>In coding, there might be cases when we throw errors directly to illustrate the problem.</p><pre>return Item{}, errors.New(&quot;item could not be found in the store&quot;)</pre><p>It is harder to track. Instead, we can just store it in a variable, and in later cases, we can use a variable instead of the entire text.</p><pre>package clean<br>var (<br>    NullItem = Item{}<br>    ErrItemNotFound = errors.New(&quot;item could not be found in the store&quot;) <br>)<br><br>func (store *Store) GetItem(id string) (Item, error) {<br>    store.mtx.Lock()<br>    defer store.mtx.Unlock()<br><br>    item, ok := store.items[id]<br>    if !ok {<br>        return NullItem, ErrItemNotFound<br>    }<br>    return item, nil<br>}<br><br>// Now we can use if errors.Is(err, clean.ErrItemNotFound) for error handling</pre><p>If you want to return a specific error message, you can look for returning dynamic errors.</p><h4>Handling Nil</h4><p>Things can break when you try to access methods or properties of a nil value. Thus, it’s recommended to avoid returning a nil value when possible.</p><pre>//one way can be justing checking if the data is nil<br>if app.cache == nil {<br>      app.cache = NewKVCache()<br>   }<br>//you can also pass empty struct instead of nil</pre><h4>Handling Pointers</h4><p>The pointer itself is a complex thing. We need to know about itself first to reduce the complexity. First, passing a pointer means the data sent are not deep copies instead, you are passing actual data. Changes in one place can change everywhere else. It seems basic but while handling pointers, this simple thing can corrupt real data. That’s why we need to understand the mutability of pointers. Let’s look at this code to understand mutability in pointer.</p><pre>type Person struct {<br> Name string<br>}<br><br>func changeName(p *Person, newName string) {<br> p.Name = newName<br>}<br><br>func main() {<br> // Creating a person instance<br> person := Person{Name: &quot;John&quot;}<br> fmt.Println(&quot;Initial name:&quot;, person.Name) // Output: Initial name: John<br> changeName(&amp;person, &quot;Jane&quot;)<br> fmt.Println(&quot;Updated name:&quot;, person.Name) // Output: Updated name: Jane<br>  // Although name is changed in another function data has been changed in all scope<br>}</pre><h4>Interfaces</h4><p>Without generics, interfaces are the only option to send multitype data. But it is important that we use concrete type whenever possible. Go 1.19 supports generics. Generics can be used to further reduce the redundancy and increase the readability.</p><p>Let’s look at interfaces method first.</p><pre>type Person struct {<br>   Name string<br>}<br><br>func changeName(p interface{}, newName string) {<br>   switch v := p.(type) {<br>   case *Person:<br>      v.Name = newName<br>   case *string:<br>      *v = newName<br>   default:<br>      fmt.Println(&quot;Unsupported type&quot;)<br>   }<br>}<br><br>func main() {<br> person := Person{Name: &quot;John&quot;}<br> changeName(&amp;person, &quot;Jane&quot;)<br><br> name := &quot;Alice&quot;<br> changeName(&amp;name, &quot;Bob&quot;)<br><br> fmt.Println(&quot;Updated name:&quot;, name) // Output: Updated name: Bob<br>}</pre><p>if you are looking to send direct data from interface without newName string parameter. You can do something like this</p><pre>func changeName(p interface{}, newName string) {<br> if person, ok := p.(*Person); ok {<br>  person.Name = newName<br> } else {<br>  fmt.Println(&quot;Unsupported type&quot;)<br> }<br>}</pre><p>But, As I have said earlier, using interface is not concrete. It is better to use concrete example. Since Go 1.19 supports generics, it is better to use generics. Now, Let see how we can implement generics.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/cheekybits/genny/generic&quot;<br>)<br><br>type Telephone generic.Type<br><br>func GetAllUsers[T Telephone](T Telephone) bool {<br> // Logic to get all users based on the provided telephone type<br> // Placeholder return statement<br> return true<br>}<br><br>func main() {<br> telephone := &quot;1234567890&quot;<br> result := GetAllUsers(telephone)<br> fmt.Println(result)<br>}</pre><p>This is the end of the article. Let me know what I should do next. Make sure you like and follow for updates. You can pop into my website here:<br>http://<a href="http://sagarshrestha1999.com.np/">sagarshrestha1999.com.np/</a></p><p>Happy Coding 👨‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ebcd7bca4f6" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/write-clean-code-in-go-6ebcd7bca4f6">Write Clean Code in Go</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Took Kit Query in React]]></title>
            <link>https://articles.readytowork.jp/redux-took-kit-query-in-react-69220942f5e5?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/69220942f5e5</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[rtk-query]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[rtk]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 20:57:08 GMT</pubDate>
            <atom:updated>2023-07-02T20:57:08.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voj-9C4uuNn6Gs0xEVu05A.png" /></figure><p>State management is one of the core functions while creating a frontend app.</p><blockquote>Application state management is the process of maintaining knowledge of an application’s inputs across multiple related data flows that form a complete business transaction — or a session — to understand the condition of the app at any given moment.</blockquote><p>There are many libraries that can handle states such as context management, custard, provider, Redux, and many more. Currently, we will discuss Redux.</p><h3>Redux</h3><p>Redux is a predictable state container that helps write code that is consistent with the environment. It also provides easy to debug environment.</p><h3>Three Principles of Redux</h3><ol><li>Single Source of Truth<br>The global state of your application is stored in an object tree within a single store.</li><li>Read-only State<br>The only way to change the state in redux is to emit an action, that describes what happens.</li><li>Changes are made with pure functions<br>To specify how the state tree is transformed by actions, you write pure reducers.</li></ol><h3>Explaining Redux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sJ5641tTBSXZUCnH.png" /></figure><ol><li>Redux Store<br>It is the main central place to store all the state. As we explain in principle, it has a single source of truth. The store is usually provided to the <strong>App.js</strong> with the help of &lt;Provider&gt; &lt;/Provider&gt; tag, which makes it act as a global state such that its children can share it.</li><li>Redux Actions<br>Since Redux has a read-only state, there is a need of dispatching the action. And, action explains what needs to be changed in the state.</li><li>Redux Reducer<br>Reducer takes the current state and action, and it returns the updated state.</li></ol><h3>Advantages of Redux</h3><ol><li>Centralized state management system</li><li>Performance Optimizations</li><li>Pure reducer functions (Immutability)</li><li>Can Store data long-term</li><li>Easy Time-travel Debugging as it makes the state available for debugging at any time</li><li>Supportive community</li></ol><h3>Redux Tool Kit (RTK)</h3><p>Now what is RTK? It is simply a set of tools that make development with redux easier and fast. It speeds up development, uses recommended best practices, provides good default behaviors, catches mistakes, and allows you to write simpler code.</p><p>Redux can be a burden as it adds a large amount of trivial code. It is good for complex applications. Therefore, to counter it, developers started building Redux Toolkit (RTK), which has improved the efficiency of Redux implementation. It eliminates complexity and is easy to configure.</p><p>RTK also came up with a simpler way of adding redux to the project. That is Rtk query</p><h3>RTK Query</h3><p>RTK stands for Redux toolkit. It comes with a redux toolkit query add-on with the @reduxjs/toolkit package. RTK Query is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching &amp; caching logic yourself. It can be integrated with any framework capable of using Redux. Built-in typescript, it supports OpenAPI, graphic, and React hooks. It has a surprisingly small bundle size compared to redux.</p><p>RTK Query uses queries and mutations to improve data fetching and caching. It provides inbuilt support for <a href="https://redux-toolkit.js.org/rtk-query/usage/error-handling">error handling</a> and <a href="https://redux-toolkit.js.org/rtk-query/usage/manual-cache-updates#optimistic-updates">optimistic updates</a>.</p><ul><li><a href="https://redux-toolkit.js.org/rtk-query/usage/queries"><strong>Queries</strong></a> — with data fetching library.</li><li><a href="https://redux-toolkit.js.org/rtk-query/usage/mutations"><strong>Mutations</strong></a> — send updates to the server as well as replicate them in the cache locally.</li></ul><p>We will be implementing this in this article.</p><p>Before getting into coding, we need a backend. So, I have prepared an article on it as well.</p><p>https://<a href="https://sgstlife.medium.com/99511f3b41ea">sgstlife.medium.com</a>/99511f3b41ea</p><p>Now we can implement it in our React application. First, let’s create a react app and run it. We will build basic CRUD first.</p><pre>npx create-react-app rtk-query<br>cd my-app<br>npm start</pre><p>Now let’s create a folder structure for better organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*QQtMWhiLXbVgAFnyviqzMw.png" /></figure><p>We won’t be discussing the design UI in this article. So, let’s expedite this process.</p><pre>npm i react-icons<br>npm install reactstrap react react-dom</pre><p>Changes in App.js</p><pre>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;Home /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>You can replace app.css with</p><pre>.App {<br>  text-align: center;<br>}<br><br>.box{<br>  background:white;<br>  width:300px;<br>  border-radius:6px;<br>  margin: 0 auto 0 auto;<br>  margin-top: 150px;<br>  padding:0px 0px 70px 0px;<br>  border: #2980b9 4px solid; <br>}<br><br>.email{<br>  margin:10px;<br>  background:#ecf0f1;<br>  border: #ccc 1px solid;<br>  padding: 8px;<br>  width:250px;<br>  border-radius:4px;<br>}<br><br>.btn{<br>  background:#2ecc71;<br>  width:125px;<br>  padding-top:5px;<br>  padding-bottom:5px;<br>  color:white;<br>  border-radius:4px;<br>  border: #27ae60 1px solid;<br>  <br>  /* margin-top:20px;<br>  margin-left:80px; */<br> <br>  font-weight:800;<br>  font-size:0.8em;<br>}<br><br>.btn:hover{<br>  background:#2CC06B; <br>}<br><br>/* dashboard */<br>.styled-table {<br>  border-collapse: collapse;<br>  margin: auto;<br>  font-size: 0.9em;<br>width:90%;<br>  box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);<br>}<br><br>.styled-table thead tr {<br>  background-color: #009879;<br>  color: #ffffff;<br>  text-align: left;<br>}<br><br>.id{<br>width:5%;<br>text-align: left;<br><br>}<br>.todo{<br>width:70%;<br>text-align: left;<br><br>}<br>.status{<br>width:10%;<br>text-align: left;<br><br>}<br><br>.styled-table th,<br>.styled-table td {<br>  padding: 12px 15px;<br>}<br><br>.styled-table tbody tr {<br>  border-bottom: 1px solid #dddddd;<br>}<br><br>.styled-table tbody tr:nth-of-type(even) {<br>  background-color: #f3f3f3;<br>}<br><br>.styled-table tbody tr:last-of-type {<br>  border-bottom: 2px solid #009879;<br>}<br>/* modal */<br><br>.modal {<br>  position: fixed; /* Stay in place */<br>  z-index: 1; /* Sit on top */<br>  padding-top: 100px; /* Location of the box */<br>  left: 0;<br>  top: 0;<br>  width: 100%; /* Full width */<br>  height: 100%; /* Full height */<br>  overflow: auto; /* Enable scroll if needed */<br>  background-color: rgb(0,0,0); /* Fallback color */<br>  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */<br>}<br><br>/* Modal Content */<br>.modal-content {<br>  background-color: #fefefe;<br>  margin: auto;<br>  padding: 10px 20px;<br>  border: 1px solid #888;<br>  width: 40%;<br>  <br>}<br><br>textarea {<br>  width: 100%;<br>  height: 150px;<br>  padding: 12px 20px;<br>  box-sizing: border-box;<br>  border: 2px solid #ccc;<br>  border-radius: 4px;<br>  background-color: #f8f8f8;<br>  font-size: 16px;<br>  resize: none;<br>}<br>.inner{<br>  text-align: left;<br>  padding: 20px;<br><br>}<br>/* The Close Button */<br>.close {<br>  color: #aaaaaa;<br>  float: right;<br>  font-size: 28px;<br>  font-weight: bold;<br>}<br><br>.close:hover,<br>.close:focus {<br>  color: #000;<br>  cursor: pointer;<br>}</pre><p>Now let’s create these files</p><p>components/create.js</p><pre>import React, { useState } from &#39;react&#39;;<br>import { FaPlusCircle } from &#39;react-icons/fa&#39;;<br>import { Modal } from &quot;reactstrap&quot;;<br><br>function Create() {<br>    const [modalOpen, setModalOpen] = useState(false);<br>    return (<br>        &lt;div&gt;<br>            &lt;div style={{marginRight:80, alignItems:&quot;right&quot;, marginBottom:10, position:&quot;relative&quot;, float:&quot;right&quot;}}&gt;&lt;button onClick={() =&gt; setModalOpen(!modalOpen)}&gt;&lt;FaPlusCircle/&gt; Create&lt;/button&gt; &lt;/div&gt;<br>            &lt;Modal toggle={() =&gt; setModalOpen(!modalOpen)} isOpen={modalOpen}&gt;<br>                &lt;div&gt;<br>                    &lt;span className=&quot;close&quot;  onClick={() =&gt; setModalOpen(!modalOpen)}&gt;×&lt;/span&gt;<br>                    &lt;div className=&#39;inner&#39;&gt;<br>                        &lt;form &gt;<br>                            &lt;h2&gt;Create New Todo&lt;/h2&gt;<br>                            &lt;label &gt;To Do&lt;/label&gt;&lt;br /&gt;<br>                            &lt;textarea style={{margin:10}} id=&quot;todo&quot;&gt;&lt;/textarea&gt;<br>                            &lt;label htmlFor=&quot;lname&quot;&gt;Status&lt;/label&gt;&lt;br /&gt;<br>                            &lt;input className=&#39;email&#39; type=&quot;text&quot; id=&quot;status&quot; defaultValue=&quot;&quot; /&gt;&lt;br /&gt;&lt;br /&gt;<br>                            &lt;button type=&#39;submit&#39;&gt;Create&lt;/button&gt;<br>                        &lt;/form&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/Modal&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default Create;</pre><p>Components/edit.js</p><pre>import React, { useState } from &#39;react&#39;;<br>import { FaEdit } from &#39;react-icons/fa&#39;;<br>import { Modal } from &quot;reactstrap&quot;;<br><br>function Edit({item}) {<br>    const [modalOpen, setModalOpen] = useState(false);<br>    return (<br>        &lt;div&gt;<br>            &lt;FaEdit  onClick={() =&gt; setModalOpen(!modalOpen)}/&gt;<br>            &lt;Modal toggle={() =&gt; setModalOpen(!modalOpen)} isOpen={modalOpen}&gt;<br>                &lt;div&gt;<br>                    &lt;span className=&quot;close&quot;  onClick={() =&gt; setModalOpen(!modalOpen)}&gt;×&lt;/span&gt;<br>                    &lt;div className=&#39;inner&#39;&gt;<br>                        &lt;form&gt;<br>                            &lt;h2&gt;Edit Todo&lt;/h2&gt;<br>                            &lt;label &gt;To Do&lt;/label&gt;&lt;br /&gt;<br>                            &lt;textarea style={{margin:10}} id=&quot;todo&quot; defaultValue={item.todo}&gt;&lt;/textarea&gt;<br>                            &lt;label htmlFor=&quot;lname&quot;&gt;Status&lt;/label&gt;&lt;br /&gt;<br>                            &lt;input className=&#39;email&#39; type=&quot;text&quot; id=&quot;status&quot; name=&quot;lname&quot; defaultValue={item.status} /&gt;&lt;br /&gt;&lt;br /&gt;<br>                            &lt;button type=&quot;submit&quot; &gt;Edit&lt;/button&gt;<br>                        &lt;/form&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/Modal&gt;<br>           <br>        &lt;/div&gt;<br>    );<br>}<br>export default Edit;</pre><p>pages/home.js</p><pre>import React from &#39;react&#39;;<br>import Create from &#39;../components/create&#39;;<br>import Edit from &#39;../components/edit&#39;;<br>import { FaTrash } from &#39;react-icons/fa&#39;;<br><br>function Home() {<br>    var item ={<br>        todo:&quot;Swimming&quot;,<br>        status:&quot;pending&quot;<br>    }<br>    return (<br>        &lt;div className=&#39;home&#39;&gt;<br>            &lt;h1&gt;Dashboard&lt;/h1&gt;<br>            &lt;Create&gt;&lt;/Create&gt;<br>            &lt;table className=&quot;styled-table&quot;&gt;<br>                &lt;thead&gt;<br>                        &lt;tr&gt;<br>                            &lt;th className=&quot;id&quot;&gt;id&lt;/th&gt;<br>                            &lt;th className=&quot;todo&quot;&gt;Todo&lt;/th&gt;<br>                            &lt;th className=&quot;status&quot;&gt;Status&lt;/th&gt;<br>                            &lt;th className=&quot;ch&quot;&gt;Change&lt;/th&gt;<br>                        &lt;/tr&gt;<br>                    <br>                &lt;/thead&gt;<br>                &lt;tbody&gt;                    <br>                        &lt;tr&gt;<br>                            &lt;th className=&quot;id&quot;&gt;1&lt;/th&gt;<br>                            &lt;th className=&quot;todo&quot;&gt;Swimming&lt;/th&gt;<br>                            &lt;th className=&quot;status&quot;&gt;Pending&lt;/th&gt;<br>                            &lt;th className=&quot;ch&quot;&gt;<br>                                &lt;div style={{display: &#39;flex&#39;}}&gt;<br>                                    &lt;div style={{marginLeft:&#39;10px&#39;}}&gt;&lt;Edit item={item}&gt;&lt;/Edit&gt;&lt;/div&gt;<br>                                    &lt;div style={{marginLeft:&#39;10px&#39;}}&gt;&lt;FaTrash/&gt;&lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/th&gt;<br>                            <br>                        &lt;/tr&gt;<br>                <br>                &lt;/tbody&gt;<br>            &lt;/table&gt;<br>           <br>        &lt;/div&gt;<br>    );<br>}<br><br>export default Home;</pre><p>It should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6u6wHkN2TFOITqK2i_GQSg.png" /></figure><p>Now, you have fine looking app now. Now let’s integrate our react query into this project. First, install RTK packages.</p><pre>npm install @reduxjs/toolkit react-redux</pre><p>Now, let’s start our CRUD application. We have our server running on http://localhost:4001 by default. Now create a file features/todoAPI.js. This will fetch all the data from our server. Make sure you have added some data to our server from POSTMAN.</p><pre>import { createApi, fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;<br><br>export const todoApi = createApi({<br>  reducerPath: &quot;todoApi&quot;,<br>  baseQuery: fetchBaseQuery({ baseUrl: &quot;http://localhost:4001/todos/&quot;}),<br>  tagTypes: [&#39;Todos&#39;],<br>  endpoints: (builder) =&gt; ({<br>    getAllTodos: builder.query({<br>      query: () =&gt; &quot;&quot;,<br>      providesTags: [&#39;Todos&#39;]<br>    }),<br>  }),<br>});<br><br>export const { useGetAllTodosQuery} = todoApi;</pre><p>Getting into details, CreateApi defines endpoints to retrieve data from the api. You can include how to fetch and transform the data inside this function. Make sure you use one API slice per URL for a better organization.</p><p>In the above code, we have some attributes:</p><ul><li><em>keepUnusedDataFor</em> <strong>— </strong>To configure the data expiration time. I haven’t written in code. You can add it below tags as <em>keepUnusedDataFor:30</em></li><li><em>tagTypes</em> — These tags will be used by RTK Query as keys to cache data. We will see in functioning later.</li><li><em>endpoints — </em>It allows interaction with endpoints. Now we have getAllTodos to fetch all data. All the requests to the server are written here</li><li><em>baseQuery</em>— It allows adding baseUrl and query related to headers information. We can easily add our authorization token from here</li></ul><p>Now use this on our App.js with the help of <em>&lt;ApiProvider&gt;</em> without the need of configuring the store. You can also configure the store if you are using rtk. Let me know if you need a tutorial on that.</p><pre>import { todoApi } from &#39;./features/todoAPI&#39;;<br><br>function App() {<br>  return (<br>    &lt;ApiProvider api={todoApi}&gt;<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;Home /&gt;<br>      &lt;/div&gt;<br>    &lt;/ApiProvider&gt;<br>  );<br>}</pre><p>Now let’s call our get request and show it on the table. We’ll be making changes in home.js.</p><pre>import { useGetAllTodosQuery } from &#39;../features/todoAPI&#39;;<br><br>function Home() {<br>    const {data:todo, isloading}= useGetAllTodosQuery() // fetching data<br>    return (<br>        &lt;div className=&#39;home&#39;&gt;<br>            ...<br>                &lt;tbody&gt;  <br>                     { (!isloading &amp;&amp; todo) ? todo.map((item, _) =&gt; (<br>                        //mapping data to the table<br>                        &lt;tr&gt;<br>                            &lt;th className=&quot;id&quot;&gt;{item._id}&lt;/th&gt; //getting data from item<br>                            &lt;th className=&quot;todo&quot;&gt;{item.todo}&lt;/th&gt;<br>                            &lt;th className=&quot;status&quot;&gt;{item.status}&lt;/th&gt; <br>                            &lt;th className=&quot;ch&quot;&gt;<br>                                &lt;div style={{display: &#39;flex&#39;}}&gt;<br>                                    &lt;div style={{marginLeft:&#39;10px&#39;}}&gt;&lt;Edit item={item}&gt;&lt;/Edit&gt;&lt;/div&gt;<br>                                    &lt;div style={{marginLeft:&#39;10px&#39;}}&gt;&lt;FaTrash/&gt;&lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/th&gt;<br>                            <br>                        &lt;/tr&gt;<br>                    )): ()=&gt;(&quot;error&quot;)} //throwing error<br>                &lt;/tbody&gt;<br>              ....<br>        &lt;/div&gt;<br>    );<br>}</pre><p>Now the data is successfully fetched. Let me show you the required output. Data are fetched from the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIp9DctGduzifZBbHCpiaw.png" /></figure><p>Now let’s add create, update, and delete requests in the query at once as it won’t be hard to understand the rest of the flow altogether.</p><p>/features/todoAPI.js</p><pre>...<br>endpoints: (builder) =&gt; ({<br>    ...<br>    createTodo: builder.mutation({<br>      query: (body) =&gt; ({<br>        url:&#39;&#39;,<br>        method :&#39;POST&#39;,<br>        body:body<br>      }),<br>      invalidatesTags: [&#39;Todos&#39;]<br>    }),<br>    updateTodo: builder.mutation({<br>      query: ({id,todo,status}) =&gt; ({<br>        url:`${id}`,<br>        method :&#39;PUT&#39;,<br>        body:{todo,status}<br>      }),<br>      invalidatesTags: [&#39;Todos&#39;]<br>    }),<br>    deleteTodo: builder.mutation({<br>      query: (id) =&gt; ({<br>        url:`${id}`,<br>        method :&#39;DELETE&#39;<br>      }),<br>      invalidatesTags: [&#39;Todos&#39;]<br>    })<br>  }),<br>...<br>export const { useGetAllTodosQuery, useCreateTodoMutation, useUpdateTodoMutation,useDeleteTodoMutation } = todoApi;</pre><p>Here, we have made use of mutations for sending data to the server. Now, let’s take about some attributes here.</p><ul><li><em>query</em> — It allows RTK query to perform some query. It allows to set URL, method of request, and also set body for the mutation.</li><li><em>invalidateTags</em>— In creating method, we set the tags by using providesTags. Now we invalidate these tags so that the rtk query knows the data fetches are old and prefetching are needed</li></ul><p>Now let’s work on the implementation of create in create.js</p><pre>...<br>import { useCreateTodoMutation } from &#39;../features/todoAPI&#39;;<br><br>function Create() {<br>    ..<br>    const [createTodoMut] = useCreateTodoMutation()<br>    const createTodo = async (event) =&gt; {<br>        event.preventDefault()<br>        const todo = {<br>          todo: event.target.todo.value,<br>          status: event.target.status.value,<br>        }<br>        createTodoMut(todo)<br>        setModalOpen(!modalOpen)<br>      };<br>    return (<br>            ...<br>                        &lt;form onSubmit={createTodo}&gt;<br>                            ...<br>                        &lt;/form&gt;<br>            ...<br>    );<br>}</pre><p>UseCreateTodoMutation is used to call create request. You can add it on onSubmit and send it to the mutation by <em>createTodoMut(todo).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDyVGmPQNhWvAEdA-rbbOQ.png" /></figure><p>Now let’s add update feature which is similar to create feature. Let’s edit in edit.js</p><pre>...<br>import { useUpdateTodoMutation } from &#39;../features/todoAPI&#39;;<br><br>function Edit({item}) {<br>   ..<br>    const [updateTodoMut] = useUpdateTodoMutation()<br>    <br>    const editTodo = async (event) =&gt; {<br>        event.preventDefault()<br>        const todo = {<br>            todo: event.target.todo.value,<br>            status: event.target.status.value,<br>        }<br>        updateTodoMut({id:item._id, ...todo} )<br>        setModalOpen(!modalOpen)<br>      };<br><br>    return (<br>       ..<br>                        &lt;form onSubmit={editTodo}&gt;<br>                            &lt;h2&gt;Edit Todo&lt;/h2&gt;<br>                            &lt;label &gt;To Do&lt;/label&gt;&lt;br /&gt;<br>                            &lt;textarea style={{margin:10}} id=&quot;todo&quot; defaultValue={item.todo}&gt;&lt;/textarea&gt;<br>                            &lt;label htmlFor=&quot;lname&quot;&gt;Status&lt;/label&gt;&lt;br /&gt;<br>                            &lt;input className=&#39;email&#39; type=&quot;text&quot; id=&quot;status&quot; name=&quot;lname&quot; defaultValue={item.status} /&gt;&lt;br /&gt;&lt;br /&gt;<br>                            &lt;button type=&quot;submit&quot; &gt;Edit&lt;/button&gt;<br>                        &lt;/form&gt;<br>        ..<br>        <br>    );<br>}<br>..</pre><p>You can use the pen icon to edit the request. It is similar to createTodo. Now let’s end this with a delete request in home.js file.</p><pre>..<br>import { useDeleteTodoMutation, useGetAllTodosQuery } from &#39;../features/todoAPI&#39;;<br><br>function Home() {<br>    ..<br>    const [deleteTodoMut]= useDeleteTodoMutation()<br>    const deleteData =  (id) =&gt; {<br>        deleteTodoMut(id)<br>    };<br>    return (<br>        &lt;div className=&#39;home&#39;&gt;<br>            ..<br>                     { (!isloading &amp;&amp; todo) ? todo.map((item, _) =&gt; (<br>                            ..<br>                                    &lt;div style={{marginLeft:&#39;10px&#39;}}&gt;&lt;FaTrash onClick={()=&gt;{deleteData(item._id)}}/&gt;&lt;/div&gt;<br>                            ..<br>                    )): ()=&gt;(&quot;error&quot;)} <br><br>                ..<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default Home;</pre><p>UseDeleteTodoMutation will use Delete mutation to delete the item. You can click on the delete icon to see this feature. Now, our CRUD Application is complete. You can see the code in this link<br>https://<a href="https://github.com/Znerf/rtk-query">github.com/Znerf/rtk-query</a></p><p>Let me know what I should do next. Make sure you like and follow for updates. You can pop into my website here and Say Hi:<br>http://<a href="http://sagarshrestha1999.com.np/">sagarshrestha1999.com.np/</a></p><p>Happy Coding <a href="https://emojipedia.org/man-technologist/">👨‍💻</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69220942f5e5" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/redux-took-kit-query-in-react-69220942f5e5">Redux Took Kit Query in React</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Backend in NodeJS]]></title>
            <link>https://sgstlife.medium.com/basic-backend-in-nodejs-99511f3b41ea?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/99511f3b41ea</guid>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 03:46:40 GMT</pubDate>
            <atom:updated>2023-06-26T03:46:40.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2HKo9FjIwcMhROL6IhQfg.png" /></figure><p>This is a basic, easy backend which uses Express, Nodejs and Mongodb. This will be a reference to the next tutorials. I’ll try to make as short as possible. Without further verbose comments, let&#39;s get into creating a server which can do basic CRUD operations.</p><p><strong>Installation</strong><br>First, let’s install Nodejs from the official website. It will provide us exe file which can be easily installed on windows. It will also install npm by default, so you don’t need to install npm separately. I am using node version 16, so if you are following this tutorial, I recommend you use this version.</p><p><a href="https://nodejs.org/en/download">Node.js - Download Node.js®</a></p><p>Creating an App<br>You can start by creating an app inside a folder. And follows the script below</p><pre>mkdir nodeServer<br>cd nodeServer<br>node init <br>##you can pass default answer to the process</pre><p>This will create a nodejs app. Now, you need to create some basic folder and files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*qfRtjp5brTCKbpPQLkLxtA.png" /></figure><p>In order to run the app you need to add “start”: “node index.js” inside script of package.json. You can use nodemon if you don’t want to refresh the server once a while</p><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;,<br> },</pre><p>After that, Lets start working on index.js. I’ll try to provide explantion in code.</p><pre><br>const express = require(&#39;express&#39;)<br>const cors = require(&quot;cors&quot;);<br><br>//instantiating express app and variables<br>const app= express()<br>const port=4001;<br><br>app.use(express.json());  // this will enable getting elements from Post request as json<br>app.use(cors())            // this is for handling cors<br><br>app.get(&quot;/&quot;,(req,res)=&gt;{ // Basic GET request to check if app is running<br>    console.log(req)<br>    res.send(&quot;App is running&quot;) <br>})<br><br>app.listen(port, ()=&gt;{ // Setting up app <br>    console.log(`Server running on http://localhost:${port}`)<br>})</pre><p>Now you can start the app using</p><pre>npm install express // for installing express<br>npm install cors    // for installing cors for handling cross origin request<br>npm run start      // for starting application</pre><p>You can check from the Postman if the app is running or not. You should get something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxtrbnR8Bj4kTCD2UWDwLQ.png" /></figure><p>MongoDB</p><p>For this project, we are using MongoDB. It is a structureless database. You can easily install it from this website.</p><p><a href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/">Install MongoDB Community Edition on Windows</a></p><p>We will be using mongoose as ODM for handling mongoDB. Lets install it and add some lines into our index.js file.</p><pre> npm install mongoose</pre><pre>const mongoose= require(&quot;mongoose&quot;) //importing mongoose<br><br>mongoose.connect(&quot;mongodb://localhost/nodeserver&quot;) //connecting to our database<br>// you can store these value in env file to ensure security. But right now I will just use plain text<br>.then(()=&gt;{<br>    <br>    app.listen(port, ()=&gt;{ // enwraping the listen to database connect<br>        console.log(`Server running on http://localhost:${port}`)<br>    })<br>    console.log(&quot;Mongodb Database connected&quot;)<br>})<br>.catch((e)=&gt;{  //throwing error when connection fails<br>    console.log(&quot;error::&quot;,e)<br>})</pre><p>Now create an CRUD application for todo. Before coding, let’s talk about the follow. First of all, All of the request enter through routes and routes checks which controller it needs to complete the request. Then, controller gets that request and use models that maps the data to the database.</p><p>Now, Starting with models. Create a file models/todoModels.js, and you can write following code</p><pre>//Model maps data to database <br>const mongoose = require(&quot;mongoose&quot;)<br><br>const Schema= mongoose.Schema; <br><br>const TodoSchema= new Schema(//creating a schema<br>    {<br>        todo: {// fields in the database<br>            type:String, <br>            required:true<br>        },<br>        status: {<br>            type:String,<br>            required:true<br>        }<br>    },<br>    {<br>        timestamps:true //for storing databse<br>    }<br>)<br><br>module.exports= mongoose.model(&quot;Todos&quot;, TodoSchema); //mapping schema to a model</pre><p>Now we can access it from a controller. Now, let’s create a file controllers/todoController.js .</p><pre><br>//importing Library<br>const mongoose= require(&quot;mongoose&quot;)<br>//importing model we created<br>const Todos= require(&quot;../models/todoModel&quot;)<br><br>//function declaration<br>const getTodos= async(req, res)=&gt;{ // this is for fetching all todo data from database<br>    try{<br>        const todos = await Todos.find() // this .find() function enable us to fetch data from model<br>        res.status(200).json(todos) // returning data with status code 200<br>    }catch(error){ // this is for throwing error<br>        res.status(400).json({&quot;error&quot;:error})<br>    }<br>}<br><br>const getTodo= async(req, res)=&gt;{ // this is for fetching one todo data from database<br>    const {id} = req.params; // all the path elements comes form req.params we need to send id from path you can see it on postman below<br>    try{<br>        const todos = await Todos.findById({_id : id}); // .findById() enable us to get on data by id<br>        res.status(200).json(todos) <br>    }catch(error){<br>        res.status(400).json({&quot;error&quot;:error})<br>    }<br>}<br><br>const deleteTodo= async(req, res)=&gt;{ // this is for deleting data<br>    const {id} = req.params;<br>    try{<br>        const todos = await Todos.findByIdAndDelete({_id : id});// .findByIdAndDelete() enable us to delete data by id<br>        res.status(200).json(todos)<br>    }catch(error){<br>        res.status(400).json({&quot;error&quot;:&quot;Couldn&#39;t delete the document&quot;})<br>    }<br>}<br><br>const updateTodo = async(req, res)=&gt;{// this is for updating todo<br>    const {id} =req.params; <br>    try{<br>        const todos = await Todos.findByIdAndUpdate( //.findByIdAndUpdate enable us to update specific data by id<br>            {_id:id},{...req.body}<br>        );<br>        res.status(200).json(todos)<br>    }catch{<br>        res.status(400).json({&quot;error&quot;:&quot;Couldn&#39;t udpate the document&quot;})<br>    }<br><br>}<br><br>const createTodos = async (req,res)=&gt;{// this is for creating todo<br>    try{<br>        const {todo ,status} =req.body; // You can easily get POST body data from req.body<br>        const todos = await Todos.create({// .create() enables to save data on database<br>            todo,<br>            status<br>        })<br>        res.status(200).json(todos)<br>    }catch(e){<br>        console.log(e)<br>    }<br>}<br><br>///export the function to be import on routes<br>module.exports={<br>    getTodos,<br>    createTodos,<br>    getTodo,<br>    deleteTodo,<br>    updateTodo<br>}</pre><p>Now Let’s link this to our routes/todoRoutes.js</p><pre><br>//importing Libray<br>const express= require(&quot;express&quot;);<br>//importing from controllers we created<br>const {getTodos, createTodos, getTodo, deleteTodo, updateTodo} = require(&quot;../controllers/todoController&quot;);<br><br>//intantiating Router for routes controller<br>const router= express.Router();<br><br>//Routes Asignments<br>router.get(&quot;/test&quot;, (req,res)=&gt;{<br>    res.status(200).json({&quot;message&quot;:&quot;Hello World&quot;})   //Basic testing function<br>})<br>router.post(&quot;/&quot;, createTodos);<br><br>router.get(&quot;/&quot;, getTodos)           //Get Todos and return array of todos from controllers<br><br>router.get(&quot;/:id&quot;, getTodo);<br><br>router.delete(&quot;/:id&quot;, deleteTodo)<br><br>router.put(&quot;/:id&quot;,updateTodo )<br><br><br>//export router <br>module.exports = router</pre><p>Now we need to add this to our index.js</p><pre>app.use(&quot;/todos&quot;, todoRoutes)</pre><p>Now your CRUD function is complete. You can test it from POST man.</p><ol><li>Creating Todo request</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttsj2tBR04c55AK8c0xD7g.png" /></figure><p>You need to go to Body tab and chose “raw” and JSON and add data as</p><pre>{<br>    &quot;todo&quot;:&quot;Cooking&quot;,<br>    &quot;status&quot;:&quot;pending2&quot;<br>}</pre><p>2. Getting this data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbSSf81UzlEkthkRGbGOgQ.png" /></figure><p>3. Getting specific data<br>You can get specific data by adding id on endpoint <a href="http://localhost:4001/todos/648076a8a1c7af113941366c">http://localhost:4001/todos/{</a>id}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-R_dKwCbFcWWiTYtDvg_A.png" /></figure><p>4. Updating this data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE5-di0tAhlda8yBJmREig.png" /></figure><p>5. Deleting the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujReeyRiYFkUYNdLnI3Qtg.png" /></figure><p>This is just a basic CRUD operation in nodejs. If you don’t need tutorial, You can follow instruction from this github link below. Don’t forget to follow and checkout on my next tutorial. This tutorial isn’t beginner friendly, but you can easily install it from github readme section without need of understanding it if you are here from my later articles.</p><p><a href="https://github.com/Znerf/node-server">https://github.com/Znerf/node-server</a></p><p>Let me know what I should do next. Make sure you like and follow for updates. You can pop into my website here:<br>http://<a href="http://sagarshrestha1999.com.np/">sagarshrestha1999</a>.com.np/</p><p>Happy Coding 👨‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99511f3b41ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservice in Gin Golang]]></title>
            <link>https://articles.readytowork.jp/microservice-in-gin-golang-91851930036a?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/91851930036a</guid>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[microservices-application]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Tue, 02 May 2023 05:17:14 GMT</pubDate>
            <atom:updated>2023-05-02T05:17:14.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservices in Gin Golang</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFL9cik57TA-Ab22M_TOEg.png" /></figure><p>Before we start, this is one of the practice sessions. And you might need a computer with a basic Go-Gin application installed before you start. Now, let’s talk about some techniques we use in backend development. When developing an organization, we must consider proper architecture in the development pattern. Coding for a small project is straightforward. But as it grows, it can get harder to scale and manage the projects.</p><p>Let’s discuss some architecture first.</p><p><strong>Monolithic Architecture</strong></p><blockquote><strong>Monolithic Architecture</strong> is like a big container, wherein all the software components of an app are assembled and tightly coupled, i.e., each component fully depends on each other</blockquote><p>Monolithics itself means large and slow to change. In software development, monolithic architecture means all the services inside the system share a common instance no matter how big the application gets.</p><p>Advantage</p><ol><li>Easy deployment</li><li>Easy Development</li><li>Uniform Performing APIs</li><li>Simplified testing</li><li>Easy debugging</li></ol><p>Disadvantages</p><p>1. Slow Speed in development</p><p>2. Low Scalability</p><p>3. Low Reliability as one error takes the system down</p><p>4. Lack of flexibility</p><p>5. Small deployments need the entire system to be down</p><p><strong>Microservice</strong></p><blockquote>Microservice is an architectural style that structures an application as a collection of services that are independently deployable, loosely coupled, organized around business capabilities and owned by a small team. The microservice architecture enables an organization to deliver large, complex applications rapidly, frequently, reliably and sustainably — a necessity for competing and winning in today’s world.</blockquote><p>In Microservice, unlike monolithic architecture, the big app splits into numbers of services. A small team handles each service. This makes the application scalable, reliable, and easy to debug. It makes the program easy to code and deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*F90d8CoecLrsNlW5" /><figcaption>From <a href="https://www.atlassian.com/">https://www.atlassian.com/</a></figcaption></figure><p>Advantage<br>1. High Agility, scalability<br>2. Continuous and independent deployment <br>3. Maintainable and Testable <br>4. High reliability <br>In short, the opposite disadvantages of a monolithic system</p><p>Disadvantage<br>1. More complex<br>2. High infrastructure costs<br>3. Organizational overhead and more communication needed<br>4. Hard for Debugging <br>5. Lack of standardization and ownership</p><p>Now, let&#39;s dive into the codes. Primarily, let’s create a scenario where there is a logistics company that ships items. Now, the company ships the item and register them in service, namely <em>logistics</em>. This service uses another service, <em>Email, </em>to send emails to individuals.</p><p>Now, create a service for EmailJob. Before starting you need to init go repository and install some libraries.</p><pre>//Initilize go project<br>go mod init microservice<br><br>//install gin<br>go get -u github.com/gin-gonic/gin</pre><p>Now, you can create an app<em> Email.go </em>and create basic gin application.</p><pre>package main<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br> router := gin.Default()<br> router.GET(&quot;/status&quot;, func(c *gin.Context) {<br>  c.JSON(200, &quot;Email Server Running&quot;)<br> })<br> <br> router.Run(&quot;:9000&quot;)<br>}</pre><p>This sample app is running a GET in /status path. You can check it using Postman to see if it’s running.</p><p>Now, set up a <em>send-email</em> POST requests. For it, we need to add a <em>struct</em> for creating fetching data, say <em>EmailJob</em>.</p><pre>type EmailJob struct {<br> Sender  string `json:&quot;sender&quot; binding:&quot;required&quot;`<br> JobId   int    `json:&quot;job_id&quot; binding:&quot;gte=0&quot;`<br> Subject string `json:&quot;subject&quot; binding:&quot;required&quot;`<br> Email   string `json:&quot;email&quot; binding:&quot;required&quot;`<br> Body    string `json:&quot;body&quot; binding:&quot;required&quot;`<br>}</pre><p>Now, we can add basic POST requests in the main application assigning random numbers to that task.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;math/rand&quot;<br> &quot;time&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>type EmailJob struct {<br> Sender  string `json:&quot;sender&quot; binding:&quot;required&quot;`<br> JobId   int    `json:&quot;job_id&quot; binding:&quot;gte=0&quot;`<br> Subject string `json:&quot;subject&quot; binding:&quot;required&quot;`<br> Email   string `json:&quot;email&quot; binding:&quot;required&quot;`<br> Body    string `json:&quot;body&quot; binding:&quot;required&quot;`<br>}<br><br>func main() {<br> router := gin.Default()<br> router.GET(&quot;/status&quot;, func(c *gin.Context) {<br>    c.JSON(200, &quot;Email Server Running&quot;)<br> })<br> router.POST(&quot;/send-email&quot;, func(c *gin.Context) {<br>    var emailHandler EmailJob<br>    if err := c.ShouldBindJSON(&amp;emailHandler); err != nil {<br>       c.JSON(400, gin.H{&quot;error&quot;: &quot;Invalid input!&quot;, &quot;er&quot;: err})<br>       return<br>    }<br><br>    log.Printf(&quot;Email Service: creating new Email job #%v...&quot;, emailHandler.Sender)<br>    rand.Seed(time.Now().UnixNano())<br>    emailHandler.JobId = rand.Intn(1000)<br>    log.Printf(&quot;EmailService: created print job #%v&quot;, emailHandler.JobId)<br><br>    //send email here<br>    // sendEmail(emailHandler.Subject, emailHandler.Body+&quot; has been shipped&quot;)<br>    //<br>    c.JSON(200, emailHandler)<br> })<br> router.Run(&quot;:9000&quot;)<br>}</pre><p>Now our email service is complete. You can test this POST request from Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PY2wBfhu6xlpx_NjmR3TLw.png" /></figure><p>Now we can build a logistics Service. We can proceed to create a new file <em>logistics.go</em>. We need to take data from the merchant and add it to the <em>LogisticsJob</em> struct.</p><pre>package main<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>type LogisticsJob struct {<br> Type  string `json:&quot;type&quot; binding:&quot;required&quot;`<br> Email string `json:&quot;email&quot; binding:&quot;required&quot;`<br> Item  string `json:&quot;item&quot; binding:&quot;required&quot;`<br>}<br><br>func main() {<br> router := gin.Default()<br> router.GET(&quot;/status&quot;, func(c *gin.Context) {<br>    c.JSON(200, &quot;Logistics Server Running&quot;)<br> })<br> router.POST(&quot;/process&quot;, func(c *gin.Context) {<br>    var logistics LogisticsJob<br>    if err := c.ShouldBindJSON(&amp;logistics); err != nil {<br>       c.JSON(400, gin.H{&quot;error&quot;: &quot;Invalid input!&quot;, &quot;er&quot;: err})<br>     return<br>    }<br>    c.JSON(200, logistics)<br> })<br> router.Run(&quot;:9001&quot;)<br>}</pre><p>You can test it in Postman and the data return must be the same as the data that passed in the body section.</p><p>Now, Let’s combine these two applications. For it, we will make use of a resty library. It is used for sending REST API Requests. Installing it is quite easy.</p><pre>go get -u github.com/go-resty/resty/v2</pre><p>Now, we need to create a new function <em>createEmailJob </em>which will call our API in the Email service. We will also email <em>EmailJob </em>Struct for storing data.</p><pre>type EmailJob struct {<br>   Sender  string `json:&quot;sender&quot; binding:&quot;required&quot;`<br>   JobId   int    `json:&quot;job_id&quot; binding:&quot;gte=0&quot;`<br>   Subject string `json:&quot;subject&quot; binding:&quot;required&quot;`<br>   Email   string `json:&quot;email&quot; binding:&quot;required&quot;`<br>   Body    string `json:&quot;body&quot; binding:&quot;required&quot;`<br>}<br><br>func createEmailJob(emailJob EmailJob) EmailJob {<br>   client := resty.New()<br><br>   var p EmailJob<br><br>   _, err := client.R().<br>      SetBody(emailJob).<br>      SetResult(&amp;p).<br>      Post(&quot;http://localhost:9000/send-email&quot;)<br><br>   if err != nil {<br>      log.Println(&quot;EmailServer: unable to connect to EmailService&quot;)<br>      return EmailJob{}<br>   }<br>   log.Printf(&quot;EmailServer: created email job #%v via EmailService&quot;, p.JobId)<br>   return p<br> }</pre><p>Here, we attached the body to the rest library and make a POST request to get data from the email service. Now, let’s add these codes to our final file.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/go-resty/resty/v2&quot;<br>)<br><br>type EmailJob struct {<br>   Sender  string `json:&quot;sender&quot; binding:&quot;required&quot;`<br>   JobId   int    `json:&quot;job_id&quot; binding:&quot;gte=0&quot;`<br>   Subject string `json:&quot;subject&quot; binding:&quot;required&quot;`<br>   Email   string `json:&quot;email&quot; binding:&quot;required&quot;`<br>   Body    string `json:&quot;body&quot; binding:&quot;required&quot;`<br>}<br><br>type LogisticsJob struct {<br>   Type  string `json:&quot;type&quot; binding:&quot;required&quot;`<br>   Email string `json:&quot;email&quot; binding:&quot;required&quot;`<br>   Item  string `json:&quot;item&quot; binding:&quot;required&quot;`<br>}<br><br>func createEmailJob(emailJob EmailJob) EmailJob {<br>   client := resty.New()<br><br>   var p EmailJob<br><br>   _, err := client.R().<br>      SetBody(emailJob).<br>      SetResult(&amp;p).<br>      Post(&quot;http://localhost:9000/send-email&quot;)<br><br>   if err != nil {<br>      log.Println(&quot;EmailServer: unable to connect EmailService&quot;)<br>      return EmailJob{}<br>   }<br>   log.Printf(&quot;EmailServer: created email job #%v via EmailService&quot;, p.JobId)<br>   return p<br> }<br><br>func main() {<br>   router := gin.Default()<br>   router.GET(&quot;/status&quot;, func(c *gin.Context) {<br>      c.JSON(200, &quot;Logistics Server Running&quot;)<br>   })<br>   router.POST(&quot;/process&quot;, func(c *gin.Context) {<br>      var logistics LogisticsJob<br>      if err := c.ShouldBindJSON(&amp;logistics); err != nil {<br>         c.JSON(400, gin.H{&quot;error&quot;: &quot;Invalid input!&quot;, &quot;er&quot;: err})<br>      return<br>    }<br>    //processing<br>    emailData := EmailJob{<br>       Sender:  &quot;abc@logistics.com&quot;,<br>       Subject: &quot;Item&quot; + logistics.Type,<br>       Email:   logistics.Email,<br>       Body:    logistics.Item,<br>     }<br>    //save this data in database<br><br>    //calling email server<br><br>    result := createEmailJob(emailData)<br>    c.JSON(200, result)<br> })<br> router.Run(&quot;:9001&quot;)<br>}</pre><p>Now our logistics service is complete. If we check the path <a href="http://localhost:9001/process"><em>http://localhost:9001/process</em></a> with a required body, we can get a appropriate response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEPrHxL2wdh8RNGPnAylYw.png" /></figure><p>These two ports are acting as services and communicating for proper response. Here Logistics service takes data from the merchant and sends it to an email service to send emails to the desired people.</p><p>This is the implementation of Microservice in gin-gonic.</p><p>Happy Coding ❇️</p><p>github : <a href="https://github.com/Znerf/microservice-golang">https://github.com/Znerf/microservice-golang</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91851930036a" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/microservice-in-gin-golang-91851930036a">Microservice in Gin Golang</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GOing N+1 Query]]></title>
            <link>https://articles.readytowork.jp/going-n-1-query-17888f74ae7a?source=rss-478e5829a8d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/17888f74ae7a</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[loading-data]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Sagar Shrestha]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 18:57:13 GMT</pubDate>
            <atom:updated>2023-04-27T18:58:12.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to Sagar’s Concept session where we unveil some of the secrets of programming and discuss the problem we faced during coding. Today, we are going to discuss N+1 Query Problem.</p><p>For optimizing performance in backend development, we need to consider optimizing the backend architecture and our coding pattern. One of the problems we see is the N+1 Problem, which is observed during the retrieval of data from the database. By learning about it, we can avoid a performance pitfall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v06V87fVCbTmK80GateagQ.png" /></figure><p><strong>N+1 Query Problem</strong></p><blockquote>N+1 query problem is a problem in database retrieval where the related entities of an object are queried individually from a database, leading to O(n) queries where n is the number of related entities of the object.</blockquote><p>N+1 is a performance issue in which related properties of an entity are accessed individually rather than in bulk. When we access child entities individually, the complexity of the queries will be O(n). Let’s take an example of pseudocode in Go.</p><p>Consider we have a personal table with one child relation (for now). So, the child table references the parent table, which means the child table will have parent_id.</p><pre>persons = load_person();<br>for _, person := range persons{<br>  child = load_child_from_person(person.id)<br>}</pre><p>Here SQL queries will be like this:</p><pre>// inside load_person<br>SELECT * FROM person WHERE ...<br>//inside load_child_from_person<br>SELECT * FROM child WHERE child.person_id = 1<br>SELECT * FROM child WHERE child.person_id = 2<br>SELECT * FROM child WHERE child.person_id = 3<br>SELECT * FROM child WHERE child.person_id = 4<br>...</pre><p>Explaining the above code, a person’s data is fetched all at once, but a child’s data is fetched one at a time. This solution is prone to N+1 queries problem. This can be a problem for the performance of the system. For instance, Let’s assume there is a 1milisecond delay between the database and the backend server. 1ms is very low. But if there are 100 related data, then there will be a 100ms delay. And, if we are working on large relations, it can throttle our performance significantly. Database cost may rise higher than server cost.</p><p>Bulk queries can solve this error by handling all data individually rather than individually.</p><h3>Batching Queries</h3><p>In these methods, queries are batch such that one query is used rather than multiple queries, minimizing collective connection delays and increasing the performance of the system.</p><p>It can be illustrated in a Go pseudocode.</p><pre>persons = load_person();<br>childs = load_child();<br>for _, person := range persons{<br>  person.child := child[person.id]<br>}</pre><p>Here SQL queries will be like this:</p><pre>SELECT * FROM person WHERE ...<br>SELECT * FROM child WHERE person_id IN (1, 2, 3, 4, 5, ...)</pre><p>We have now successfully reduced the number of queries and increased our performance. With the present technology, ORM handles it successfully. But, we need to know if the architecture of ORM is prone to N+1 problems or not. We can also detect this with distributed tracing. Before we go to ORM we must know about Lazy loading and eager loading.</p><h3>Lazy Loading</h3><p>Lazy Loading is the technique where the related/child entities are fetched when needed. Child entities are not loaded until we need them, which reduces unnecessary fetching of data from the database.</p><p><strong>When to use lazy loading</strong></p><ol><li>In the main collection side of the app.</li><li>If we know the child&#39;s properties are called infrequently.</li></ol><h3>Eager Loading</h3><p>Eager Loading is the technique where child properties are loaded with the parent data. We iterate the data automatically. It can be achieved in GORM with <em>preload().</em></p><p><strong>When to use eager loading</strong></p><ol><li>If we need to access child entities frequently.</li><li>If there are lots of relations on the server side. It can reduce our complexity.</li></ol><p>Both have their own advantages and disadvantages and are in trade-offs. If we need to fetch single data with few relations, a single query can optimize our storage. But if we have large data with multiple relations, eager loading can increase our performance. All data is retrieved by a single query and can be cached to improve application performance.</p><p>Going back to the N+1 problem, lazy loading is prone to this problem while Eager loading handles this better in ORM.</p><p>Happy Coding 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17888f74ae7a" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/going-n-1-query-17888f74ae7a">GOing N+1 Query</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>