<?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 Arun deshan on Medium]]></title>
        <description><![CDATA[Stories by Arun deshan on Medium]]></description>
        <link>https://medium.com/@arundeshan?source=rss-5ecffd8cbe96------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H3T9lUM0A9Gb9Y0Qr8UnuQ.jpeg</url>
            <title>Stories by Arun deshan on Medium</title>
            <link>https://medium.com/@arundeshan?source=rss-5ecffd8cbe96------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:35:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arundeshan/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[Clean Code: Why You Should Avoid Switch Statements (And What to Do Instead)]]></title>
            <link>https://medium.com/@arundeshan/clean-code-why-you-should-avoid-switch-statements-and-what-to-do-instead-1839ab6223e4?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/1839ab6223e4</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[clean-code-principle]]></category>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 11:43:12 GMT</pubDate>
            <atom:updated>2025-06-06T11:43:12.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Q32UaZ_AmhRtBrG" /><figcaption>Photo by <a href="https://unsplash.com/@izzyfisch_?utm_source=medium&amp;utm_medium=referral">Isabella Fischer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In <em>Clean Code</em>, Robert C. Martin (Uncle Bob) emphasizes writing functions that are small, focused, and easy to maintain. One of the key problems he identifies is the use of switch statements (and long if-else chains). These constructs often violate core principles of clean code, such as:</p><ul><li>Single Responsibility Principle (SRP) — A function should have only one reason to change.</li><li>Open/Closed Principle (OCP) — Code should be open for extension but closed for modification.</li><li>Polymorphism over Conditionals — Favor object-oriented design over procedural branching.</li></ul><p>In this post, we’ll explore why switch statements are problematic and how to replace them with polymorphism in JavaScript.</p><h3>The Problem with Switch Statements</h3><p>Consider a payroll system where we calculate pay based on employee type:</p><h4>❌ Bad: A Large Switch Statement</h4><pre>function calculatePay(employee) {<br>  switch (employee.type) {<br>    case &#39;COMMISSIONED&#39;:<br>      return calculateCommissionedPay(employee);<br>    case &#39;HOURLY&#39;:<br>      return calculateHourlyPay(employee);<br>    case &#39;SALARIED&#39;:<br>      return calculateSalariedPay(employee);<br>    default:<br>      throw new Error(&#39;Invalid employee type&#39;);<br>  }<br>}</pre><h4>Why This Is Bad</h4><ol><li>Violates SRP — The function does more than one thing (handles multiple employee types).</li><li>Violates OCP — Adding a new employee type requires modifying this function.</li><li>Duplication — Similar switch statements will appear in isPayday(), deliverPay(), etc.</li><li>Hard to Test — Each new case increases complexity and testing burden.</li></ol><h3>The Solution: Polymorphism</h3><p>Instead of using switch, we can leverage polymorphism—where different employee types handle their own logic.</p><h4>✅ Good: Polymorphic Design</h4><pre>// Base Employee class (abstraction)<br>class Employee {<br>  calculatePay() {<br>    throw new Error(&#39;Method must be implemented&#39;);<br>  }<br><br>  isPayday() {<br>    throw new Error(&#39;Method must be implemented&#39;);<br>  }<br>}<br><br>// Employee Subclasses (concrete implementations)<br>class CommissionedEmployee extends Employee {<br>  constructor(record) {<br>    super();<br>    this.record = record;<br>  }<br><br>  calculatePay() {<br>    return `Pay for commissioned: ${this.record.name}`;  }<br>}<br><br>class HourlyEmployee extends Employee {<br>  calculatePay() {<br>    // Hourly-specific logic<br>  }<br>}<br><br>// Factory to create the right employee<br>class EmployeeFactory {<br>  static createEmployee(record) {<br>    switch (record.type) {<br>      case &#39;COMMISSIONED&#39;:<br>        return new CommissionedEmployee(record);<br>      case &#39;HOURLY&#39;:<br>        return new HourlyEmployee(record);<br>      default:<br>        throw new Error(&#39;Invalid employee type&#39;);<br>    }<br>  }<br>}<br><br>// Usage<br>const employeeRecord = { type: &#39;commissioned&#39;, name: &#39;Alice&#39; };<br>const employee = EmployeeFactory.createEmployee(employeeRecord);<br>const pay = employee.calculatePay(); // Polymorphic call!</pre><h4>Why This Is Better</h4><p>✔ Single Responsibility — Each employee class handles its own logic.<br>✔ Open/Closed — New types can be added without modifying existing code.<br>✔ No Duplication — No repeated switch statements across functions.<br>✔ Easier Testing – Each class can be tested independently.</p><h3>When Is a Switch Statement Acceptable?</h3><h4>Uncle Bob says:</h4><blockquote>“Switch statements can be tolerated if they appear only once, are used to create polymorphic objects, and are hidden behind an inheritance relationship.</blockquote><p>In our example, the switch is isolated inside a factory, so the rest of the system doesn’t see it.</p><h3>Conclusion</h3><ul><li>Avoid switch statements in business logic – They lead to large functions and duplication.</li><li>Use polymorphism instead – Encapsulate behavior in classes or strategy objects.</li><li>Hide the switch in a factory – If you must use one, keep it isolated.</li></ul><p><strong><em>By following these principles, your code becomes more maintainable, extensible, and testable — exactly what Clean Code advocates!</em></strong></p><h3>Further Reading</h3><p><em>Clean Code</em> — Robert C. Martin (Chapter 3: Functions)<br><em>Refactoring</em> — Martin Fowler (Replace Conditional with Polymorphism)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1839ab6223e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defensive Programming Part 01: Writing JavaScript Code That Doesn’t Break (Because Someone Will…]]></title>
            <link>https://medium.com/@arundeshan/defensive-programming-part-01-writing-javascript-code-that-doesnt-break-because-someone-will-855926089f1a?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/855926089f1a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[defensive-programming]]></category>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Tue, 20 May 2025 03:17:00 GMT</pubDate>
            <atom:updated>2025-05-20T03:17:00.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>Defensive Programming Part 01: Writing JavaScript Code That Doesn’t Break (Because Someone Will Break It)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*byc91imvkLu4ATPKrjuFOA.jpeg" /></figure><p>Imagine you’re writing a function, and you <em>know</em> someone — maybe even you in three weeks — will misuse it. They’ll pass the wrong type, forget a parameter, or send data that’s just plain weird. Defensive programming is the art of anticipating these mistakes and building code that stays robust, no matter what chaos comes its way. It’s like coding with a helmet on, protecting your runtime from crashing and burning.</p><p>Defensive programming isn’t just a set of tricks; it’s a mindset born from the early days of software engineering, especially in mission-critical systems like aerospace, banking, or medical applications, where a bug could mean lost satellites, millions of dollars, or even lives. Today, we’ll explore five key techniques to make your JavaScript code more defensive, complete with practical examples to inspire you to think proactively about error handling.</p><h3>1. Fail Fast to Save Your Runtime</h3><p>The first rule of defensive programming is to <em>fail fast</em>. If something’s wrong with the input, don’t let your function waste time processing it. Catch the issue early and bail out with a clear error message.</p><p>Consider a function that fetches a user based on an ID:</p><pre>function getUser(id) {<br>  // Log access, check cache, send analytics...<br>  console.log(&#39;Access logged&#39;);<br>  // Fetch user<br>  return fetch(`/api/user/${id}`);<br>}</pre><p>If id is missing, the function will still log access and attempt the fetch, which will fail. This wastes resources and pollutes logs with meaningless data. Instead, check the input first:</p><pre>function getUser(id) {<br>  if (!id) {<br>    throw new Error(&#39;ID is required&#39;);<br>  }<br>  // Log access, check cache, send analytics...<br>  console.log(&#39;Access logged&#39;);<br>  // Fetch user<br>  return fetch(`/api/user/${id}`);<br>}</pre><p>By failing fast, you prevent unnecessary work and make debugging easier with explicit errors.</p><h3>2. Check Types, Not Just Truthiness</h3><p>Relying on truthy/falsy checks can lead to subtle bugs. For example, consider a function that calculates the length of a string:</p><pre>function getLength(str) {<br>  if (!str) {<br>    return 0;<br>  }<br>  return str.length;<br>}</pre><p>This works for getLength(&quot;hello&quot;) (returns 5) and getLength(null) (returns 0), but getLength(123) returns undefined because numbers don’t have a length property. A better approach is to explicitly check the type:</p><pre>function getLength(str) {<br>  if (typeof str !== &#39;string&#39;) {<br>    throw new Error(&#39;A string is expected&#39;);<br>  }<br>  return str.length;<br>}</pre><p>Now, getLength(123) throws a clear error, and getLength(&quot;hello&quot;) still works. This is especially critical in JavaScript, where TypeScript’s compile-time checks disappear at runtime, leaving you to handle dynamic inputs from APIs or users.</p><h3>3. Sanitize and Validate Inputs</h3><p>Sometimes, inputs aren’t just the wrong type — they’re outright invalid. Take a function that parses a person’s age:</p><pre>function parseAge(ageStr) {<br>  return parseInt(ageStr);<br>}</pre><p>This returns 10 for parseAge(&quot;10&quot;), but parseAge(&quot;Cena&quot;) returns NaN, and parseAge(&quot;-10&quot;) returns -10, which is invalid for an age. Let’s sanitize and validate:</p><pre>function parseAge(ageStr) {<br>  const age = parseInt(ageStr);<br>  if (isNaN(age) || age &lt; 0) {<br>    throw new Error(&#39;A valid non-negative age is required&#39;);<br>  }<br>  return age;<br>}</pre><p>Now, parseAge(&quot;Cena&quot;) and parseAge(&quot;-10&quot;) throw errors, while parseAge(&quot;10&quot;) returns 10. Sanitizing (converting to a number) and validating (checking for NaN or negative values) ensures your function handles bad data gracefully.</p><h3>4. Use Defaults to Handle Missing Inputs</h3><p>When inputs are optional or missing, defaults can prevent crashes. Consider a greeting function:</p><pre>function greet(name) {<br>  return `Hello, ${name.toUpperCase()}`;<br>}</pre><p>Calling greet(&quot;Ki&quot;) returns &quot;Hello, KI&quot;, but greet() throws a TypeError because name is undefined. Adding a default parameter fixes this:</p><pre>function greet(name = &#39;Stranger&#39;) {<br>  return `Hello, ${name.toUpperCase()}`;<br>}</pre><p>Now, greet() returns &quot;Hello, STRANGER&quot;, and greet(&quot;Ki&quot;) still works. Defaults provide a fallback, ensuring your function remains functional even when inputs are missing.</p><h3>5. Guard Against Structure Changes with Optional Chaining</h3><p>APIs and external data sources are notorious for changing structures unexpectedly. A function accessing nested properties can crash if the structure isn’t what you expect:</p><pre>function getCity(user) {<br>  return user.address.city;<br>}</pre><p>If user.address is undefined, this throws an error. Optional chaining (?.) makes it safer:</p><pre>function getCity(user) {<br>  return user?.address?.city ?? &#39;Unknown&#39;;<br>}</pre><p>Now, getCity({ address: { city: &#39;Milano&#39; } }) returns &quot;Milano&quot;, and getCity({}) returns &quot;Unknown&quot;. This guards against missing properties, which is critical when dealing with unpredictable external data.</p><h3>Why Defensive Programming Matters</h3><p>Defensive programming is about anticipating failure and handling it gracefully. By failing fast, checking types, sanitizing inputs, using defaults, and guarding against structure changes, you create code that’s resilient to misuse — whether from users, APIs, or even your future self on a frantic Friday afternoon. These techniques aren’t exhaustive, but they instill a mindset of proactive error handling.</p><p>In JavaScript, where runtime errors can sneak past compile-time tools like TypeScript, defensive programming is your insurance policy. It’s not about being paranoid; it’s about being prepared. So, code like someone’s going to break your function — because they will.</p><blockquote><em>Ready to make your code bulletproof? Try these techniques in your next JavaScript project and share your tips in the comments!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=855926089f1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Response Handler for .NET Minimal APIs]]></title>
            <link>https://medium.com/@arundeshan/building-a-custom-response-handler-for-net-minimal-apis-cef2a7b09413?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/cef2a7b09413</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 14:14:20 GMT</pubDate>
            <atom:updated>2025-03-12T14:14:20.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Custom Response Handler for .NET Minimal APIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*2W2o-BYqVDUYryjGfaHW5g.jpeg" /></figure><p>Building APIs with .NET Minimal APIs is a breeze, but as your project grows, handling responses consistently can become a challenge. How do you ensure that every endpoint returns a standardized response? How do you simplify error handling and reduce boilerplate code?</p><p>In this blog post, I’ll walk you through how I built a <strong>custom response handler</strong> for .NET Minimal APIs, using a <strong>Post management system</strong> as an example. By the end, you’ll have a reusable, consistent, and maintainable way to handle API responses in your projects.</p><h4>Step 1: Setting Up the Project Structure</h4><pre>- Program.cs<br>- EndPoints/<br>- Enums/<br>- Constants/<br>- Interfaces/<br>- Contracts/<br>- Entities/<br>- Services/</pre><h4>Step 2: Defining the Custom Response Structure</h4><p>Before implementing the ApiResponse&lt;T&gt; class, we need to define the ErrorCode and HttpStatusCode classes. These will help standardize error handling and HTTP status codes across your API.</p><ol><li><strong>ErrorCode Enum:</strong> The ErrorCode enum defines all possible error codes that your API can return. This makes it easier to handle and communicate specific errors.</li></ol><pre>// Enums/ErrorCode.cs<br>    public enum ErrorCode<br>    {<br>        // Default<br>        UnDefinedError,<br><br>        // Authentication &amp; Authorization<br>        EmailNotVerified,<br>        InvalidCredentials,<br>        AccountLocked,<br>        AccessDenied,<br>        InvalidToken,<br>        TokenRequired,<br><br>        // Validation<br>        ValidationError,<br>        MissingRequiredField,<br>        InvalidEmailFormat,<br>        PasswordTooWeak,<br><br>        // User Management<br>        UserNotFound,<br>        UserAlreadyExists,<br>        InvalidUserRole,<br><br>        // Resource Management<br>        ResourceNotFound,<br>        ResourceAlreadyExists,<br>        ResourceLimitExceeded,<br><br>        // System &amp; Server<br>        InternalServerError,<br>        ServiceUnavailable,<br>        DatabaseError,<br>        NetworkError,<br><br>        // Payment &amp; Subscription<br>        PaymentFailed,<br>        SubscriptionExpired,<br>        InvalidPaymentMethod,<br><br>        // Third-Party Integration<br>        ThirdPartyApiError,<br>        ExternalServiceUnavailable,<br><br>        // Custom Business Logic<br>        InvalidOperation,<br>        QuotaExceeded,<br>        InvalidInvitationCode<br>    }</pre><p>One of the key features of this approach is the use of an ErrorCode enum. This enum not only helps identify specific errors on the backend but also enables the frontend to handle errors more effectively. By sharing this enum between the backend and frontend, you can create a seamless error-handling experience for your users. Plus, it’s easy to extend and customize as your application evolves.</p><p>2.<strong> HttpStatusCode Class:</strong> The HttpStatusCode class defines constants for common HTTP status codes. This ensures consistency when setting status codes in your responses.</p><pre>// Constants/HttpStatusCode.cs<br>    public static class HttpStatusCode<br>    {<br>        public const int Ok = 200;<br>        public const int Created = 201;<br>        public const int Accepted = 202;<br>        public const int NoContent = 204;<br><br>        public const int BadRequest = 400;<br>        public const int Unauthorized = 401;<br>        public const int Forbidden = 403;<br>        public const int NotFound = 404;<br>        public const int Conflict = 409;<br><br>        public const int InternalServerError = 500;<br>        public const int NotImplemented = 501;<br>        public const int BadGateway = 502;<br>        public const int ServiceUnavailable = 503;<br>    }</pre><p>3. <strong>ApiResponse&lt;T&gt; Class: </strong>Now that we have the ErrorCode and HttpStatusCode classes, we can implement the ApiResponse&lt;T&gt; class. This class standardizes the structure of API responses, making it easier to handle success and error scenarios.</p><pre>// Contracts/ApiResponse.cs<br>    public class ApiResponse&lt;T&gt;<br>    {<br>        public bool Success { get; set; }<br>        public T? Data { get; set; }<br>        public string Message { get; set; } = string.Empty;<br>        public int StatusCode { get; set; }<br>        public ErrorCode? ErrorCode { get; set; }<br><br>        public static ApiResponse&lt;T&gt; SuccessResult(T data, int statusCode = HttpStatusCode.Ok, string message = &quot;Success&quot;)<br>        {<br>            return new ApiResponse&lt;T&gt;<br>            {<br>                Success = true,<br>                Data = data,<br>                StatusCode = statusCode,<br>                Message = message<br>            };<br>        }<br><br>        public static ApiResponse&lt;T&gt; ErrorResult(string message, int statusCode, ErrorCode errorCode = ErrorCode.UnDefinedError)<br>        {<br>            return new ApiResponse&lt;T&gt;<br>            {<br>                Success = false,<br>                StatusCode = statusCode,<br>                Message = message,<br>                ErrorCode = errorCode<br>            };<br>        }<br>    }</pre><h4>Step 3: Implementing the Post Domain</h4><ul><li>Define the Post entity and related DTOs.</li><li>Create a service interface (IPostService) and its implementation (PostService).</li><li>Implement CRUD operations for posts.</li></ul><ol><li><strong>Define the </strong><strong>Post Entity:</strong></li></ol><pre>// Entities/Post.cs<br>public class Post<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; } = string.Empty;<br>    public string Content { get; set; } = string.Empty;<br>}</pre><p><strong>2. Create a DTO for Creating Posts:</strong></p><pre>// Contracts/CreatePostRequest.cs<br>public class CreatePostRequest<br>{<br>    public string Title { get; set; } = string.Empty;<br>    public string Content { get; set; } = string.Empty;<br>}</pre><p><strong>3. Define the </strong><strong>IPostService Interface:</strong></p><pre>// Interfaces/IPostService.cs<br>public interface IPostService<br>{<br>    ApiResponse&lt;Post&gt; CreatePost(CreatePostRequest request);<br>    ApiResponse&lt;Post&gt; GetPost(int id);<br>    ApiResponse&lt;List&lt;Post&gt;&gt; GetAllPosts();<br>}</pre><p><strong>4. Implement the </strong><strong>PostService:</strong></p><pre>// Services/PostService.cs<br>public class PostService : IPostService<br>{<br>    private static readonly List&lt;Post&gt; Posts = [];<br><br>    public ApiResponse&lt;Post&gt; CreatePost(CreatePostRequest request)<br>    {<br>        var post = new Post { Id = Posts.Count + 1, Title = request.Title, Content = request.Content };<br>        Posts.Add(post);<br>        return ApiResponse&lt;Post&gt;.SuccessResult(post, HttpStatusCode.Created, &quot;Post created successfully.&quot;);<br>    }<br><br>    public ApiResponse&lt;Post&gt; GetPost(int id)<br>    {<br>        var post = Posts.FirstOrDefault(p =&gt; p.Id == id);<br>        if (post == null)<br>            return ApiResponse&lt;Post&gt;.ErrorResult(&quot;Post not found.&quot;, HttpStatusCode.NotFound,<br>                ErrorCode.ResourceNotFound);<br><br>        return ApiResponse&lt;Post&gt;.SuccessResult(post);<br>    }<br><br>    public ApiResponse&lt;List&lt;Post&gt;&gt; GetAllPosts()<br>    {<br>        return ApiResponse&lt;List&lt;Post&gt;&gt;.SuccessResult(Posts);<br>    }<br>}</pre><h4>Step 4: Creating Endpoints for Post Management</h4><ul><li>Use Minimal APIs to define endpoints for creating and retrieving posts.</li><li>Integrate the custom response handler (ApiResponse&lt;T&gt;) into the endpoints.</li></ul><ol><li><strong>Register the Service in </strong><strong>Program.cs:</strong></li></ol><pre>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddScoped&lt;IPostService, PostService&gt;();<br>var app = builder.Build();</pre><p><strong>2. Define Endpoints:</strong></p><pre>// EndPoints/PostEndpoints.cs<br>public static class PostEndpoints<br>{<br>    public static void MapPostEndpoints(this WebApplication app)<br>    {<br>        app.MapPost(&quot;/posts&quot;, (CreatePostRequest request, IPostService postService) =&gt;<br>        {<br>            var response = postService.CreatePost(request);<br>            return Results.Json(response, statusCode: response.StatusCode);<br>        });<br><br>        app.MapGet(&quot;/posts/{id:int}&quot;, (int id, IPostService postService) =&gt;<br>        {<br>            var response = postService.GetPost(id);<br>            return Results.Json(response, statusCode: response.StatusCode);<br>        });<br>        <br>        app.MapGet(&quot;/posts&quot;, (IPostService postService) =&gt;<br>        {<br>            var response = postService.GetAllPosts();<br>            return Results.Json(response, statusCode: response.StatusCode);<br>        });<br>    }<br>}</pre><p><strong>3. Use Endpoints in </strong><strong>Program.cs:</strong></p><pre>app.MapPostEndpoints();<br>app.Run();</pre><h4>Step 5: Testing the API</h4><ul><li><strong>Create a Post</strong></li></ul><pre>POST /posts<br>{<br>    &quot;title&quot;: &quot;My First Post&quot;,<br>    &quot;content&quot;: &quot;This is the content of my first post.&quot;<br>}</pre><pre>{<br>    &quot;success&quot;: true,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;My First Post&quot;,<br>        &quot;content&quot;: &quot;This is the content of my first post.&quot;<br>    },<br>    &quot;message&quot;: &quot;Post created successfully.&quot;,<br>    &quot;statusCode&quot;: 201,<br>    &quot;errorCode&quot;: null<br>}</pre><ul><li><strong>Get a Post</strong></li></ul><pre>GET /posts/1</pre><pre>{<br>    &quot;success&quot;: true,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;My First Post&quot;,<br>        &quot;content&quot;: &quot;This is the content of my first post.&quot;<br>    },<br>    &quot;message&quot;: &quot;Success&quot;,<br>    &quot;statusCode&quot;: 200,<br>    &quot;errorCode&quot;: null<br>}</pre><ul><li>Get all Post</li></ul><pre>GET /posts</pre><pre>{<br>    &quot;success&quot;: true,<br>    &quot;data&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;My First Post&quot;,<br>            &quot;content&quot;: &quot;This is the content of my first post.&quot;<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;My Second Post&quot;,<br>            &quot;content&quot;: &quot;This is the content of my second post.&quot;<br>        }<br>    ],<br>    &quot;message&quot;: &quot;Success&quot;,<br>    &quot;statusCode&quot;: 200,<br>    &quot;errorCode&quot;: null<br>}</pre><ul><li><strong>Error Scenario (Post Not Found)</strong></li></ul><pre>GET /posts/999</pre><pre>{<br>    &quot;success&quot;: false,<br>    &quot;data&quot;: null,<br>    &quot;message&quot;: &quot;Post not found.&quot;,<br>    &quot;statusCode&quot;: 404,<br>    &quot;errorCode&quot;: 14<br>}</pre><h4>Conclusion</h4><p>Standardizing API responses doesn’t have to be complicated. With a custom response handler like ApiResponse&lt;T&gt;, you can ensure consistency, reduce boilerplate code, and simplify error handling in your .NET Minimal APIs. By leveraging enums like ErrorCode and HttpStatusCode, you can make your API more robust and developer-friendly. Whether you’re building a small project or a large-scale application, this approach will save you time and make your codebase cleaner and more maintainable. Give it a try in your next project, and let me know how it works for you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cef2a7b09413" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina with MySQL for CRUD operations]]></title>
            <link>https://medium.com/@arundeshan/ballerina-with-mysql-for-crud-operations-cd1c992e26bc?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd1c992e26bc</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 20:00:42 GMT</pubDate>
            <atom:updated>2024-11-07T20:00:42.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddJFYtWc2YumDpfOmzevPA.png" /></figure><h3>Step 1: Set Up the Ballerina Project</h3><ul><li>First, create a new Ballerina project by running the following command in your terminal:</li></ul><pre>bal new ballerina_crud_application</pre><ul><li>Navigate into the project directory:</li></ul><pre>cd ballerina_crud_application</pre><ul><li>Open the project in your preferred code editor (e.g., Visual Studio Code) to begin development:</li></ul><pre>code .</pre><h3>Step 2: Set Up the Basic Service</h3><ul><li>Open the service.bal file located in the ballerina_crud_application project folder.</li><li>Clear out any default code within service.bal to start fresh.</li><li>Begin by importing the HTTP module, which will allow you to set up an HTTP service:</li></ul><pre>import ballerina/http;</pre><ul><li>Create a simple HTTP service that listens on port 9090. This service will include a test GET endpoint for retrieving a sample response. Add the following code to define the service and endpoint:</li></ul><pre>service / on new http:Listener(9090) {<br>    resource function get books() returns string {<br>        return &quot;Book list&quot;;<br>    }<br>}</pre><h3>Step 3: Run and Test the Application</h3><ul><li>To start the Ballerina service, navigate to the project directory in your terminal and run:</li></ul><pre>bal run</pre><p>This command will compile and start your service, making it available for testing on localhost at port 9090.</p><ul><li>Now, open Postman (or your preferred API testing tool) to test the GET endpoint. In Postman, set up a new request with the following details:</li><li><strong>Method</strong>: GET</li><li><strong>URL</strong>: <a href="http://localhost:9090/books">http://localhost:9090/books</a></li><li>Send the request. If everything is set up correctly, you should receive the following response:</li></ul><pre>Book list</pre><h3>Step 4: Organize Database module Files</h3><p>To manage the database interactions, let’s create a structured setup under a module folder within the project, specifically for database functionality. This will help in organizing the Ballerina files related to database operations, making the code easier to maintain and scale.</p><ul><li>Inside the ballerina_crud_application project folder, create a modules folder.</li><li>Within modules, create another folder called database. This folder will house all files related to the database client and operations.</li></ul><pre>ballerina_crud_application/<br>├── modules/<br>│   └── database/<br>│       ├── client.bal<br>│       ├── constant.bal<br>│       ├── db_functions.bal<br>│       ├── db_queries.bal<br>│       ├── enums.bal<br>│       ├── types.bal<br>│       └── utils.bal</pre><ul><li><strong>client.bal</strong>: Handles the initialization of the MySQL database client and manages connections.</li><li><strong>constant.bal</strong>: Stores constant values for easy modification and reusability.</li><li><strong>db_function.bal</strong>: Contains functions to perform CRUD operations (create, read, update, delete) on the Book table.</li><li><strong>db_queries.bal</strong>: Stores raw SQL queries as reusable constants for better query management and cleaner code.</li><li><strong>enums.bal</strong>: Defines enums for any database-related constants or types, such as status codes or category types.</li><li><strong>types.bal</strong>: Declares the custom types or data structures used throughout the database layer, such as the Book record.</li><li><strong>utils.bal</strong>: Provides utility functions.</li></ul><h3>Step 5: Update the client.bal File</h3><p>In the client.bal file, we’ll set up the MySQL database client to connect to the book_shop database.</p><ul><li><strong>Import Required Modules: </strong>First, import the MySQL connector and driver in client.bal:</li></ul><pre>import ballerinax/mysql;<br>import ballerinax/mysql.driver as _;</pre><ul><li><strong>Define Database Client Configuration: </strong>The database client requires configuration details like the user, password, database name, host, and port. We’ll define a DatabaseConfig record for these parameters in types.bal. In the types.bal file, define the DatabaseConfig record:</li></ul><pre>type DatabaseConfig record {|<br>    # User of the database<br>    string user;<br>    # Password of the database<br>    string password;<br>    # Name of the database<br>    string database;<br>    # Host of the database<br>    string host;<br>    # Port<br>    int port;<br>|};</pre><ul><li><strong>Configure and Initialize the Database Client: </strong>Now, in client.bal, use the DatabaseConfig record to configure the MySQL client:</li></ul><pre># Database Client Configuration.<br>configurable DatabaseConfig dbConfig = ?;<br><br>final mysql:Client dbClient = check new (<br>    user = dbConfig.user,<br>    password = dbConfig.password,<br>    database = dbConfig.database,<br>    host = dbConfig.host,<br>    port = dbConfig.port<br>);</pre><ul><li><strong>configurable DatabaseConfig dbConfig = ?;</strong>: Makes the dbConfig record configurable, allowing database details to be provided during deployment or runtime.</li><li><strong>mysql:Client dbClient</strong>: Creates a MySQL client instance using the dbConfig values for connecting to the database.</li></ul><h3>Step 6: Create the Config.toml File</h3><ul><li><strong>Create a </strong><strong>Config.toml File: </strong>In the root directory of your ballerina_crud_application project, create a file named Config.toml. This file will contain the database configuration details required to initialize the MySQL client.</li><li><strong>Add Database Configuration to </strong><strong>Config.toml</strong>: Inside Config.toml, add the following configuration:</li></ul><pre>[ballerina_crud_application.database.dbConfig]<br>user=&quot;root&quot;<br>password=&quot;&quot;<br>host=&quot;localhost&quot;<br>port=3306<br>database=&quot;book_shop&quot;</pre><ul><li><strong>Add </strong><strong>Config.toml to </strong><strong>.gitignore</strong>: To prevent sensitive information in Config.toml from being exposed, add it to the .gitignore file:</li></ul><pre>echo &quot;Config.toml&quot; &gt;&gt; .gitignore</pre><h3>Step 7: Create Database and Table in MySQL Workbench</h3><h4>1. Open MySQL Workbench</h4><ul><li>Open <strong>MySQL Workbench</strong> on your system.</li></ul><h4>2. Create a New Connection</h4><ul><li><strong>Connection Name</strong>: Any name (e.g., “Book Shop DB”)</li><li><strong>Username</strong>: root</li><li><strong>Password</strong>: Leave it empty or enter if required</li><li><strong>Host</strong>: localhost</li><li><strong>Port</strong>: 3306</li><li><strong>Default Schema</strong>: Leave it empty (we’ll create the database)</li></ul><h4>3. Create the book_shop Database</h4><ul><li>Once connected to MySQL, click on the <strong>SQL</strong> icon in the top toolbar to open a new query tab.</li><li>Run the following query to create the book_shop database:</li></ul><pre>CREATE DATABASE IF NOT EXISTS book_shop;<br>USE book_shop;</pre><h4>4. Create the book Table</h4><ul><li>In the same query tab, run the following query to create the book table:</li></ul><pre>CREATE TABLE IF NOT EXISTS book (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    title VARCHAR(255) NOT NULL,<br>    author VARCHAR(255) NOT NULL,<br>    published_year VARCHAR(50) NOT NULL,<br>    genre VARCHAR(100),<br>    price DECIMAL(10, 2) NOT NULL,<br>    quantity INT NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>);</pre><h4>5. Insert Sample Data into the book Table</h4><ul><li>Now, insert some sample data to the book table with this query:</li></ul><pre>INSERT INTO book (title, author, published_year, genre, price, quantity)<br>VALUES (&quot;The Great Gatsby&quot;, &quot;F. Scott Fitzgerald&quot;, &quot;1925&quot;, &quot;Classic&quot;, 10.99, 20);</pre><p><em>Now, the </em><em>book_shop database and the </em><em>book table are ready with sample data. You can now proceed to use this database in your Ballerina CRUD application.</em></p><h3>Step 8: Create Query Function to Get Books</h3><p>In the db_queries.bal file, define the query function to fetch all books from the book table. Here&#39;s the code:</p><pre>import ballerina/sql;<br><br>isolated function getBooksQuery() returns sql:ParameterizedQuery =&gt; `<br>    SELECT <br>        id,<br>        title,<br>        author,<br>        published_year,<br>        genre,<br>        price,<br>        quantity<br>    FROM <br>        book;<br>`;</pre><h3>Step 9: Create Database Function to Get Books</h3><h4><strong>1. In the </strong><strong>db_functions.bal File</strong></h4><ul><li>Define the function getBooks that fetches data from the database using the query function getBooksQuery:</li></ul><pre>import ballerina/sql;<br><br>// Define the function to fetch books from the database.<br>public isolated function getBooks() returns Book[]|sql:Error {<br>    // Execute the query and return a stream of Book records.<br>    stream&lt;Book, sql:Error?&gt; resultStream = dbClient-&gt;query(getBooksQuery());<br>    <br>    // Check if the result is a stream of Book records.<br>    if resultStream is stream&lt;Book&gt; {<br>        return from Book book in resultStream<br>            select book;<br>    }<br>    <br>    // If there is an error, return an error message.<br>    return error(&quot;Error fetching books&quot;);<br>}</pre><h4><strong>2. Define the </strong><strong>Book Record Type in </strong><strong>types.bal</strong></h4><ul><li>In the types.bal file, define the Book record type with the appropriate SQL column annotations:</li></ul><pre># Book record type.<br>public type Book record {|<br>    # Book ID<br>    @sql:Column {name: &quot;id&quot;}<br>    readonly int id;<br><br>    # Book title<br>    @sql:Column {name: &quot;title&quot;}<br>    string title;<br><br>    # Book author<br>    @sql:Column {name: &quot;author&quot;}<br>    string author;<br><br>    # Book published year<br>    @sql:Column {name: &quot;published_year&quot;}<br>    string publishedYear;<br><br>    # Book genre<br>    @sql:Column {name: &quot;genre&quot;}<br>    string genre;<br><br>    # Book price<br>    @sql:Column {name: &quot;price&quot;}<br>    string price;<br><br>    # Book quantity<br>    @sql:Column {name: &quot;quantity&quot;}      <br>    string quantity;    <br>|};        </pre><blockquote>If you encounter an error like <em>undefined module &#39;sql&#39;</em> while importing the <em>sql</em> module, follow these steps to resolve it:</blockquote><ul><li>Run the following command on terminal to pull the necessary SQL module and then <strong>Restart Your IDE.</strong></li></ul><pre>bal pull ballerina/sql</pre><h3>Step 10: Create the get API Resource Function in service.bal</h3><ul><li><strong>Define the </strong><strong>get Resource for Retrieving Books: </strong>In the service.bal file, create a resource function to handle the GET /books request:</li></ul><pre>import ballerina_crud_application.database;<br><br>import ballerina/http;<br><br>service / on new http:Listener(9090) {<br><br>    // Resource function to get all books.<br>    resource function get books() returns database:Book[]|http:InternalServerError {<br>        // Call the getBooks function to fetch data from the database.<br>        database:Book[]|error response = database:getBooks();<br><br>        // If there&#39;s an error while fetching, return an internal server error.<br>        if response is error {<br>            return &lt;http:InternalServerError&gt;{<br>                body: &quot;Error while retrieving books&quot;<br>            };<br>        }<br><br>        // Return the response containing the list of books.<br>        return response;<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>resource function get books()</strong>: This function defines the GET HTTP endpoint for /books. When this endpoint is accessed, the function is triggered.</li><li><strong>database:getBooks()</strong>: The function calls getBooks (defined in db_functions.bal) to fetch the list of books from the database.</li><li><strong>Error Handling</strong>: If the getBooks function returns an error, the API responds with an internal server error (http:InternalServerError) and a message &quot;Error while retrieving books&quot; <em>OR</em> If successful, the list of books is returned as a response.</li><li><strong>Return Type</strong>: The return type is database:Book[]|http:InternalServerError, which means it can either return a list of Book records (from the database) or an InternalServerError if something goes wrong.</li></ul><h3>Step 11: Implement the POST Method for Creating Books</h3><h4>1. Update the db_queries.bal File</h4><ul><li>Create a query to insert a new book into the book table. Add the following function to the db_queries.bal file:</li></ul><pre>isolated function insertBookQuery(BookCreate payload) returns sql:ParameterizedQuery =&gt; `<br>    INSERT INTO book<br>        (<br>            title,<br>            author,<br>            published_year,<br>            genre,<br>            price,<br>            quantity<br>        )<br>    VALUES<br>        (<br>            ${payload.title},<br>            ${payload.author},<br>            ${payload.publishedYear},<br>            ${payload.genre},<br>            ${payload.price},<br>            ${payload.quantity}<br>        )<br>`;</pre><h4>2. Update the types.bal File</h4><ul><li>Define the BookCreate record type in the types.bal file to represent the data needed to create a book.</li></ul><pre># Book create record type.<br>public type BookCreate record {|<br>    # Book title<br>    string title;<br>    # Book author<br>    string author;<br>    # Book published year<br>    string publishedYear;<br>    # Book genre<br>    string genre;<br>    # Book price<br>    decimal price;<br>    # Book quantity<br>    int quantity;<br>|};</pre><h4>3. Update the db_functions.bal File</h4><ul><li>Create the function insertBook that will execute the insert query defined earlier.</li></ul><pre>public isolated function insertBook(BookCreate payload) returns sql:ExecutionResult|sql:Error {<br>    return dbClient-&gt;execute(insertBookQuery(payload));<br>}</pre><h4>4. Update the service.bal File</h4><ul><li>Define the POST /books API endpoint to handle the creation of a new book.</li></ul><pre>    resource function post books(database:BookCreate book) returns http:Created|http:InternalServerError {<br>        sql:ExecutionResult|sql:Error response = database:insertBook(book);<br>        if response is error {<br>            return &lt;http:InternalServerError&gt;{<br>                body: &quot;Error while inserting book&quot;<br>            };<br>        }<br>        return http:CREATED;<br>    }</pre><h3>Step 12: Implement the DELETE Method for Removing a Book</h3><ul><li>Update db_queries.bal</li></ul><pre>isolated function deleteBookQuery(int bookId) returns sql:ParameterizedQuery =&gt; `<br>    DELETE FROM book WHERE id = ${bookId}<br>`;</pre><ul><li>Update db_functions.bal</li></ul><pre>public isolated function deleteBook(int bookId) returns sql:ExecutionResult|sql:Error {<br>    return dbClient-&gt;execute(deleteBookQuery(bookId));<br>}</pre><ul><li>Update service.bal</li></ul><pre>resource function delete books/[int id]() returns http:NoContent|http:InternalServerError {<br>     sql:ExecutionResult|sql:Error response = database:deleteBook(id);<br><br>     if response is error {<br>         return &lt;http:InternalServerError&gt;{<br>             body: &quot;Error while deleting book&quot;<br>         };<br>     }<br><br>     return http:NO_CONTENT;<br>}</pre><h3>Step 13: Implement the PATCH Method for Updating Book Fields</h3><ul><li>Update db_queries.bal</li></ul><pre>isolated function updateBookQuery(int bookId, BookUpdate payload) returns sql:ParameterizedQuery =&gt;`<br>    UPDATE book<br>        SET <br>            title = COALESCE(${payload.title}, title),<br>            author = COALESCE(${payload.author}, author),<br>            published_year = COALESCE(${payload.publishedYear}, published_year),<br>            genre = COALESCE(${payload.genre}, genre),<br>            price = COALESCE(${payload.price}, price),<br>            quantity = COALESCE(${payload.quantity}, quantity)<br>        WHERE id = ${bookId}<br>`;</pre><ul><li>Update types.bal</li></ul><pre># Book update record type.<br>public type BookUpdate record {|<br>    # Book title<br>    string? title = ();<br>    # Book author<br>    string? author = ();<br>    # Book published year<br>    string? publishedYear = ();<br>    # Book genre<br>    string? genre = ();<br>    # Book price<br>    decimal? price = ();<br>    # Book quantity<br>    int? quantity = ();<br>|};</pre><ul><li>Update db_functions.bal</li></ul><pre>public isolated function updateBook(int bookId, BookUpdate payload) returns sql:ExecutionResult|sql:Error {<br>    return dbClient-&gt;execute(updateBookQuery(bookId, payload));<br>}</pre><ul><li>Update service.bal</li></ul><pre>resource function patch books/[int id](database:BookUpdate book) returns http:NoContent|http:InternalServerError {<br>    sql:ExecutionResult|sql:Error response = database:updateBook(id, book);<br><br>    if response is error {<br>        return &lt;http:InternalServerError&gt;{<br>            body: &quot;Error while updating book&quot;<br>        };<br>    }<br><br>    return http:NO_CONTENT;<br>}</pre><h3>Conclusion</h3><p>In this guide, we created a simple CRUD application for managing books using Ballerina and MySQL. By following these steps, you can set up endpoints to add, retrieve, update, and delete records in your database, while also managing configurations and structuring code effectively for scalability. This project demonstrates the power of Ballerina’s SQL module and the simplicity it offers for building robust, database-integrated REST APIs.</p><p>Repo : <a href="https://github.com/deshan68/ballerina_crud_application/tree/v1.0.1">https://github.com/deshan68/ballerina_crud_application/tree/v1.0.1</a></p><p>For more details on Ballerina and its features, visit the <a href="https://ballerina.io/">Ballerina official site</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd1c992e26bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to containerize MERN application with Docker Compose]]></title>
            <link>https://medium.com/@arundeshan/how-to-containerize-mern-application-with-docker-compose-e5fec828c1d3?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5fec828c1d3</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 18:33:48 GMT</pubDate>
            <atom:updated>2024-11-06T18:33:48.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awKRX8iuxm5r0yclfdlwRQ.png" /></figure><h3>Table of Contents</h3><p><strong>1. Clone the Repository<br></strong>Begin by cloning the GitHub repository that contains a basic MERN application. This includes:</p><ul><li>A simple React application (client).</li><li>A Node.js/Express server with basic GET and POST methods that connects to MongoDB(api).</li></ul><p><strong>2. Create Dockerfile and .dockerignore for Each Project<br></strong>Set up a Dockerfile in both the client and server projects. These files specify the instructions for building container images for each part of the MERN stack. Additionally, create .dockerignore files to exclude unnecessary files and folders from the image, reducing build size and time.</p><p><strong>3. Set Up docker-compose.yml<br></strong>Create a docker-compose.yml file to define and manage the MERN application&#39;s services (client, server, and MongoDB) in one file. Docker Compose allows us to configure and start these services together, making it easier to set up the full-stack environment.</p><p><strong>4. Test the Containerized Application<br></strong>Run docker compose up to start the application, then verify each service to ensure the client can communicate with the server and database. Test the functionality by making sample requests to the API and interacting with the frontend.</p><h3>Step 1: Clone the Repository</h3><ul><li><strong>Command to Clone the Repository:</strong></li></ul><pre>git clone https://github.com/deshan68/Containerize-MERN-Application.git<br>cd Containerize-MERN-Application</pre><ul><li><strong>Install Dependencies: </strong>After cloning, navigate to each project folder (client and server) and install the necessary modules:</li></ul><pre>cd client<br>npm install</pre><ul><li>Then, for the server:</li></ul><pre>cd ../api<br>npm install</pre><h3>Step 2: <strong>Create Dockerfile and .dockerignore for Each Project</strong></h3><p>To containerize the MERN application, we need to set up Dockerfile and .dockerignore files for both the client (React) and server (Node.js) projects. These files define the environment and steps needed to build container images for each project.</p><h4>Dockerfile and .dockerignore for the api</h4><ul><li>The server’s Dockerfile specifies a Node.js environment, installs dependencies, and sets up the server to run in a container.</li><li>Dockerfile (Server/api):</li></ul><pre># Base image with Node.js<br>FROM node:20.14<br><br># Install nodemon globally for auto-restarting on code changes<br>RUN npm install -g nodemon<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy all files from the current directory into the container<br>COPY . .<br><br># Install dependencies<br>RUN npm install<br><br># Expose port 4000 for the server<br>EXPOSE 4000<br><br># Start the server using npm<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><ul><li>.dockerignore (api):</li></ul><pre>node_modules<br>package-lock.json</pre><h4>Dockerfile and .dockerignore for the Client</h4><ul><li>The client’s Dockerfile sets up a containerized environment for the React application, handling dependencies and build configurations.</li><li>Dockerfile (Client):</li></ul><pre># Base image with Node.js<br>FROM node:20.14<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy package.json first to leverage Docker&#39;s layer caching<br>COPY package.json .<br><br># Install dependencies<br>RUN npm install<br><br># Copy the rest of the client files into the container<br>COPY . .<br><br># Expose port 3000 for the client<br>EXPOSE 3000<br><br># Start the React app in development mode<br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><ul><li><strong>.dockerignore (Client)</strong>:</li></ul><pre>node_modules<br>package-lock.json</pre><p>After setting up the Dockerfiles and .dockerignore files in each project folder (server and client), your project structure should look similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*4-ZECs5tbZ0S91UQQEeLqQ.png" /></figure><h3>Step 3: <strong>Set Up docker-compose.yml</strong></h3><p>The docker-compose.yml file defines and configures the three main services of our MERN application: MongoDB (database), API server (backend), and client (frontend). Here’s a breakdown of each attribute used:</p><pre>services:<br>  mongo:<br>    image: mongo<br>    container_name: mongo_container<br>    volumes:<br>      - mongo_data:/data/db<br>    ports:<br>      - &quot;27017:27017&quot;</pre><ul><li><strong>image</strong>: Specifies the MongoDB image to use. Docker will pull the latest MongoDB image from Docker Hub if not already available locally.</li><li><strong>container_name</strong>: Sets a custom name for the MongoDB container, making it easier to reference.</li><li><strong>volumes</strong>: Maps a Docker volume to /data/db inside the container, where MongoDB stores its data. This setup ensures data persistence.</li><li><strong>ports</strong>: Exposes port 27017 to allow external access to MongoDB.</li></ul><pre>  api:<br>    build: ./api<br>    container_name: server_container<br>    ports:<br>      - &quot;4000:4000&quot;<br>    depends_on:<br>      - mongo<br>    volumes:<br>      - ./api:/app<br>      - /app/node_modules<br>    environment:<br>      - MONGODB_URL=mongodb://mongo:27017/userDB</pre><ul><li><strong>build</strong>: Specifies the location of the server project’s Dockerfile (in this case, ./api).</li><li><strong>container_name</strong>: Sets a custom name for the server container.</li><li><strong>ports</strong>: Maps port 4000 in the container to port 4000 on the host, making the API accessible externally.</li><li><strong>depends_on</strong>: Ensures the MongoDB service starts before the API server.</li><li><strong>volumes</strong>: Maps the api directory to /app in the container, allowing changes in the codebase to reflect in real-time. The /app/node_modules folder is also specified here to keep dependencies within the container environment.</li><li><strong>environment</strong>: Defines environment variables, such as MONGODB_URL, which allows the API to connect to MongoDB. The URL uses the service name mongo as the hostname.</li></ul><pre>  client:<br>    build: ./client<br>    container_name: client_container<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - api<br>    stdin_open: true<br>    tty: true<br>    volumes:<br>      - ./client:/app<br>      - /client/node_modules</pre><ul><li><strong>build</strong>: Specifies the path to the client’s Dockerfile (./client).</li><li><strong>container_name</strong>: Sets a custom name for the client container.</li><li><strong>ports</strong>: Maps port 3000 in the container to port 3000 on the host, making the React app accessible externally.</li><li><strong>depends_on</strong>: Ensures the API server starts before the client.</li><li><strong>stdin_open and </strong><strong>tty</strong>: Allows the client container to remain open and responsive, which is useful for interactive tasks in development mode.</li><li><strong>volumes</strong>: Maps the client directory to /app in the container, making it easy to develop with real-time code updates.</li></ul><pre>volumes:<br>  mongo_data:</pre><ul><li><strong>volumes</strong>: Defines a named volume mongo_data that persists MongoDB data, ensuring it’s not lost when containers are restarted or removed.</li></ul><h4>This is what the final docker-compose.yml file should look like:</h4><pre>services:<br>  mongo:<br>    image: mongo<br>    container_name: mongo_container<br>    volumes:<br>      - mongo_data:/data/db<br>    ports:<br>      - &quot;27017:27017&quot;<br><br>  api:<br>    build: ./api<br>    container_name: server_container<br>    ports:<br>      - &quot;4000:4000&quot;<br>    depends_on:<br>      - mongo<br>    volumes:<br>      - ./api:/app<br>      - /app/node_modules<br>    environment:<br>      - MONGODB_URL=mongodb://mongo:27017/userDB<br><br>  client:<br>    build: ./client<br>    container_name: client_container<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - api<br>    stdin_open: true<br>    tty: true<br>    volumes:<br>      - ./client:/app<br>      - /client/node_modules<br><br>volumes:<br>  mongo_data:</pre><h3>Step 4: Test the Containerized Application</h3><p>With the docker-compose.yml file set up, we’re ready to create and run the containers for our MERN application.</p><ul><li><strong>Run Docker Compose: </strong>Execute the following command from the root directory (where the docker-compose.yml file is located):</li></ul><pre>docker compose up</pre><ul><li><strong>Verify in Docker Desktop: </strong>Once the setup completes, you can open Docker Desktop to view the containers and images that have been created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NPyuq3dIYREHyEKhhSHGw.png" /><figcaption>This section will display all images created for MongoDB, the server, and the client.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPUuSu_Bq7F2A45xJFC0bA.png" /><figcaption>This section will show the running containers for each service (MongoDB, API server, and client).</figcaption></figure><ul><li><strong>Testing the Application:<br>- </strong>Open a web browser and go to http://localhost:3000 to access the React frontend.<br>- The API should be accessible at http://localhost:4000 for backend requests.<br>- MongoDB will be running in the background, handling database interactions from the API.</li></ul><h4>Create a New Record in the Database with Postman</h4><ul><li><strong>Open Postman</strong> and set the request to POST with the URL: <a href="http://localhost:4000/api/users.">http://localhost:4000/api/users</a></li><li><strong>Add JSON Body</strong>: Go to the <strong>Body</strong> tab, select <strong>raw</strong> and set it to <strong>JSON</strong>.</li></ul><pre>{<br>  &quot;name&quot;: &quot;Perera&quot;,<br>  &quot;age&quot;: 36<br>}</pre><ul><li><strong>Send the Request</strong> and check the response to confirm the new user is added.</li></ul><h3>Conclusion</h3><p>In this guide, we successfully containerized a MERN application using Docker Compose. We created separate Dockerfiles and .dockerignore files for both the client and server, set up MongoDB, and linked all services together using Docker Compose.</p><p>By running docker compose up, we were able to bring up all services, including the MongoDB database, the API server, and the React client. We also tested the functionality of the application by using Postman to create a new record in the MongoDB database via the API.</p><p>With Docker Compose, we simplified the development and deployment process, ensuring that each service runs in its isolated container while still communicating seamlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5fec828c1d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Docker Volumes for Persistent Data in JavaScript Apps]]></title>
            <link>https://medium.com/@arundeshan/using-docker-volumes-for-persistent-data-in-javascript-apps-eddcbb9e8966?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/eddcbb9e8966</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 12:56:09 GMT</pubDate>
            <atom:updated>2024-11-03T12:56:09.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MR06PQNb16e7gqn7.png" /></figure><h4><strong>What are Docker Volumes?</strong></h4><p>Docker containers allow applications to run in isolated environments, but by default, any data created inside the container is lost once it stops. This can be a problem if you want to keep data between runs. Docker volumes are a solution to this issue, letting you store data outside the container in a way that persists even after the container stops or is removed.</p><p><strong>Docker volumes</strong> are essentially storage spaces on your host machine that can be attached to containers. This way, any data saved to a volume remains available for future use, even if the container is restarted or replaced. Using Docker volumes is an easy and effective way to manage data persistence when working with containers.</p><h4><strong>When to Use Docker Volumes?</strong></h4><p>Docker volumes are useful for saving important data so it doesn’t get lost when a container stops or is deleted. Here are some situations where you should use them:</p><ol><li><strong>Database Storage</strong>: Use a volume for database data (like MySQL or MongoDB) to make sure your information is safe and still there if the container restarts or gets replaced.</li><li><strong>Application Data</strong>: If your app creates or stores files (like uploads, documents, or profile pictures), save them in a volume to keep them safe even if the app container changes.</li><li><strong>Essential Caches</strong>: For any caches that take a long time to rebuild, use a volume. This way, the cache data stays available even after a restart, making your app faster.</li></ol><h4>Example: Using Docker Volumes</h4><p>To demonstrate how Docker volumes work, let’s start by creating a simple JavaScript application and containerize it. Then, we’ll see how volumes can help us by allowing live changes to our files without rebuilding the container each time.</p><h4>Step 1: Set Up the Project</h4><ul><li>Create a new folder for the project.</li></ul><pre>mkdir simple-js-app<br>cd simple-js-app</pre><ul><li><strong>Create </strong><strong>index.js</strong> Inside the folder, create a file named index.js and add the following code:</li></ul><pre>const a = 10;<br>const b = 20;<br>const sum = a + b;<br><br>console.log(&quot;sum is &quot;, sum);</pre><p><strong>Create </strong><strong>Dockerfile</strong> In the same folder, create a file named Dockerfile and add the following content:</p><pre># Base image<br>FROM node:20-alpine<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy all files into the container<br>COPY . .<br><br># Command to run the application<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><h4>Step 2: Build and Run the Docker Container (Without Volumes)</h4><ul><li><strong>Build the Docker image:</strong> In your terminal, run the following command to build an image for this application:</li></ul><pre>docker build -t simple-js-app .</pre><ul><li><strong>Run the Container: </strong>Start the container with the following command:</li></ul><pre>docker run simple-js-app</pre><p>This should output:</p><pre>sum is 30</pre><p><em>Now, if you make a change to </em><em>index.js (for example, change </em><em>const a = 10; to </em><em>const a = 15;) and rerun the container, the change will </em><strong><em>not</em></strong><em> show up because the container does not automatically pick up changes from your local files.</em></p><h4>Step 3: Install nodemon for Automatic Restart</h4><p>Adding nodemon will help us automatically restart the application in the container whenever we make changes to our code. This saves us from having to rebuild and restart the container each time we make an edit. Let’s go through the updated steps.</p><ul><li><strong>Initialize the Project with </strong><strong>package.json:</strong>In your project directory, run the following command to create a package.json file:</li></ul><pre>npm init -y</pre><ul><li><strong>Install </strong><strong>nodemon:</strong>Install nodemon as a development dependency. nodemon will monitor our files and restart the application whenever it detects a change.</li></ul><pre>npm install nodemon --save-dev</pre><ul><li><strong>Update </strong><strong>package.json to Use </strong><strong>nodemon:</strong>Open package.json and update the &quot;scripts&quot; section to use nodemon:</li></ul><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;nodemon -L index.js&quot;<br>}</pre><p><em>Now, running </em><em>npm start will start the application using </em><em>nodemon, which will watch for file changes and automatically restart the app.</em></p><h4>Step 4: Update the Dockerfile</h4><ul><li>Edit the Dockerfile to look like this:</li></ul><pre># Base image<br>FROM node:20-alpine<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy package.json and package-lock.json<br>COPY package*.json .<br><br># Install dependencies<br>RUN npm install<br><br># Copy the rest of the application files<br>COPY . .<br><br># Start the app in development mode with nodemon<br>CMD [ &quot;npm&quot;, &quot;start&quot; ]</pre><ul><li>After updating the Dockerfile, you need to build the new Docker image with the following command:</li></ul><pre>docker build -t simple-image .</pre><p><em>Once the build completes, you’ll have a new Docker image named </em><em>simple-image.</em></p><h4>Step 5: Run the Container with Volumes for Live Code Updates</h4><p>To run the container with live code updates, use the following command:</p><pre>docker run --name simple-container --rm -v /app/node_modules -v ${PWD}:/app simple-image</pre><p>Here’s what each part of the command does:</p><ul><li>--name simple-container: Assigns a name to the container, making it easier to reference or manage.</li><li>--rm: Automatically removes the container when it stops, keeping things tidy.</li><li>-v /app/node_modules: Creates an anonymous volume for the node_modules folder. This ensures the container&#39;s node_modules directory isn’t overwritten by the volume mounted from the host.</li><li>-v ${PWD}:/app: Mounts your current directory (${PWD}) to /app in the container, allowing live updates as you edit files locally.</li><li>simple-image: The name of the Docker image we built in <em>Step 4.</em></li></ul><p><em>This command will run your application in the container with live code updates, so any changes you make to files in your project folder will be immediately reflected in the container.</em></p><h4>Conclusion</h4><p>In this guide, we learned how to use Docker volumes with a simple JavaScript app. We covered what Docker volumes are, how to set up a containerized app, and how <strong>nodemon</strong> helps us see code changes instantly. By using a volume, we can update our code without rebuilding the Docker image, making our development process faster.</p><p>Docker volumes are important for keeping data safe in containers. They allow us to save important information, like database entries or uploaded files, even if the container restarts or updates. This is especially helpful in development, testing, and production.</p><p>Now you’re ready to use Docker volumes in your own projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eddcbb9e8966" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First Steps in Docker: Building a Simple JavaScript App]]></title>
            <link>https://medium.com/@arundeshan/your-first-steps-in-docker-building-a-simple-javascript-app-b851d0d975f1?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/b851d0d975f1</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 11:08:35 GMT</pubDate>
            <atom:updated>2024-11-01T11:08:35.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w-Gp8ulRdYVYNoC-" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why Containers Exist</h4><p>Have you ever built a software application that works perfectly on your local machine, only to find that it breaks when moved to another system? This frustrating problem happens all the time in software development. Maybe it’s a version mismatch in dependencies, a different OS configuration, or some subtle setting.</p><p>Docker was created to solve this “it works on my machine” problem by creating consistent environments that can run anywhere.</p><p>Imagine a virtual box that includes everything your application needs to run — libraries, dependencies, system files — all packaged up so it behaves the same way, regardless of where it’s running. That’s the magic of <strong>containers</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*SXW6ILBVQXvNy9Qhx1jNRw.jpeg" /></figure><h4>How Docker Helps in Development and Deployment</h4><p>Docker containers are designed to make two main parts of the software development life cycle (SDLC) smoother: <strong>development</strong> and <strong>deployment</strong>.</p><ul><li><strong>Development</strong>: Imagine joining a new company, receiving your laptop, and being handed a long checklist of software, dependencies, and configurations to install before you can even run the application. It’s complex and leaves lots of room for human error. But with Docker, all the configurations, libraries, and dependencies needed to run the application can be set up in a single, simple command! This allows developers to work in consistent, error-free environments with minimal setup.</li><li><strong>Deployment: </strong>Deployment used to be just as tricky as development setup. Once your app was ready, deploying it to a server involved several steps, from configuring the server environment to installing dependencies. Containers simplify this by packaging everything the application needs into a single, standardized container. Whether it’s on your laptop, a colleague’s laptop, or a server in the cloud, Docker ensures the application runs the same way everywhere, streamlining deployment.</li></ul><h4>What is Docker?</h4><p>Docker is a platform that makes it easy for developers to develop, ship, and run applications by packaging them in a standardized unit called a <strong>container</strong>. Containers bundle the application code along with all necessary dependencies and configurations, ensuring the application works consistently, no matter where it runs.</p><h4>Why Doesn’t Code Always Work on Different Systems?</h4><ul><li><strong>Environment Configuration</strong>: Differences in configuration files and settings can lead to unexpected behavior.</li><li><strong>Dependency Issues</strong>: Applications often rely on specific versions of libraries or packages. Missing or mismatched dependencies on another system can break the code.</li><li><strong>Operating System Differences</strong>: An application developed on Windows may behave differently on Linux or macOS due to differences in system commands and files.</li><li><strong>Hardware Differences</strong>: Code may run differently or inefficiently on systems with varying hardware specifications.</li><li><strong>Network Configuration</strong>: Different network setups (like firewall rules or IP address configurations) can affect how applications communicate with each other.</li></ul><h4>Evolution of Virtualization in Cloud Computing</h4><p><strong>1. Bare Metal Computing: </strong>In bare metal computing, applications run directly on a physical host, with the hardware layer at the base, consisting of components like the CPU, memory, storage, and networking. On top of the hardware, an operating system (OS) is installed based on application needs (e.g., Windows, Linux), followed by necessary binaries and libraries. Finally, one or more applications are installed directly onto the OS, running without virtualization. This setup allows applications to operate with high performance directly on the server’s resources, though it limits flexibility since the entire server is dedicated to a single environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*FphzFTal5wxxht1J2XTs1w.png" /><figcaption><strong>Bare Metal Computing</strong></figcaption></figure><p><strong>2. Virtual Machines (VMs): </strong>In response to the limitations of bare metal computing, engineers introduced virtualization, creating the concept of <strong>Virtual Machines (VMs)</strong>. In this setup, the <strong>host</strong> is the physical system or server, which may or may not have a host operating system installed. A <strong>hypervisor</strong> — a specialized software layer that can utilize hardware resources — manages the physical hardware, enabling multiple VMs to run on a single host. Each VM operates independently with its own operating system, libraries, binaries, and applications, allowing for better resource utilization, isolation, and flexibility.</p><p><strong><em>Note</em></strong><em>: The hypervisor is a combination of software and hardware that allocates the server’s physical resources across multiple VMs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Ye9SMnEfIvJogT7BHfqnaw.png" /><figcaption><strong>Virtual Machines</strong></figcaption></figure><p><strong>3. Containers: </strong>In the case of Containers, we start with either physical or virtual hardware at the bottom layer, running a host operating system. On top of this OS, there’s a container runtime — software that takes container images and runs them on the host system. Containers differ from virtual machines primarily in how they use the operating system. While each VM runs its own complete OS, including a separate kernel, containers share the host OS kernel, meaning they don’t require their own OS or kernel. This makes containers lighter and faster to start than VMs, though they offer slightly less isolation. Proper configuration can still ensure strong isolation between containers, making them secure and efficient for cloud-based applications.</p><p><strong><em>Note</em></strong><em>: The container runtime is the software that runs containerized applications within the host system, optimizing performance by sharing the host OS kernel across containers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ZD3ExwE0t10OEkI5_YGzLg.png" /><figcaption><strong>Containers</strong></figcaption></figure><h3>Docker Image and Container</h3><p>A <strong>Docker image</strong> is a lightweight, standalone, and executable package that includes everything needed to run a piece of software, including the code, runtime, libraries, environment variables, and configuration files. Images are read-only and serve as the blueprint for creating Docker containers. They are built using a <strong>Dockerfile</strong>, which specifies the instructions for assembling the image.</p><p>A <strong>Docker container</strong> is a runnable instance of a Docker image. It is created from an image and includes everything necessary to execute the application. Containers are isolated from each other and the host system, allowing multiple containers to run simultaneously on the same hardware without interfering with each other. Unlike images, containers are mutable, meaning you can modify their state while they are running, but they are designed to be ephemeral, often created and destroyed as needed.</p><h3>Creating and running a Docker container</h3><ul><li><strong>Create a Dockerfile</strong>: Write a Dockerfile that outlines the instructions for your application, including the base image, dependencies, and the commands needed to run the application.</li><li><strong>Build the Docker Image</strong>: Use the Dockerfile to create a Docker image. This image contains everything needed to run your application in a standardized way.</li><li><strong>Run the Docker Container</strong>: Start a container from the built image. The container runs your application in an isolated environment, allowing it to function consistently across different systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjTUpEi8h53-DMkweX2TDQ.png" /></figure><h4>Parent/Base Images in Docker</h4><p>A <strong>parent/base image</strong> in Docker is the starting point for creating your own Docker images. It provides the basic operating system and environment needed to run applications. For example, you might use a base image like Node.js, Python, or a lightweight Linux distribution. Using a base image makes it easier to set up your application because it already has the necessary components.</p><p>You can find a variety of official Docker images on Docker <a href="https://hub.docker.com/">Docker Hub</a></p><p>To download a base image from Docker Hub,</p><pre>docker pull &lt;image-name&gt;:&lt;tag&gt;    </pre><p>For example, to pull the Node.js image, run:</p><pre>docker pull node:20-alpine</pre><p><em>After downloading a base image, open Docker Desktop and go to the “Images” section on the left side. You’ll see a list of all your downloaded images, including the one you just pulled.</em></p><h4>Step 1: Create the Project Folder</h4><p>Create a folder named sample-js-project:</p><pre>mkdir sample-js-project<br>cd sample-js-project</pre><h4>Step 2: Create index.js File</h4><p>Inside the sample-js-project folder, create a file named index.js and add code to add two integers and print the result:</p><pre>// index.js<br>const add = (a, b) =&gt; a + b;<br>console.log(&quot;The sum is:&quot;, add(5, 10));</pre><h4>Step 3: Initialize package.json</h4><p>In the same folder, initialize a package.json file (run npm init -y if you&#39;re using npm) and add a start script:</p><pre># Base image<br>FROM node:20-alpine<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy all the application files<br>COPY . .<br><br># Run the app<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><ul><li><strong>Base Image</strong>: FROM node:20-alpine uses a lightweight Node.js image. This line specifies the base image to start from.</li><li><strong>Working Directory</strong>: WORKDIR /app sets the working directory to /app. This means any following commands in the Dockerfile, such as copying files or running commands, will happen in this /app directory.</li><li><strong>Copy Application Files</strong>: COPY . . copies the rest of the project files. The first . refers to the current folder where the Dockerfile is located on your computer, and the second . refers to the working directory inside the container (/app).</li><li><strong>Run the Application</strong>: CMD [&quot;npm&quot;, &quot;start&quot;] starts the app by running index.js. Tells Docker to run the command npm start when starting the container.</li></ul><h4>Step 4: Running the Docker Image</h4><ul><li><strong>Open the terminal</strong> and navigate to your project folder (sample-js-project).</li><li><strong>Build the Docker Image</strong>: Run the following command to build the image, tagging it as sample-js-project:</li></ul><pre>docker build -t sample-js-project .</pre><p><strong><em>docker build -t sample-js-project .</em></strong><em>: This command builds a Docker image from the Dockerfile in the current directory (</em><em>.) and tags it with the name </em><em>sample-js-project.</em></p><ul><li><strong>Run the Docker Container</strong>: Once the image is built, create and run a container from the image with this command:</li></ul><pre>docker run sample-js-project</pre><p><strong><em>docker run sample-js-project</em></strong><em>: This command creates and runs a container from the </em><em>sample-js-project image, executing the app inside the container.</em></p><p><strong>After starting the Docker image and running the container, you can view both in Docker Desktop:</strong></p><ul><li>In the <strong>Images</strong> section, you’ll see the sample-js-project image you built.</li><li>In the <strong>Containers</strong> section, you’ll see the running container created from that image.</li></ul><h3>Conclusion</h3><p>In this article, we learned the basics of Docker and how it helps in developing and deploying applications using containers. We created a simple JavaScript project that adds two integers and set it up with Docker. By building a Docker image and running a container, we ensured that our application works consistently in any environment.</p><p>Docker makes it easy to package applications and their dependencies, reducing problems related to different environments. With this knowledge, you can start using Docker in your own projects.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b851d0d975f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YAML for DevOps: A Beginner’s Guide]]></title>
            <link>https://medium.com/@arundeshan/yaml-for-devops-a-beginners-guide-789e8ecb23d2?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/789e8ecb23d2</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 15:03:07 GMT</pubDate>
            <atom:updated>2024-10-28T15:03:07.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1GNEzzbwiE96-Uw7qWtLA.jpeg" /></figure><p>YAML (Yet Another Markup Language) is a popular data serialization format known for its readability and simplicity. It’s widely used in DevOps for configuration files in various tools like Docker, Kubernetes, and Ansible, making it essential for DevOps practitioners to understand.</p><h4><strong><em>Why Learn YAML?</em></strong></h4><p>Many DevOps tools and applications rely on YAML to manage configurations, making it a critical skill for DevOps professionals. YAML is especially popular because it’s human-readable, more so than alternatives like XML and JSON, and easy to navigate. Let’s dive into the essentials of YAML with examples.</p><h4>What is YAML?</h4><p>YAML is a data serialization language like JSON and XML, used to transfer data between systems. In YAML, data is represented in a format that both humans and machines can read, allowing applications with different technologies and structures to communicate seamlessly. However, YAML is not a markup language, which means it doesn’t use tags like XML.</p><p>YAML files typically use the .yaml or .yml extensions.</p><h4>YAML Format Compared to XML and JSON</h4><p>The strength of YAML lies in its simplicity and readability compared to XML and JSON.</p><ul><li><strong>YAML</strong>: A straightforward, clean format with indentation-based hierarchy.</li></ul><pre>microservices:<br>  - app: user-authentication<br>    port: 9000<br>    version: 1.0</pre><ul><li><strong>XML</strong>: Uses angle brackets to define data structure, which can become verbose.</li></ul><pre>&lt;microservices&gt;<br>  &lt;microservice&gt;<br>    &lt;app&gt;user-authentication&lt;/app&gt;<br>    &lt;port&gt;9000&lt;/port&gt;<br>    &lt;version&gt;1.0&lt;/version&gt;<br>  &lt;/microservice&gt;<br>&lt;/microservices&gt;</pre><ul><li><strong>JSON</strong>: Uses curly braces and requires explicit syntax for each data structure level.</li></ul><pre>{<br>  &quot;microservices&quot;: [<br>    {<br>      &quot;app&quot;: &quot;user-authentication&quot;,<br>      &quot;port&quot;: 9000,<br>      &quot;version&quot;: &quot;1.0&quot;<br>    }<br>  ]<br>}</pre><h4>What is YAML Used For?</h4><p>YAML’s flexibility makes it perfect for configuration files across DevOps tools:</p><ul><li><strong>Docker Compose</strong>: Manages multi-container Docker applications.</li><li><strong>Kubernetes</strong>: Configures clusters and deployments.</li><li><strong>Ansible</strong>: Automates IT tasks, using YAML to define playbooks.</li></ul><p><strong>Below, we’ll cover YAML basics, from syntax to complex data structures.</strong></p><h3>YAML Syntax Basics</h3><h4>Key-Value Pairs</h4><p>YAML uses simple key-value pairs for basic configurations.</p><pre>app: user-authentication<br>port: 9000<br>version: 1.0</pre><p>Here, different data types, like strings and numbers, can be used without special formatting. If you need to include special characters, use quotes (&quot;user-authentication\n&quot;).</p><h4>Comments</h4><p>You can add comments with the # symbol, which YAML ignores when reading.</p><pre>app: user-authentication<br>port: 9000<br># This is a comment<br>version: 1.0</pre><h4>Objects and Indentation</h4><p>In YAML, indentation is crucial. Objects are created by nesting keys and values.</p><pre>microservices:<br>  app: user-authentication<br>  port: 9000<br>  version: 1.0</pre><p>Each level of indentation must be consistent; even a single extra space will cause a syntax error. Consider using a YAML validator or a plugin in your IDE to avoid mistakes.</p><h4>YAML Lists</h4><p>YAML also supports lists, useful for defining multiple values in a single category. Lists begin with a dash (-) for each entry:</p><pre>microservices:<br>  - app: user-authentication<br>    port: 9000<br>    version: 1.0<br>  - app: shopping-cart<br>    port: 9002<br>    version: 2.9</pre><h4>Boolean Values</h4><p>In YAML, Boolean values can be expressed as true/false, yes/no, or on/off.</p><pre>microservices:<br>  - app: user-authentication<br>    port: 9000<br>    version: 1.0<br>    deployed: true<br>  - app: shopping-cart<br>    port: 9002<br>    version: 2.9<br>    deployed: no</pre><h4>Nested Lists</h4><p>YAML can also handle nested lists within lists, allowing for complex data structures.</p><pre>microservices:<br>  - app: user-authentication<br>    port: 9000<br>    deployed: no<br>    version:<br>      - 1.2<br>      - 1.3</pre><p>Or, for a single array format:</p><pre>microservices:<br>  - app: user-authentication<br>    port: 9000<br>    deployed: no<br>    version: [1.2, &quot;1.4&quot;]</pre><h3>Real Kubernetes YAML Configuration Example</h3><p>Here’s a real-world Kubernetes YAML configuration file example for deploying an application. This file defines a Kubernetes <strong>Deployment</strong> and an associated <strong>Service</strong> to make the application accessible.</p><pre>apiVersion: apps/v1          # Specifies the Kubernetes API version<br>kind: Deployment              # Defines the kind of resource (Deployment, Service, etc.)<br>metadata:                     <br>  name: my-app-deployment     # Name of the Deployment<br>  labels:<br>    app: my-app               # Label to identify this resource<br>spec:<br>  replicas: 3                 # Number of pod replicas to create<br>  selector:<br>    matchLabels:<br>      app: my-app             # Matches pods with this label<br>  template:<br>    metadata:<br>      labels:<br>        app: my-app           # Labels for the created pods<br>    spec:<br>      containers:<br>        - name: my-app        # Name of the container<br>          image: my-app:1.0   # Docker image to use<br>          ports:<br>            - containerPort: 80  # Port the container listens on<br><br>---<br><br>apiVersion: v1                # API version for the Service resource<br>kind: Service                 # Defines the resource type (Service)<br>metadata:<br>  name: my-app-service        # Name of the Service<br>spec:<br>  selector:<br>    app: my-app               # Selects pods with this label<br>  ports:<br>    - protocol: TCP           # Protocol used by the service<br>      port: 80                # Port on the Service<br>      targetPort: 80          # Port on the pod the Service should forward requests to<br>  type: LoadBalancer          # Type of Service to expose the application externally</pre><h4>Multi-line Strings in YAML</h4><p>In YAML, multi-line strings make it easier to read and maintain long text blocks. You can use the <strong>pipe (</strong><strong>|)</strong> or <strong>greater-than (</strong><strong>&gt;)</strong> symbols to define multi-line strings in different ways.</p><blockquote><strong><em>Using the Pipe Symbol (</em></strong><strong><em>|)</em></strong></blockquote><p>To preserve line breaks as they appear in the YAML file, use the pipe (|) symbol. Each line in the multi-line string is kept as it is, making it ideal for structured text.</p><pre>multiLineString: |<br>  this is the multi line string<br>  this is the second line of the multi line string<br>  next line</pre><p>The above YAML will output exactly as written, with each line separated. This is useful for texts like logs, documentation comments, or configuration descriptions.</p><blockquote><strong><em>Using the Greater-than Symbol (</em></strong><strong><em>&gt;)</em></strong></blockquote><p>If you want to convert a multi-line string into a single line by removing line breaks, use the greater-than (&gt;) symbol. Line breaks are replaced by spaces in the final output.</p><pre>singleLineString: &gt;<br>  this is the multi line string<br>  this is the second line of the multi line string<br>  next line</pre><h4>Real Use Case of Multi-line Strings</h4><p>Multi-line strings are often used in YAML for configuration files where long text is needed. A common example is specifying a multi-line environment variable in a Kubernetes configuration, such as setting up a complex configuration string, certificate, or JSON block.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: example-config<br>data:<br>  config.json: |<br>    {<br>      &quot;database&quot;: {<br>        &quot;host&quot;: &quot;db.example.com&quot;,<br>        &quot;port&quot;: 3306,<br>        &quot;username&quot;: &quot;user&quot;,<br>        &quot;password&quot;: &quot;pass&quot;<br>      },<br>      &quot;log_level&quot;: &quot;info&quot;<br>    }</pre><p>Here, the config.json key holds a JSON object as a multi-line string. This approach is especially useful when embedding code snippets, certificates, or JSON/YAML data within other YAML files.</p><h3>Environment Variables in YAML</h3><p>In YAML configuration files, environment variables allow for dynamic values that can change based on the environment. This is especially useful in deployment configurations, where sensitive information like database credentials should not be hard-coded. By using environment variables, we can securely pass such data into containers or applications.</p><blockquote><em>Accessing Environment Variables in YAML</em></blockquote><p>To access an environment variable within a YAML configuration, use the <strong>dollar sign (</strong><strong>$)</strong> followed by the variable name. Here&#39;s an example of how to define a command in YAML for a MySQL pod that uses an environment variable.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: mysql-pod<br>spec:<br>  containers:<br>    - name: mysql-container<br>      image: mysql:latest<br>      env:<br>        - name: MYSQL_ROOT_PW<br>          valueFrom:<br>            secretKeyRef:<br>              name: mysql-secret<br>              key: root-password<br>      command: <br>        - /bin/sh<br>        - -ec<br>        - &gt;-<br>          mysql -h 127.0.0.1 -u root -p$MYSQL_ROOT_PW -e &#39;SELECT 1&#39;</pre><ul><li>/bin/sh -ec opens a shell and executes commands.</li><li>mysql -h 127.0.0.1 -u root -p$MYSQL_ROOT_PW -e &#39;SELECT 1&#39; runs a MySQL command, substituting $MYSQL_ROOT_PW with the actual password stored in the environment variable.</li></ul><h4>Multiple YAML Documents in One File</h4><p>In YAML, you can include multiple documents within a single file by separating each document with three dashes (---). This is especially useful for defining multiple Kubernetes resources or configurations in a single YAML file, which helps with organizing complex deployments.</p><blockquote><em>Using </em><em>--- to Separate YAML Documents</em></blockquote><p>Each section separated by --- acts as an independent YAML document within the same file.</p><pre># First document: ConfigMap definition<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: app-config<br>data:<br>  APP_ENV: &quot;production&quot;<br>  LOG_LEVEL: &quot;info&quot;<br>---<br># Second document: Deployment definition<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: app-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: my-app<br>  template:<br>    metadata:<br>      labels:<br>        app: my-app<br>    spec:<br>      containers:<br>        - name: app-container<br>          image: my-app:latest<br>          env:<br>            - name: APP_ENV<br>              valueFrom:<br>                configMapKeyRef:<br>                  name: app-config<br>                  key: APP_ENV<br>---<br># Third document: Service definition<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: app-service<br>spec:<br>  selector:<br>    app: my-app<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8080</pre><ul><li><strong>ConfigMap</strong>: The first document creates a ConfigMap with environment variables for the application (APP_ENV and LOG_LEVEL).</li><li><strong>Deployment</strong>: The second document defines a Deployment for the application with three replicas and references the ConfigMap for its environment variables.</li><li><strong>Service</strong>: The third document creates a Service to expose the application on port 80, directing traffic to the application’s target port 8080.</li></ul><h3>Conclusion</h3><p>YAML is a powerful yet simple data serialization language, widely used in DevOps for its human-readable format and structured syntax. By learning YAML, you’ll be equipped to work with essential DevOps tools like Docker, Kubernetes, and Ansible, making it easier to organize, share, and deploy complex system setups efficiently. Whether you’re defining single or multiple documents in one file, YAML simplifies the process, helping you keep configurations clean and manageable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=789e8ecb23d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Recursive React Component in React]]></title>
            <link>https://medium.com/@arundeshan/how-to-build-a-recursive-react-component-in-react-0d678dfe219d?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d678dfe219d</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 16:57:54 GMT</pubDate>
            <atom:updated>2024-10-25T16:57:54.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Building recursive components in React can greatly simplify the process of displaying nested data, like file trees or hierarchical data. In this tutorial, I’ll walk you through building a recursive React component step-by-step with TypeScript, using a simple file directory tree structure as our example. Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-xD2qC_UqCm1k0YE" /><figcaption>Photo by <a href="https://unsplash.com/@seimesa?utm_source=medium&amp;utm_medium=referral">Mario Mesaglio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 1: Set Up the Project Structure</h3><p>For this example, we assume you have a working React project created with a tool like Vite or Create React App. Once your project is set up, create the following file structure:</p><pre>src/<br>├── App.tsx<br>├── App.css<br>├── file.ts</pre><p>The file.ts file will store the sample data we want to display, App.tsx will contain our main application component, and App.css will style the component.</p><h3>Step 2: Define the Data Structure</h3><p>In file.ts, define the file directory structure as a JavaScript object. Our structure uses a recursive data type, where each entry can either be a file or a folder (with potential child entries). Here’s what the file should look like:</p><pre>// file.ts<br>export const files = {<br>  children: [<br>    {<br>      name: &quot;node_modules&quot;,<br>      children: [<br>        {<br>          name: &quot;bin&quot;,<br>          children: [<br>            { name: &quot;acorn&quot; },<br>            { name: &quot;esbuild&quot; },<br>          ],<br>        },<br>      ],<br>    },<br>    {<br>      name: &quot;public&quot;,<br>      children: [<br>        { name: &quot;vite.svg&quot; },<br>        { name: &quot;favIcon.ico&quot; },<br>      ],<br>    },<br>    {<br>      name: &quot;src&quot;,<br>      children: [<br>        { name: &quot;App.tsx&quot; },<br>        { name: &quot;App.css&quot; },<br>        { name: &quot;main.tsx&quot; },<br>      ],<br>    },<br>    { name: &quot;package.json&quot; },<br>    { name: &quot;README.md&quot; },<br>  ],<br>};</pre><p>Here, children is an array of entries that can recursively contain more children, creating a nested structure.</p><h3>Step 3: Define the TypeScript Type for Entries</h3><p>In App.tsx, start by defining the type for each entry in the file structure. This type should handle both files and folders:</p><pre>type TEntry = {<br>  name: string;<br>  children?: TEntry[];<br>};</pre><p>The children field is optional, as it only applies to folders. If an entry lacks children, we know it’s a file.</p><h3>Step 4: Create the Recursive Entry Component</h3><p>Now, we’ll create the recursive component that will render each file or folder. Start by defining the Entry component, which takes two props: entry and depth. The depth prop controls the indentation level for each entry.</p><pre>import { useState } from &quot;react&quot;;<br>import {<br>  ChevronRightIcon,<br>  ChevronDownIcon,<br>  FolderIcon,<br>} from &quot;@heroicons/react/20/solid&quot;;<br>import { DocumentIcon } from &quot;@heroicons/react/24/outline&quot;;<br><br>function Entry({ entry, depth }: { entry: TEntry; depth: number }) {<br>  const [isExpanded, setIsExpanded] = useState(false);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button<br>        onClick={() =&gt; setIsExpanded(!isExpanded)}<br>        style={{ paddingLeft: `${depth * 20}px` }}<br>      &gt;<br>        {entry.children ? (<br>          isExpanded ? (<br>            &lt;&gt;<br>              &lt;ChevronDownIcon style={{ width: &quot;15px&quot;, height: &quot;15px&quot; }} /&gt;<br>              &lt;FolderIcon style={{ width: &quot;15px&quot;, height: &quot;15px&quot; }} /&gt;<br>            &lt;/&gt;<br>          ) : (<br>            &lt;&gt;<br>              &lt;ChevronRightIcon style={{ width: &quot;15px&quot;, height: &quot;15px&quot; }} /&gt;<br>              &lt;FolderIcon style={{ width: &quot;15px&quot;, height: &quot;15px&quot; }} /&gt;<br>            &lt;/&gt;<br>          )<br>        ) : (<br>          &lt;DocumentIcon style={{ width: &quot;15px&quot;, height: &quot;15px&quot; }} /&gt;<br>        )}<br>        {entry.name}<br>      &lt;/button&gt;<br>      {isExpanded &amp;&amp; entry.children &amp;&amp; (<br>        &lt;div&gt;<br>          {entry.children.map((child, index) =&gt; (<br>            &lt;Entry key={index} entry={child} depth={depth + 1} /&gt;<br>          ))}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Key Parts of the Entry Component:</h3><ul><li><strong>isExpanded State:</strong> A boolean state to toggle the visibility of child elements.</li><li><strong>Indentation:</strong> We use paddingLeft to control the indentation of each entry based on its depth.</li><li><strong>Conditional Rendering:</strong> If entry.children exists, the component displays icons to expand or collapse. Otherwise, it displays a file icon.</li><li><strong>Recursion:</strong> When isExpanded is true, the Entry component renders itself recursively for each child in entry.children.</li></ul><h3>Step 5: Render the File Structure</h3><p>In App.tsx, use the Entry component to render the top-level entries in the files object, setting the initial depth to 1.</p><pre>import { files } from &quot;./file&quot;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;list-container&quot;&gt;<br>      {files.children.map((entry, index) =&gt; (<br>        &lt;Entry key={index} entry={entry} depth={1} /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Here, we iterate through files.children and create an Entry component for each top-level folder or file, with depthinitialized to 1.</p><h3>Step 6: Styling the Component</h3><p>Add some basic CSS in App.css to improve the appearance. Here’s a sample:</p><pre>.list-container {<br>  font-family: Arial, sans-serif;<br>  font-size: 14px;<br>  color: #333;<br>}<br><br>button {<br>  border: none;<br>  background: none;<br>  cursor: pointer;<br>  display: flex;<br>  align-items: center;<br>}</pre><h3>Step 7: Testing the Recursive Component</h3><p>Now, start the development server with npm run dev (for Vite) or npm start (for Create React App) to see the component in action. You should be able to expand and collapse folders to navigate the file structure.</p><h3>Conclusion</h3><p>In this tutorial, we’ve built a recursive React component to display a file directory structure. Recursive components can simplify code when rendering deeply nested data structures, allowing you to handle complex UIs with minimal code. By modifying depth, you can adjust indentation levels and create cleaner, visually organized layouts.</p><p>Experiment with different structures in the files object and customize the appearance to suit your application. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d678dfe219d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to store password in db]]></title>
            <link>https://medium.com/@arundeshan/how-to-store-password-in-db-cad6acb51651?source=rss-5ecffd8cbe96------2</link>
            <guid isPermaLink="false">https://medium.com/p/cad6acb51651</guid>
            <dc:creator><![CDATA[Arun deshan]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 11:03:24 GMT</pubDate>
            <atom:updated>2024-07-10T11:03:24.804Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital age, the security of user data, especially passwords, is of paramount importance. Poor password management can lead to serious security breaches. Here are some key practices to avoid and recommendations to ensure passwords are stored securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvTFWe90AgzqFdaf2LBBZg.jpeg" /></figure><h4><strong>Things we shouldn’t do</strong></h4><ol><li><strong>Storing Passwords in Plain Text: </strong>When passwords are saved as plain text, anyone with access to the storage medium can read them.</li><li><strong>Storing Password Hashes Directly:</strong> While storing password hashes is better than storing plain text passwords, it is still not sufficient on its own. Password hashes can be vulnerable to precomputation attacks, such as rainbow tables. A rainbow table is a precomputed table for reversing cryptographic hash functions, which allows attackers to quickly look up the hash and find the corresponding password.</li></ol><h4><strong>Best Practices for Secure Password Storage</strong></h4><p><strong>Salting Passwords: </strong>To mitigate precomputation attacks like rainbow tables, it is essential to salt passwords before hashing them. A salt is a random value added to the password before it is hashed, making each hash unique even if the same password is used by multiple users.</p><h3><strong>How it works</strong></h3><h4>Store a password</h4><p>When a user creates a password, a random salt is generated and appended to the password. This combined value is then hashed. The salt is stored along with the hashed password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sB3x4kVsWmULb9GrsMFnUw.png" /><figcaption>Store a password</figcaption></figure><h4>Validate a password</h4><p>To validate a password, the system can follow a secure and straightforward process:</p><ol><li>The user inputs their password during the login process.</li><li>The system retrieves the unique salt associated with the user’s stored password hash from the database.</li><li>The system appends the fetched salt to the entered password and hashes this combined value. Let’s call this hash value H1.</li><li>The system compares H1 (the hash of the entered password and salt) with H2 (the stored hash in the database). If H1 and H2 match, the password is valid and the user is authenticated.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXuYdto_IbK9IxjrM5H_bQ.png" /><figcaption>Validate a password</figcaption></figure><blockquote>Remember, security is not a one-time setup but an ongoing process. Regularly review and update your security practices to stay ahead of potential threats.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad6acb51651" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>