<?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 Riffki Krisdiyanto on Medium]]></title>
        <description><![CDATA[Stories by Riffki Krisdiyanto on Medium]]></description>
        <link>https://medium.com/@riffkikris13?source=rss-dbd5ab6199e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*557eCmMwzJUeXfKs</url>
            <title>Stories by Riffki Krisdiyanto on Medium</title>
            <link>https://medium.com/@riffkikris13?source=rss-dbd5ab6199e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:36:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@riffkikris13/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[Workflow Engine Integration with .NET Core]]></title>
            <link>https://medium.com/@riffkikris13/workflow-engine-integration-with-net-core-9ab0ff1c4025?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ab0ff1c4025</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 09:52:56 GMT</pubDate>
            <atom:updated>2024-08-16T09:52:56.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Workflow Engine Integration with .NET Core</h3><p>Workflow engine is a powerful tool for automating, managing, and coordinating complex business processes. Workflow visualization is just one of its many features, aiding in the design and understanding of workflows. However, its primary function is to ensure that the process runs smoothly, efficiently, and according to predetermined rules.</p><h4>Database Setup</h4><p>The database we will use is SQL server. And here I will install it into docker. Use the command below.</p><pre>docker run -e &#39;ACCEPT_EULA=Y&#39; -e &#39;SA_PASSWORD=0p4BtZ4EJg&#39; -p 1433:1433 --name rdb -d mcr.microsoft.com/mssql/server:2019-latest</pre><p>After that open the link below.</p><p><a href="https://github.com/optimajet/WorkflowEngine.NET/tree/master/Providers">WorkflowEngine.NET/Providers at master · optimajet/WorkflowEngine.NET</a></p><p>Since here we are using SQL Server, then download the OptimaJet.Workflow.DbPersistence folder. You can adjust it according to the database you are using. Go to the SQL folder then extract the CreatePersistenceObjects.sql file. After that open DBeaver and create a connection to the database that was created earlier. If so, import the sql file and run the script. Then a table will be created that will be used by the workflow engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T44S3XjOKE0Sh_4mHjlt9g.png" /></figure><h4>App Development</h4><p>Create a blank solution project in Visual Studio and add a project of type Class Library, here I named it WorkflowLibrary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6F5eSY9578DZjxnLaKxDw.png" /></figure><p>Install both libraries below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*r5uViVJeJXgF77SiDbl-og.png" /></figure><p>Create a WorkflowInit class and provide the code below. This is for Workflow Runtime needs.</p><pre>using System;<br>using System.Xml.Linq;<br>using OptimaJet.Workflow.Core.Builder;<br>using OptimaJet.Workflow.Core.Bus;<br>using OptimaJet.Workflow.Core.Runtime;<br>using OptimaJet.Workflow.DbPersistence;<br><br>namespace WorkflowLibrary<br>{<br>    public static class WorkflowInit<br>    {<br>        private static readonly Lazy&lt;WorkflowRuntime&gt; LazyRuntime = new Lazy&lt;WorkflowRuntime&gt;(InitWorkflowRuntime);<br><br>        public static WorkflowRuntime Runtime<br>        {<br>            get { return LazyRuntime.Value; }<br>        }<br><br>        public static string ConnectionString { get; set; }<br><br>        private static WorkflowRuntime InitWorkflowRuntime()<br>        {<br>            // TODO Uncomment for .NET Framework if you don&#39;t set ConnectionString externally.<br>            //ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[&quot;ConnectionString&quot;].ConnectionString;<br><br>            if (string.IsNullOrEmpty(ConnectionString))<br>            {<br>                throw new Exception(&quot;Please init ConnectionString before calling the Runtime!&quot;);<br>            }<br>            // TODO If you have a license key, you have to register it here<br>            //WorkflowRuntime.RegisterLicense(&quot;your license key text&quot;);<br><br>            // TODO If you are using database different from SQL Server you have to use different persistence provider here.<br>            var dbProvider = new MSSQLProvider(ConnectionString);<br><br>            var builder = new WorkflowBuilder&lt;XElement&gt;(<br>                dbProvider,<br>                new OptimaJet.Workflow.Core.Parser.XmlWorkflowParser(),<br>                dbProvider<br>            ).WithDefaultCache();<br><br>            var runtime = new WorkflowRuntime()<br>                .WithBuilder(builder)<br>                .WithPersistenceProvider(dbProvider)<br>                .EnableCodeActions()<br>                .SwitchAutoUpdateSchemeBeforeGetAvailableCommandsOn()<br>                .AsSingleServer();<br><br>            var plugin = new OptimaJet.Workflow.Plugins.BasicPlugin();<br>            // Settings for SendEmail actions<br>            // plugin.Setting_Mailserver = &quot;smtp.yourserver.com&quot;;<br>            // plugin.Setting_MailserverPort = 25;<br>            // plugin.Setting_MailserverFrom = &quot;from@yourserver.com&quot;;<br>            // plugin.Setting_MailserverLogin = &quot;login@yourserver.com&quot;;<br>            // plugin.Setting_MailserverPassword = &quot;pass&quot;;<br>            // plugin.Setting_MailserverSsl = true;<br>            runtime.WithPlugin(plugin);<br><br>            // events subscription<br>            runtime.ProcessActivityChanged += (sender, args) =&gt; { };<br>            runtime.ProcessStatusChanged += (sender, args) =&gt; { };<br>            // TODO If you have planned to use Code Actions functionality that required references to external assemblies<br>            // you have to register them here<br>            //runtime.RegisterAssemblyForCodeActions(Assembly.GetAssembly(typeof(SomeTypeFromMyAssembly)));<br><br>            // starts the WorkflowRuntime<br>            // TODO If you have planned use Timers the best way to start WorkflowRuntime is somewhere outside<br>            // of this function in Global.asax for example<br>            runtime.Start();<br><br>            return runtime;<br>        }<br>    }<br>}</pre><p>After that, create a new project of type ASP.NET Core MVC, here I named it Designer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-dfytI00X0bzA57t9wNrA.png" /></figure><p>Right click on the project and select add &gt; project reference and select WorkflowLibrary so that it can be used in the Designer project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*Jnk_5yGweRlNtfd4m8x-oA.png" /></figure><p>Right click the Controller folder and select add &gt; controller. Then right click on the view() method and click add view. Then select Razor View — Empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHmpkT-u7NxkIvWsq9HaFw.png" /></figure><p>After that, change the Controller that was created earlier to the following code.</p><pre>using System.Collections.Specialized;<br>using System.Text;<br>using Microsoft.AspNetCore.Mvc;<br>using OptimaJet.Workflow;<br>using WorkflowLibrary;<br><br>namespace DesignerApp.Controllers<br>{<br>    public class DesignerController : Controller<br>    {<br>        public IActionResult Index()<br>        {<br>            return View();<br>        }<br><br>        [Obsolete]<br>        public async Task&lt;IActionResult&gt; Api()<br>        {<br>            Stream? filestream = null;<br>            var isPost = Request.Method.Equals(&quot;POST&quot;, StringComparison.OrdinalIgnoreCase);<br>            if (isPost &amp;&amp; Request.Form.Files != null &amp;&amp; Request.Form.Files.Count &gt; 0)<br>                filestream = Request.Form.Files[0].OpenReadStream();<br><br>            var pars = new NameValueCollection();<br>            foreach (var q in Request.Query)<br>            {<br>                pars.Add(q.Key, q.Value.First());<br>            }<br><br><br>            if (isPost)<br>            {<br>                var parsKeys = pars.AllKeys;<br>                //foreach (var key in Request.Form.AllKeys)<br>                foreach (string key in Request.Form.Keys)<br>                {<br>                    if (!parsKeys.Contains(key))<br>                    {<br>                        pars.Add(key, Request.Form[key]);<br>                    }<br>                }<br>            }<br><br>            (string res, bool hasError) = await WorkflowInit.Runtime.DesignerAPIAsync(pars, filestream);<br><br>            var operation = pars[&quot;operation&quot;]?.ToLower();<br>            if (operation == &quot;downloadscheme&quot; &amp;&amp; !hasError)<br>                return File(Encoding.UTF8.GetBytes(res), &quot;text/xml&quot;);<br>            else if (operation == &quot;downloadschemebpmn&quot; &amp;&amp; !hasError)<br>                return File(UTF8Encoding.UTF8.GetBytes(res), &quot;text/xml&quot;);<br><br>            return Content(res);<br>        }<br>    }<br>}</pre><p>Go to the following page and download the workflowdesigner.min.css and workflowdesigner.min.js files.</p><p><a href="https://github.com/optimajet/WorkflowEngine.NET/tree/master/Designer">WorkflowEngine.NET/Designer at master · optimajet/WorkflowEngine.NET</a></p><p>Copy the file to the wwwroot folder and place it in its respective folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*N3BaoD-QPAogi7YAse8dIg.png" /></figure><p>Go to appsettings.json and add the connection configuration to the database.</p><pre>&quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=localhost,1433;Database=workflowdb;User Id=sa;Password=0p4BtZ4EJg;TrustServerCertificate=True;&quot;<br>},</pre><p>Add the connection configuration to Program.cs and assign it to the WorkflowInit.ConnectionString field.</p><pre>WorkflowInit.ConnectionString = app.Configuration.GetConnectionString(&quot;DefaultConnection&quot;);</pre><p>Add the list element below to views &gt; shared &gt; _Layout.cshtml so that the workflow engine can be accessed.</p><pre>&lt;li class=&quot;nav-item&quot;&gt;<br>        &lt;a class=&quot;nav-link text-dark&quot; asp-area=&quot;&quot; asp-controller=&quot;Designer&quot; asp-action=&quot;Index&quot;&gt;Workflow Designer&lt;/a&gt;<br>    &lt;/li&gt;</pre><p>Run the application and visit the address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ba-Tt7GEmSgAFKQOIUS6fA.png" /></figure><p>If it appears, then the workflow engine integration process is complete. Thank you for reading my article. Hopefully it is useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ab0ff1c4025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Restaurant Application using ASP.NET Core]]></title>
            <link>https://medium.com/@riffkikris13/simple-restaurant-application-using-asp-net-core-5f58882d68f8?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f58882d68f8</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 06:12:38 GMT</pubDate>
            <atom:updated>2024-12-08T14:13:39.618Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, in this article we will create a simple restaurant application using ASP.NET Core. In this application we will only create the backend. Okay, without wasting more time, let’s start creating the application.</p><h4>Database Setup</h4><p>The database we will use is SQL server. We will install it in docker.</p><pre>docker run -e &#39;ACCEPT_EULA=Y&#39; -e &#39;SA_PASSWORD=0p4BtZ4EJg&#39; -p 1433:1433 --name rdb -d mcr.microsoft.com/mssql/server:2019-latest</pre><p>Make sure the container is running smoothly. Log in to the container or directly use a third party app to connect to the SQL server. Next we will create 3 tables, where these three tables have a many to many relationship.</p><pre>CREATE TABLE customers (<br>   id int IDENTITY(1,1) NOT NULL PRIMARY KEY,<br>   name varchar(255) NOT NULL,<br>   phone varchar(15) NOT NULL UNIQUE,<br>);<br><br>CREATE TABLE foods (<br>   id int IDENTITY(1,1) NOT NULL PRIMARY KEY,<br>   name varchar(255) NOT NULL,<br>   price int NOT NULL ,<br>   stock int NOT NULL,<br>);<br><br>CREATE TABLE transactions (<br>   id int IDENTITY(1,1) NOT NULL PRIMARY KEY,<br>   customer_id int NOT NULL,<br>   food_id int NOT NULL,<br>   qty int NOT NULL,<br>   total_price int NOT NULL,<br>   created_at date NOT NULL,<br>   CONSTRAINT FK_Customer_Transaction FOREIGN KEY (customer_id) REFERENCES customers(id),<br>   CONSTRAINT FK_Food_Transaction FOREIGN KEY (food_id) REFERENCES foods(id)<br>);</pre><h4>Backend Development</h4><p>The first thing we will do is create a model and context from the table we created earlier. First, install the required dependencies.</p><pre>dotnet add package Microsoft.EntityFrameworkCore.Design<br>dotnet add package Microsoft.EntityFrameworkCore.SqlServer</pre><p>Here we will use reverse engineering techniques, namely to automatically generate models and contexts from the previous table. Use the command below to do so.</p><pre>dotnet ef dbcontext scaffold &quot;Server=localhost;Database=restaurant;User Id=sa;Password=0p4BtZ4EJg;TrustServerCertificate=True;&quot; Microsoft.EntityFrameworkCore.SqlServer -o Models --context RestaurantContext</pre><p>Run the command and 2 folders will be created, namely Data and Models. Add the database configuration to the appsettings.json file.</p><pre>&quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=localhost,1433;Database=restaurant;User Id=sa;Password=0p4BtZ4EJg;TrustServerCertificate=True;&quot;<br>}</pre><p>After that, go to Program.cs and add the connection configuration to the application, and also add json options to prevent circular dependency.</p><pre>builder.Services.AddDbContext&lt;RestaurantContext&gt;(options =&gt;<br>        options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>builder.Services.AddControllers().AddJsonOptions(options =&gt;<br>{<br>    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;<br>});</pre><p>After that we will continue to create Dto.</p><pre>public class CustomerRequest<br>{<br>    public string Name { get; set; } = null!;<br><br>    public string Phone { get; set; } = null!;<br>}</pre><pre>public class FoodRequest<br>{<br>    public string Name { get; set; } = null!;<br><br>    public int Price { get; set; }<br><br>    public int Stock { get; set; }<br>}</pre><pre>public class TransactionRequest<br>{<br>    public int CustomerId { get; set; }<br><br>    public int FoodId { get; set; }<br><br>    public int Qty { get; set; }<br>}</pre><p>Next we will create a controller. However, we will do reverse engineering again to generate the controller from the existing model. We will create CustomerController first. First right click on the controller folder and select add &gt; New Scaffolded Item, then select the option as shown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wrb7dydoZje4471MoaWI4Q.png" /></figure><p>After that, select the mode you want to use and its context, give it a name and then click add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*_DSxUpHh9CrJRsnFIfNirg.png" /></figure><p>The controller has been successfully generated. However, I will replace the request object in the POST and PUT methods with the Dto object that was created earlier so that the JSON structure is more organized.</p><pre>...<br>// PUT: api/Customer/5<br>// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754<br>[HttpPut(&quot;{id}&quot;)]<br>public async Task&lt;IActionResult&gt; PutCustomer(int? id, CustomerRequest req)<br>{<br>    if (id == null || id &lt;= 0)<br>    {<br>        return BadRequest(&quot;Invalid or missing id.&quot;);<br>    }<br><br>    _context.Entry(new Customer<br>    {<br>        Id = id.Value,<br>        Name = req.Name,<br>        Phone = req.Phone<br>    }).State = EntityState.Modified;<br><br>    try<br>    {<br>        await _context.SaveChangesAsync();<br>    }<br>    catch (DbUpdateConcurrencyException)<br>    {<br>        if (!CustomerExists(id.Value))<br>        {<br>            return NotFound();<br>        }<br>        else<br>        {<br>            throw;<br>        }<br>    }<br><br>    return NoContent();<br>}<br><br>// POST: api/Customer<br>// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754<br>[HttpPost]<br>public async Task&lt;ActionResult&lt;Customer&gt;&gt; PostCustomer(CustomerRequest req)<br>{<br>    var customer = new Customer<br>    {<br>        Name = req.Name,<br>        Phone = req.Phone<br>    };<br><br><br>    _context.Customers.Add(customer);<br>    await _context.SaveChangesAsync();<br><br>    return CreatedAtAction(&quot;GetCustomer&quot;, new { id = customer.Id }, customer);<br>}<br>...</pre><p>Do the same thing for Food and Transaction. But for Transaction we have to provide additional logic in POST and PUT methods.</p><pre>...<br>// PUT: api/Transaction/5<br>// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754<br>[HttpPut(&quot;{id}&quot;)]<br>public async Task&lt;IActionResult&gt; PutTransaction(int? id, TransactionRequest req)<br>{<br>    if (id == null || id &lt;= 0)<br>    {<br>        return BadRequest(&quot;Invalid or missing id.&quot;);<br>    }<br><br>    var existingTransaction = await _context.Transactions.FindAsync(id);<br>    var food = await _context.Foods.FindAsync(req.FoodId);<br><br>    if (existingTransaction == null || food == null)<br>    {<br>        return NotFound();<br>    }<br><br>    int quantityDifference = req.Qty - existingTransaction.Qty;<br>    food.Stock -= quantityDifference;<br><br>    if (food.Stock &lt; 0)<br>    {<br>        return BadRequest(&quot;Insufficient stock available.&quot;);<br>    }<br><br>    existingTransaction.CustomerId = req.CustomerId;<br>    existingTransaction.FoodId = req.FoodId;<br>    existingTransaction.Qty = req.Qty;<br>    existingTransaction.TotalPrice = food.Price * req.Qty;<br><br>    _context.Entry(existingTransaction).State = EntityState.Modified;<br><br>    using (var transaction = await _context.Database.BeginTransactionAsync())<br>    {<br>        try<br>        {<br>            await _context.SaveChangesAsync();<br>            await transaction.CommitAsync();<br>        }<br>        catch (DbUpdateConcurrencyException)<br>        {<br>            await transaction.RollbackAsync();<br>            if (!TransactionExists(id.Value))<br>            {<br>                return NotFound();<br>            }<br>            else<br>            {<br>                throw;<br>            }<br>        }<br>    }<br><br>    return NoContent();<br>}<br><br>// POST: api/Transaction<br>// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754<br>[HttpPost]<br>public async Task&lt;ActionResult&lt;Transaction&gt;&gt; PostTransaction(TransactionRequest req)<br>{<br>    using var transaction = await _context.Database.BeginTransactionAsync();<br><br>    try<br>    {<br>        var food = await _context.Foods.FindAsync(req.FoodId);<br><br>        if (food == null || food.Stock &lt; req.Qty)<br>        {<br>            return BadRequest(&quot;Not enough stock available.&quot;);<br>        }<br><br>        var newTransaction = new Transaction<br>        {<br>            CustomerId = req.CustomerId,<br>            FoodId = req.FoodId,<br>            Qty = req.Qty,<br>            TotalPrice = food.Price * req.Qty,<br>            CreatedAt = DateOnly.FromDateTime(DateTime.UtcNow)<br>        };<br><br>        food.Stock -= req.Qty;<br><br>        _context.Transactions.Add(newTransaction);<br>        await _context.SaveChangesAsync();<br><br>        await transaction.CommitAsync();<br><br>        return CreatedAtAction(&quot;GetTransaction&quot;, new { id = newTransaction.Id }, newTransaction);<br>    }<br>    catch<br>    {<br>        await transaction.RollbackAsync();<br>        throw;<br>    }<br>}<br>...</pre><p>There I added logic to check Food stock and reduce the stock if a transaction occurs and also adjust the stock when an update occurs. Don’t forget to use the database transaction feature because here we change 2 tables at once, so that the data is consistent.</p><h4>Testing</h4><p>Add Customer and Food data first with the POST method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilVtbpq77tRyVCP89iTjsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgjWjLsJao1L3eM-M557LA.png" /></figure><p>After that, make a transaction using the POST method on the /Transaction path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgElzisXq9SkoXb1cPMU-w.png" /></figure><p>Also make sure that the food stock has decreased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2z92lB4otK7JeqVPpsLlrg.png" /></figure><p>If all the above tests run perfectly, then the application creation is complete. Thank you for reading my article. Hopefully useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f58882d68f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fullstack App with ASP.NET.Core and Angular]]></title>
            <link>https://medium.com/@riffkikris13/fullstack-app-with-asp-net-core-and-angular-5bb2f2e567cf?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bb2f2e567cf</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 09:59:50 GMT</pubDate>
            <atom:updated>2024-08-07T09:59:50.921Z</atom:updated>
            <content:encoded><![CDATA[<p>Developing full-stack applications has become a highly valuable skill in the modern technology world. With the increasing need for fast, reliable, and scalable solutions, developers need to master various tools and frameworks to build robust applications. In this article, we will discuss how to build a full-stack application using ASP.NET Core on the backend and Angular on the frontend. Both these technologies offer incredible capabilities for building interactive and efficient web applications. Let’s dive deeper into how this combination can help you create an amazing full-stack application.</p><h4>Database Setup</h4><p>Here we will use SQL Server as the database. We will use docker to create the database container. Create docker compose then build the container.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  sqlserver:<br>    image: mcr.microsoft.com/mssql/server:2019-latest<br>    container_name: sqlserver<br>    environment:<br>      SA_PASSWORD: &quot;0p4BtZ4EJg&quot;<br>      ACCEPT_EULA: &quot;Y&quot;<br>    ports:<br>      - &quot;1433:1433&quot;</pre><p>After that, enter the Docker container and create 2 tables, namely the players and positions tables.</p><pre>CREATE TABLE Positions (<br>    Id INT PRIMARY KEY IDENTITY(1,1),<br>    Name NVARCHAR(50) NOT NULL,<br>    DisplayOrder INT NULL<br>);<br><br>CREATE TABLE Players (<br>    Id INT PRIMARY KEY IDENTITY(1,1),<br>    ShirtNo INT NULL,<br>    Name NVARCHAR(50) NOT NULL,<br>    PositionId INT NOT NULL,<br>    Appearances INT NULL,<br>    Goals INT NULL,<br>    FOREIGN KEY (PositionId) REFERENCES Positions(Id)<br>);</pre><p>For the positions table, we will create dummy data at the beginning because we will not create a post method for positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*uiK4H9_2xeCCIUr-xvEpaQ.png" /></figure><h4>Backend Development</h4><p>To create the backend and frontend, we will use Visual Studio 2022. First, look for the create project menu and select the Angular and ASP.NET Core templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iLd4bFqExxgZVsYombwvA.png" /></figure><p>Next, please install the three libraries below. If you are using Visual Studio, you just right-click the backend application and select the Manage Nuget Packages menu, then find the library and install it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*AauHlAQUoZhXuOiYn-pKfQ.png" /></figure><p>After that we will start to create the database model. In .NET there is an ORM that is part of .NET, namely Entity Framework Core (EF Core). The library used is Microsoft.EntityFrameworkCore.Tools, which provides tools for scaffolding the database. This feature is used to generate Entity Framework Core model code based on an existing database schema. This is known as reverse engineering, and helps you create a model that fits your database structure.</p><p>To use this feature, please open the Tools -&gt; Nuget Package Manager -&gt; Package Manager Console menu then type the command below.</p><pre>Scaffold-DbContext -Connection &quot;Server=localhost,1433; Database=soccerdb; User Id=sa; Password=0p4BtZ4EJg; MultipleActiveResultSets=true; TrustServerCertificate=True;&quot; -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir &quot;Models&quot; -ContextDir &quot;Data&quot; -Context &quot;FootballDbContext&quot; -NoOnConfiguring</pre><p>In that command we try to make a connection to localhost:1433 because that is the address of the container we created at the beginning. For the database I chose soccerdb because there I created the players and positions tables. Run the command and the model and context will be generated by the compiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*Dj616pni-ho3FZBLTRzTAA.png" /></figure><p>Open appsettings.json and add the configuration below for database connection requirements.</p><pre>&quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=localhost,1433; Database=soccerdb; User Id=sa; Password=0p4BtZ4EJg; MultipleActiveResultSets=true; TrustServerCertificate=True;&quot;<br>},</pre><p>Next, open Program.cs then add DBContext along with the database connection configuration.</p><pre>builder.Services.AddDbContext&lt;SoccerDbContext&gt;(options =&gt; options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><p>After the database connection configuration is complete, then we will create a service for players and positions. First we will create a service for players.</p><pre>namespace Soccer.Server.Services<br>{<br>    public interface IPlayersService<br>    {<br>        Task&lt;IEnumerable&lt;Player&gt;&gt; GetPlayersList();<br>        Task&lt;Player&gt; GetPlayerById(int id);<br>        Task&lt;Player&gt; CreatePlayer(Player player);<br>        Task UpdatePlayer(Player player);<br>        Task DeletePlayer(Player player);<br>    }<br>}</pre><pre>namespace Soccer.Server.Services<br>{<br>    public class PlayersService : IPlayersService<br>    {<br>        private readonly SoccerDbContext _context;<br><br>        public PlayersService(SoccerDbContext context)<br>        {<br>            _context = context;<br>        }<br><br>        public async Task&lt;IEnumerable&lt;Player&gt;&gt; GetPlayersList()<br>        {<br>            return await _context.Players<br>                .Include(x =&gt; x.Position)<br>                .ToListAsync();<br>        }<br><br>        public async Task&lt;Player&gt; GetPlayerById(int id)<br>        {<br>            return await _context.Players<br>                .Include(x =&gt; x.Position)<br>                .FirstOrDefaultAsync(x =&gt; x.Id == id);<br>        }<br><br>        public async Task&lt;Player&gt; CreatePlayer(Player player)<br>        {<br>            _context.Players.Add(player);<br>            await _context.SaveChangesAsync();<br>            return player;<br>        }<br><br>        public async Task UpdatePlayer(Player player)<br>        {<br>            _context.Players.Update(player);<br>            await _context.SaveChangesAsync();<br>        }<br><br>        public async Task DeletePlayer(Player player)<br>        {<br>            _context.Players.Remove(player);<br>            await _context.SaveChangesAsync();<br>        }<br>    }<br>}</pre><p>In this service we only perform get, create, update, and delete operations. Next we will create a service for positions.</p><pre>namespace Soccer.Server.Services<br>{<br>    public interface IPositionsService<br>    {<br>        Task&lt;IEnumerable&lt;Position&gt;&gt; GetPositionsList();<br>    }<br>}</pre><pre>namespace Soccer.Server.Services<br>{<br>    public class PositionsService : IPositionsService<br>    {<br>        private readonly SoccerDbContext _context;<br><br>        public PositionsService(SoccerDbContext context)<br>        {<br>            _context = context;<br>        }<br><br>        public async Task&lt;IEnumerable&lt;Position&gt;&gt; GetPositionsList()<br>        {<br>            return await _context.Positions<br>                .OrderBy(x =&gt; x.DisplayOrder)<br>                .ToListAsync();<br>        }<br>    }<br>}</pre><p>In this service we only provide for get list operation. Next we will create controller for players and positions.</p><pre>namespace Soccer.Server.Controllers<br>{<br>    [ApiController]<br>    [Route(&quot;api/[controller]&quot;)]<br>    public class PlayersController : ControllerBase<br>    {<br>        private readonly IPlayersService _playerService;<br><br>        public PlayersController(IPlayersService playerService)<br>        {<br>            _playerService = playerService;<br>        }<br><br>        // GET: api/Players<br>        [HttpGet]<br>        public async Task&lt;IEnumerable&lt;Player&gt;&gt; Get()<br>        {<br>            return await _playerService.GetPlayersList();<br>        }<br><br>        // GET: api/Players/5<br>        [HttpGet(&quot;{id}&quot;)]<br>        public async Task&lt;ActionResult&lt;Player&gt;&gt; Get(int id)<br>        {<br>            var player = await _playerService.GetPlayerById(id);<br><br>            if (player == null)<br>            {<br>                return NotFound();<br>            }<br><br>            return Ok(player);<br>        }<br><br>        // POST: api/Players<br>        [HttpPost]<br>        public async Task&lt;ActionResult&lt;Player&gt;&gt; Post(Player player)<br>        {<br>            await _playerService.CreatePlayer(player);<br><br>            return CreatedAtAction(&quot;Post&quot;, new { id = player.Id }, player);<br>        }<br><br>        // PUT: api/Players/5<br>        [HttpPut(&quot;{id}&quot;)]<br>        public async Task&lt;IActionResult&gt; Put(int id, Player player)<br>        {<br>            if (id != player.Id)<br>            {<br>                return BadRequest(&quot;Not a valid player id&quot;);<br>            }<br><br>            await _playerService.UpdatePlayer(player);<br><br>            return NoContent();<br>        }<br><br>        // DELETE: api/Players/5<br>        [HttpDelete(&quot;{id}&quot;)]<br>        public async Task&lt;IActionResult&gt; Delete(int id)<br>        {<br>            if (id &lt;= 0)<br>                return BadRequest(&quot;Not a valid player id&quot;);<br><br>            var player = await _playerService.GetPlayerById(id);<br>            if (player == null)<br>            {<br>                return NotFound();<br>            }<br><br>            await _playerService.DeletePlayer(player);<br><br>            return NoContent();<br>        }<br>    }<br>}</pre><pre>namespace Soccer.Server.Controllers<br>{<br>    [ApiController]<br>    [Route(&quot;api/[controller]&quot;)]<br>    public class PositionsController : ControllerBase<br>    {<br>        private readonly IPositionsService _positionService;<br><br>        public PositionsController(IPositionsService positionService)<br>        {<br>            _positionService = positionService;<br>        }<br><br>        // GET: api/Positions<br>        [HttpGet]<br>        public async Task&lt;IEnumerable&lt;Position&gt;&gt; Get()<br>        {<br>            return await _positionService.GetPositionsList();<br>        }<br>    }<br>}</pre><p>In the controller we create an API for the client and connect it to the Service. The backend application has been completed, but there is still a problem lurking, namely circular dependency. To solve this problem you must install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package and provide the configuration below in Program.cs.</p><pre>builder.Services.AddControllersWithViews().AddNewtonsoftJson(options =&gt; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);</pre><p>If you have done this, you can test the API with Postman. If it is successful, the API is running smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNxR1_RPQ9CZzIHoQ_39BQ.png" /></figure><h4>Frontend Development</h4><p>It’s time to move on to the Frontend, the first thing we’re going to do is create a module for the players, we want the components and services to be imported into the players module and look neat.</p><pre>ng generate module players --routing</pre><p>If so, next we will create several components, services and interfaces.</p><pre>ng generate component players/list<br>ng generate component players/details<br>ng generate component players/create<br>ng generate component players/edit<br>ng generate service players/players<br>ng generate service players/positions<br>ng generate interface players/player<br>ng generate interface players/position</pre><p>Open the players module and add FormsModule and ReactiveFormsModule for the needs of creating forms to the players module.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br><br>import { PlayersRoutingModule } from &#39;./players-routing.module&#39;;<br>import { ListComponent } from &#39;./list/list.component&#39;;<br>import { DetailsComponent } from &#39;./details/details.component&#39;;<br>import { CreateComponent } from &#39;./create/create.component&#39;;<br>import { EditComponent } from &#39;./edit/edit.component&#39;;<br>import { FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;<br><br><br>@NgModule({<br>  declarations: [<br>    ListComponent,<br>    DetailsComponent,<br>    CreateComponent,<br>    EditComponent<br>  ],<br>  imports: [<br>    CommonModule,<br>    PlayersRoutingModule,<br>    FormsModule,<br>    ReactiveFormsModule,<br>  ]<br>})<br>export class PlayersModule { }</pre><p>Next go to player routing and add routing and its components in the routes array. There we create a redirect if the user accesses /players. For details and edits we use the path parameter for query needs to the backend.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { ListComponent } from &#39;./list/list.component&#39;;<br>import { DetailsComponent } from &#39;./details/details.component&#39;;<br>import { CreateComponent } from &#39;./create/create.component&#39;;<br>import { EditComponent } from &#39;./edit/edit.component&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;players&#39;, redirectTo: &#39;players/list&#39;, pathMatch: &#39;full&#39; },<br>  { path: &#39;players/list&#39;, component: ListComponent },<br>  { path: &#39;players/:playerId/details&#39;, component: DetailsComponent },<br>  { path: &#39;players/create&#39;, component: CreateComponent },<br>  { path: &#39;players/:playerId/edit&#39;, component: EditComponent }<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forChild(routes)],<br>  exports: [RouterModule]<br>})<br>export class PlayersRoutingModule { }</pre><p>Open the app module and add the player module to the properties imports.</p><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br><br>import { AppRoutingModule } from &#39;./app-routing.module&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { PlayersModule } from &#39;./players/players.module&#39;;<br><br>@NgModule({<br>  declarations: [<br>    AppComponent,<br>  ],<br>  imports: [<br>    BrowserModule, HttpClientModule,<br>    AppRoutingModule,<br>    PlayersModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>Don’t forget to add outlet on the html app. There I also added navigation for additional.</p><pre>&lt;ul class=&quot;navbar-nav flex-grow&quot;&gt;<br>  &lt;li class=&quot;nav-item&quot;<br>      [routerLinkActive]=&quot;[&#39;link-active&#39;]&quot;<br>      [routerLinkActiveOptions]=&quot;{ exact: true }&quot;&gt;<br>    &lt;a class=&quot;nav-link text-dark&quot; [routerLink]=&quot;[&#39;/&#39;]&quot;&gt;Home&lt;/a&gt;<br>  &lt;/li&gt;<br>  &lt;li class=&quot;nav-item&quot; [routerLinkActive]=&quot;[&#39;link-active&#39;]&quot;&gt;<br>    &lt;a class=&quot;nav-link text-dark&quot; [routerLink]=&quot;[&#39;/players&#39;]&quot;&gt;Players&lt;/a&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Next we will create an interface for players and positions.</p><pre>export interface Position {<br>  id: number;<br>  name: string;<br>  displayOrder?: number;<br>}</pre><pre>import { Position } from &quot;./position&quot;;<br><br>export interface Player {<br>  id: number;<br>  shirtNo: number;<br>  name: string;<br>  positionId?: number;<br>  appearances?: number;<br>  goals?: number;<br>  position?: Position;<br>}</pre><p>Next we will create a service for player and position for query needs to the backend.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class PlayersService {<br><br>  private apiURL = &quot;http://localhost:5071/api&quot;;<br>  httpOptions = {<br>    headers: new HttpHeaders({<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    })<br>  };<br><br>  constructor(private httpClient: HttpClient) { }<br><br>  getPlayers(): Observable&lt;Player[]&gt; {<br>    return this.httpClient.get&lt;Player[]&gt;(this.apiURL + &#39;/players&#39;)<br>      .pipe(<br>        catchError(this.errorHandler)<br>      );<br>  }<br><br>  getPlayer(id: number): Observable&lt;Player&gt; {<br>    return this.httpClient.get&lt;Player&gt;(this.apiURL + &#39;/players/&#39; + id)<br>      .pipe(<br>        catchError(this.errorHandler)<br>      );<br>  }<br><br>  createPlayer(player: Player): Observable&lt;Player&gt; {<br>    return this.httpClient.post&lt;Player&gt;(this.apiURL + &#39;/players/&#39;, JSON.stringify(player), this.httpOptions)<br>      .pipe(<br>        catchError(this.errorHandler)<br>      );<br>  }<br><br>  updatePlayer(id: number, player: Player): Observable&lt;Player&gt; {<br>    return this.httpClient.put&lt;Player&gt;(this.apiURL + &#39;/players/&#39; + id, JSON.stringify(player), this.httpOptions)<br>      .pipe(<br>        catchError(this.errorHandler)<br>      );<br>  }<br><br>  deletePlayer(id: number) {<br>    return this.httpClient.delete&lt;Player&gt;(this.apiURL + &#39;/players/&#39; + id, this.httpOptions)<br>      .pipe(<br>        catchError(this.errorHandler)<br>      );<br>  }<br><br>  errorHandler(error: HttpErrorResponse) {<br>    let errorMessage = &#39;&#39;;<br><br>    if (error.error instanceof ErrorEvent) {<br>      errorMessage = error.error.message;<br>    } else {<br>      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;<br>    }<br>    return throwError(errorMessage);<br>  }<br>}</pre><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class PositionsService {<br><br>  private apiURL = &quot;http://localhost:5071/api&quot;;<br><br>  constructor(private httpClient: HttpClient) { }<br><br>  getPositions(): Observable&lt;Position[]&gt; {<br>    return this.httpClient.get&lt;Position[]&gt;(this.apiURL + &#39;/positions&#39;)<br>      .pipe(<br>        catchError(this.errorHandler)<br>      );<br>  }<br><br>  errorHandler(error: HttpErrorResponse) {<br>    let errorMessage = &#39;&#39;;<br><br>    if (error.error instanceof ErrorEvent) {<br>      errorMessage = error.error.message;<br>    } else {<br>      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;<br>    }<br>    return throwError(errorMessage);<br>  }<br>}</pre><p>After the interface and service have been successfully created, then we will start creating components starting with the player list component.</p><pre>@Component({<br>  selector: &#39;app-list&#39;,<br>  templateUrl: &#39;./list.component.html&#39;,<br>  styleUrls: [&#39;./list.component.css&#39;]<br>})<br>export class ListComponent implements OnInit {<br><br>  players: Player[] = [];<br><br>  constructor(public playersService: PlayersService) { }<br><br>  ngOnInit(): void {<br>    this.playersService.getPlayers().subscribe((data: Player[]) =&gt; {<br>      this.players = data;<br>    });<br>  }<br><br>  deletePlayer(id: number) {<br>    this.playersService.deletePlayer(id).subscribe(_ =&gt; {<br>      this.players = this.players.filter(item =&gt; item.id !== id);<br>    });<br>  }<br>}</pre><p>In that component we do a query when the component loads and create a method to delete data. After that we will continue to create the template.</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;br /&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      &lt;h3&gt;Players&lt;/h3&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col-text-right&quot;&gt;<br>      &lt;a href=&quot;#&quot; routerLink=&quot;/players/create/&quot; class=&quot;btn btn-success btn-sm&quot;&gt;Create New&lt;/a&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;br /&gt;<br>  &lt;table class=&quot;table table-bordered table-sm&quot;&gt;<br>    &lt;tr&gt;<br>      &lt;th&gt;Id&lt;/th&gt;<br>      &lt;th&gt;Shirt No&lt;/th&gt;<br>      &lt;th&gt;Name&lt;/th&gt;<br>      &lt;th&gt;Position&lt;/th&gt;<br>      &lt;th&gt;Appearances&lt;/th&gt;<br>      &lt;th&gt;Goals&lt;/th&gt;<br>      &lt;th width=&quot;200px&quot;&gt;&lt;/th&gt;<br>    &lt;/tr&gt;<br>    &lt;tr *ngFor=&quot;let player of players&quot;&gt;<br>      &lt;td&gt;{{ player.id }}&lt;/td&gt;<br>      &lt;td&gt;{{ player.shirtNo }}&lt;/td&gt;<br>      &lt;td&gt;{{ player.name }}&lt;/td&gt;<br>      &lt;td&gt;{{ player.position?.name }}&lt;/td&gt;<br>      &lt;td&gt;{{ player.appearances }}&lt;/td&gt;<br>      &lt;td&gt;{{ player.goals }}&lt;/td&gt;<br>      &lt;td class=&quot;text-right&quot;&gt;<br>        &lt;a href=&quot;#&quot; [routerLink]=&quot;[&#39;/players/&#39;, player.id, &#39;details&#39;]&quot; class=&quot;btn btn-info btn-sm&quot;&gt;View&lt;/a&gt;<br>        &lt;a href=&quot;#&quot; [routerLink]=&quot;[&#39;/players/&#39;, player.id, &#39;edit&#39;]&quot; class=&quot;btn btn-primary btn-sm&quot;&gt;Edit&lt;/a&gt;<br>        &lt;button type=&quot;button&quot; (click)=&quot;deletePlayer(player.id)&quot; class=&quot;btn btn-danger btn-sm&quot;&gt;Delete&lt;/button&gt;<br>      &lt;/td&gt;<br>    &lt;/tr&gt;<br>  &lt;/table&gt;<br>&lt;/div&gt;</pre><p>In the template we map the query result data in the form of a table. Next we will create the component details.</p><pre>@Component({<br>  selector: &#39;app-details&#39;,<br>  templateUrl: &#39;./details.component.html&#39;,<br>  styleUrls: [&#39;./details.component.css&#39;]<br>})<br>export class DetailsComponent implements OnInit {<br><br>  id: number = 0;<br>  player: Player | null = null;<br><br>  constructor(<br>    public playersService: PlayersService,<br>    private route: ActivatedRoute,<br>    private router: Router<br>  ) { }<br><br>  ngOnInit(): void {<br>    this.id = this.route.snapshot.params[&#39;playerId&#39;];<br>    this.playersService.getPlayer(this.id).subscribe((data: Player) =&gt; {<br>      this.player = data;<br>    });<br>  }<br>}</pre><p>In that component we only do queries when the component is loaded. Our initial data is set to null. After that we will create the template.</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;br /&gt;<br>  &lt;h3&gt;Player Details&lt;/h3&gt;<br>  &lt;br /&gt;<br>  &lt;div class=&quot;card&quot;&gt;<br>    &lt;div class=&quot;card-header&quot;&gt;<br>      &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;col&quot;&gt;<br>          &lt;h4&gt;{{ player?.name }}&lt;/h4&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;col text-right&quot;&gt;<br>          &lt;a href=&quot;#&quot; routerLink=&quot;/players/list&quot; class=&quot;btn btn-secondary btn-sm&quot;&gt;Back To Players List&lt;/a&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;ul class=&quot;list-group list-group-flush&quot;&gt;<br>      &lt;li class=&quot;list-group-item&quot;&gt;&lt;b&gt;Id:&lt;/b&gt; {{ player?.id }}&lt;/li&gt;<br>      &lt;li class=&quot;list-group-item&quot;&gt;&lt;b&gt;Shirt No:&lt;/b&gt; {{ player?.shirtNo }}&lt;/li&gt;<br>      &lt;li class=&quot;list-group-item&quot;&gt;&lt;b&gt;Position:&lt;/b&gt; {{ player?.position?.name }}&lt;/li&gt;<br>      &lt;li class=&quot;list-group-item&quot;&gt;&lt;b&gt;Appearances:&lt;/b&gt; {{ player?.appearances }}&lt;/li&gt;<br>      &lt;li class=&quot;list-group-item&quot;&gt;&lt;b&gt;Goals:&lt;/b&gt; {{ player?.goals }}&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>In the template we map the query result data. Don’t forget to give the operator “?” so that the displayed data becomes optional. Next we will create a component create.</p><pre>@Component({<br>  selector: &#39;app-create&#39;,<br>  templateUrl: &#39;./create.component.html&#39;,<br>  styleUrls: [&#39;./create.component.css&#39;]<br>})<br>export class CreateComponent implements OnInit {<br><br>  positions: Position[] = [];<br>  createForm;<br><br>  constructor(<br>    public playersService: PlayersService,<br>    public positionsService: PositionsService,<br>    private route: ActivatedRoute,<br>    private router: Router,<br>    private formBuilder: FormBuilder<br>  ) {<br>    this.createForm = this.formBuilder.group({<br>      shirtNo: [&#39;&#39;, Validators.required],<br>      name: [&#39;&#39;, Validators.required],<br>      positionId: [&#39;&#39;],<br>      appearances: [&#39;&#39;],<br>      goals: [&#39;&#39;],<br>    });<br>  }<br><br>  ngOnInit(): void {<br>    this.positionsService.getPositions().subscribe((data: Position[]) =&gt; {<br>      this.positions = data;<br>    });<br>  }<br><br>  onSubmit(formData: FormGroup) {<br>    this.playersService.createPlayer(formData.value).subscribe(res =&gt; {<br>      this.router.navigateByUrl(&#39;players/list&#39;);<br>    });<br>  }<br>}</pre><p>In this component we create a form build from a reactive form along with validation. When the data is loaded we will also query the data position to become the form value and create a method to submit. After that we will create the template.</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;br /&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      &lt;h3&gt;Create Player&lt;/h3&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col text-right&quot;&gt;<br>      &lt;a href=&quot;#&quot; routerLink=&quot;/players/list&quot; class=&quot;btn btn-secondary btn-sm&quot;&gt;Back To Players List&lt;/a&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;br /&gt;<br>  &lt;form [formGroup]=&quot;createForm&quot; (ngSubmit)=&quot;onSubmit(createForm)&quot;&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;shirtNo&quot;&gt;Shirt No:&lt;/label&gt;<br>      &lt;input formControlName=&quot;shirtNo&quot;<br>             id=&quot;shirtNo&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>      &lt;input formControlName=&quot;name&quot;<br>             id=&quot;name&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;name&quot;&gt;Position:&lt;/label&gt;<br>      &lt;select formControlName=&quot;positionId&quot;<br>              id=&quot;positionId&quot;<br>              class=&quot;form-control&quot;&gt;<br>        &lt;option value=&quot;&quot;&gt;- Select -&lt;/option&gt;<br>        &lt;option *ngFor=&quot;let position of positions&quot; [ngValue]=&quot;position.id&quot;&gt;<br>          {{position.name}}<br>        &lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;appearances&quot;&gt;Appearances:&lt;/label&gt;<br>      &lt;input formControlName=&quot;appearances&quot;<br>             id=&quot;appearances&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;goals&quot;&gt;Goals:&lt;/label&gt;<br>      &lt;input formControlName=&quot;goals&quot;<br>             id=&quot;goals&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot; [disabled]=&quot;!createForm.valid&quot;&gt;Create&lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/div&gt;</pre><p>In the template we create a form that matches the form builder that we have created in the component. And there we use the onSubmit method that we have created in the component for the needs of submitting the form. Next we will create an edit component.</p><pre>@Component({<br>  selector: &#39;app-edit&#39;,<br>  templateUrl: &#39;./edit.component.html&#39;,<br>  styleUrls: [&#39;./edit.component.css&#39;]<br>})<br>export class EditComponent implements OnInit {<br><br>  id: number = 0;<br>  player: Player | null = null;<br>  positions: Position[] = [];<br>  editForm: FormGroup;<br><br>  constructor(<br>    public playersService: PlayersService,<br>    public positionsService: PositionsService,<br>    private route: ActivatedRoute,<br>    private router: Router,<br>    private formBuilder: FormBuilder<br>  ) {<br>    this.editForm = this.formBuilder.group({<br>      id: [&#39;&#39;],<br>      shirtNo: [&#39;&#39;, Validators.required],<br>      name: [&#39;&#39;, Validators.required],<br>      positionId: [&#39;&#39;],<br>      appearances: [&#39;&#39;],<br>      goals: [&#39;&#39;],<br>    });<br>  }<br><br>  ngOnInit(): void {<br>    this.id = this.route.snapshot.params[&#39;playerId&#39;];<br><br>    this.positionsService.getPositions().subscribe((data: Position[]) =&gt; {<br>      this.positions = data;<br>    });<br><br>    this.playersService.getPlayer(this.id).subscribe((data: Player) =&gt; {<br>      this.player = data;<br>      this.editForm.patchValue(data);<br>    });<br>  }<br><br>  onSubmit(formData: FormGroup) {<br>    this.playersService.updatePlayer(this.id, formData.value).subscribe(res =&gt; {<br>      this.router.navigateByUrl(&#39;players/list&#39;);<br>    });<br>  }<br>}</pre><p>In the component, it is the same as the create component, we create a form builder and validation. When the component is loaded, we query the player and positions API so that the data can be edited and create default data. And there we create the onSubmit method too. After that we will create the template.</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;br /&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      &lt;h3&gt;Update Player&lt;/h3&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col text-right&quot;&gt;<br>      &lt;a href=&quot;#&quot; routerLink=&quot;/players/list&quot; class=&quot;btn btn-secondary btn-sm&quot;&gt;Back To Players List&lt;/a&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;br /&gt;<br>  &lt;form [formGroup]=&quot;editForm&quot; (ngSubmit)=&quot;onSubmit(editForm)&quot;&gt;<br><br>    &lt;input formControlName=&quot;id&quot;<br>           id=&quot;id&quot;<br>           type=&quot;hidden&quot; /&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;shirtNo&quot;&gt;Shirt No:&lt;/label&gt;<br>      &lt;input formControlName=&quot;shirtNo&quot;<br>             id=&quot;shirtNo&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>      &lt;input formControlName=&quot;name&quot;<br>             id=&quot;name&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;name&quot;&gt;Position:&lt;/label&gt;<br>      &lt;select formControlName=&quot;positionId&quot;<br>              id=&quot;positionId&quot;<br>              class=&quot;form-control&quot;&gt;<br>        &lt;option value=&quot;&quot;&gt;- Select -&lt;/option&gt;<br>        &lt;option *ngFor=&quot;let position of positions&quot; [ngValue]=&quot;position.id&quot;&gt;<br>          {{position.name}}<br>        &lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;appearances&quot;&gt;Appearances:&lt;/label&gt;<br>      &lt;input formControlName=&quot;appearances&quot;<br>             id=&quot;appearances&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;goals&quot;&gt;Goals:&lt;/label&gt;<br>      &lt;input formControlName=&quot;goals&quot;<br>             id=&quot;goals&quot;<br>             type=&quot;text&quot;<br>             class=&quot;form-control&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot; [disabled]=&quot;!editForm.valid&quot;&gt;Update&lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/div&gt;</pre><p>We have successfully created the frontend application. You can start to do integration testing from the frontend. If the application runs smoothly, then the process of creating a fullstack application has been successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfIorn8MJMRn-ltpj_UtGw.png" /></figure><p>Combining ASP.NET Core with Angular gives us a powerful framework for developing scalable and maintainable full-stack applications. ASP.NET Core provides a robust backend with efficient data processing capabilities and solid security, while Angular offers a dynamic and responsive frontend with a variety of modern features. By following the guide in this article, you will have a solid foundation for building full-stack applications that can meet a variety of business needs. Feel free to continue experimenting and digging deeper into the advanced features of both technologies to improve your development skills. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bb2f2e567cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Combine ASP.NET Core MVC with TypeScript]]></title>
            <link>https://medium.com/@riffkikris13/how-to-combine-asp-net-core-mvc-with-typescript-fada2d7ea81b?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fada2d7ea81b</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 08:23:30 GMT</pubDate>
            <atom:updated>2024-08-01T08:23:30.628Z</atom:updated>
            <content:encoded><![CDATA[<p>ASP.NET Core MVC is one of the most popular frameworks for developing modern web applications. Developed by Microsoft, ASP.NET Core MVC offers many advanced features that enable developers to create scalable and maintainable web applications. When combined with TypeScript, a programming language developed by Microsoft that provides static typing on top of JavaScript, developers can enjoy a more productive and secure development experience. This article will discuss the advantages of ASP.NET Core MVC and the advantages of TypeScript in developing web applications using these two technologies.</p><h4><strong>Why ASP.NET Core 8 MVC?</strong></h4><ol><li>Cross-Platform: ASP.NET Core MVC can run on Windows, macOS, and Linux. This allows developers to build and run applications across multiple platforms without significant customization.</li><li>High Performance: ASP.NET Core is known for its high performance. With its optimized architecture, ASP.NET Core can handle requests very quickly and efficiently.</li><li>Modular and Lightweight: ASP.NET Core is designed to be modular and lightweight. Developers only need to include the components they need, which reduces overhead and improves performance.</li><li>Dependency Injection: ASP.NET Core MVC has built-in support for dependency injection, which improves code testability and maintainability.</li><li>Flexible Routing: With a powerful routing system, developers can easily organize URLs and navigation within their applications, allowing for a clean and SEO-friendly URL structure.</li><li>Razor Pages: ASP.NET Core MVC supports Razor Pages, which enable developers to build applications with a page-centric approach that simplifies code development and organization.</li></ol><h4>Combining ASP.NET Core MVC and TypeScript</h4><p>Using ASP.NET Core MVC together with TypeScript offers a powerful combination for web application development. Here are some of the benefits of this combination:</p><ol><li>Safer, More Durable Code: TypeScript’s static typing helps identify errors early, improving code quality and reliability. ASP.NET Core MVC provides a powerful and flexible framework for building secure and scalable web applications.</li><li>Better Development Experience: With the support of advanced editors and development tools, developers can enjoy a more productive development experience. Features such as autocompletion and code navigation help reduce time spent on debugging and improve development efficiency.</li><li>Maintainability and Scalability: Clearer code structures and strong contracts between application components make it easier to maintain and evolve applications over time. ASP.NET Core MVC and TypeScript both support modularity and reusable code, which are important for large, complex applications.</li></ol><h4>Guide to using Typescript in ASP.NET Core MVC</h4><p>Here I will use Visual Studio 2022 because this IDE is very suitable for .NET development. First, create an ASP.NET Core MVC project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*u29vzSbLzgSrNnLUxWEoPQ.png" /></figure><p>If so, right-click the project and select the Manage Nuget Packages menu and search for Microsoft.TypeScript.MSBuild then install it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z641n_LsdXUnNBKpIi-ynQ.png" /></figure><p>Next right click on the project and choose the TypeScript JSON Configuration File. For now leave the default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*2eByT6Y5BUJDOHlJTTg32g.png" /></figure><p>Next, create 1 folder, here I named it scripts. Create a typescript file and create a function that you want to run for the button, here I only display a random number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MoWUaabm4ILJj8GgNrQrg.png" /></figure><p>I will create a button element in the html index, add a button and give it a function in the onclick section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWjqV6rGOKGowBnG4yVAQw.png" /></figure><p>Add the previously created js script to the _Layout.cshtml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IY6aCjaHDXRyddXggNXlIQ.png" /></figure><p>Try running the project, visit the website and click the button. If it works then we have successfully added Typescript to ASP.NET Core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XGnovFmArPYhKPZhL5RnA.png" /></figure><h4>Conclusion</h4><p>Using ASP.NET Core MVC together with TypeScript is a very effective approach to building modern web applications. Both offer a variety of features that improve application productivity, security, and maintainability. By leveraging the strengths of both technologies, developers can build robust, scalable, and easy-to-maintain web applications. This combination is an excellent choice for development teams looking to improve the quality and efficiency of their web application development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fada2d7ea81b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Hexagonal Architecture Implementation Using Golang]]></title>
            <link>https://medium.com/@riffkikris13/simple-hexagonal-architecture-implementation-using-golang-369277bda26f?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/369277bda26f</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 09:13:41 GMT</pubDate>
            <atom:updated>2024-07-22T09:13:41.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, in this article we will discuss what hexagonal architecture is and a simple example of its implementation using Golang. Without wasting much time let’s get started.</p><h3>1. Definition</h3><p>Hexagonal architecture, also known as the Ports and Adapters architecture, was formulated by Alistair Cockburn in 2005. This architecture focuses on isolating business logic from other components, such as the controller and repository. This architecture focuses on isolating business logic from other components, such as the controller and repository. This aims to ensure that if changes occur to components other than the business logic, it will not disrupt the business logic. It is the other components that depend on business logic.</p><p>The fundamental principles of hexagonal architecture can be summarized in three key points:</p><ol><li><strong>Isolation of Business Logic</strong>: The application’s business logic is separated from its technical implementation. This separation is achieved by breaking the application into three distinct parts: the Business (or Core) part, the Interface part (Drivers, Primary Actors, those who invoke the application), and the Infrastructure part (Driven, Secondary Actors, those called by the application). The Business part is isolated within a fictitious structure often represented by an hexagon, hence the name.</li><li><strong>Independence of the Business Part</strong>: According to hexagonal architecture, the Business part is independent of everything else. It is the Interface and Infrastructure parts that depend on the Business part. In other words, dependencies are established from the outside to the inside of the hexagon.</li><li><strong>Ports and Adapters</strong>: To enable communication between the Business part and the external world (Drivers and Driven), hexagonal architecture relies on the concept of ports and adapters. Adapters act as translators between the business domain and the external technical part. Ports define the interfaces with which adapters interact with the Core. Both are essential to manage changes in the external world without affecting the business logic.</li></ol><p>This organization ensures that any technical change has no impact on the business logic, reducing the risk of regressions and simplifying tests of the business part.</p><h3>2. Backend Development</h3><p>After knowing what hexagonal architecture is, let’s make an example of its implementation using Golang, first create a project.</p><pre>go mod init warehouse</pre><p>After that we need to install several required libraries.</p><pre>go get github.com/gofiber/fiber/v2<br>go get go.mongodb.org/mongo-driver/mongo<br>go get go.mongodb.org/mongo-driver/mongo/options<br>go get github.com/joho/godotenv<br>go get go.opentelemetry.io/otel<br>go get go.opentelemetry.io/otel/sdk<br>go get go.opentelemetry.io/otel/exporters/stdout/stdouttrace</pre><p>We install several libraries such as fiber, godotenv, opentelemetry, and others. In this application we will also use MongoDB as a database. Here I will use Docker to create a database, so we will create compose first.</p><pre>version: &quot;3.8&quot;<br><br>services:<br>  wrdb:<br>    container_name: wrdb<br>    image: mongo<br>    ports:<br>      - &quot;27017:27017&quot;</pre><p>Run the compose and enter the container then create a collection along with a json schema for validation needs.</p><pre>{<br>  &quot;$jsonSchema&quot;: {<br>    &quot;bsonType&quot;: &quot;object&quot;,<br>    &quot;required&quot;: [&quot;product_name&quot;, &quot;stock&quot;, &quot;created_at&quot;, &quot;updated_at&quot;],<br>    &quot;properties&quot;: {<br>      &quot;product_name&quot;: {<br>        &quot;bsonType&quot;: &quot;string&quot;,<br>        &quot;description&quot;: &quot;The product name must be a string and is required.&quot;<br>      },<br>      &quot;stock&quot;: {<br>        &quot;bsonType&quot;: &quot;int&quot;,<br>        &quot;description&quot;: &quot;The stock quantity must be an integer and is required.&quot;<br>      },<br>      &quot;created_at&quot;: {<br>        &quot;bsonType&quot;: &quot;date&quot;,<br>        &quot;description&quot;: &quot;The date and time when the product was created; it must be a date.&quot;<br>      },<br>      &quot;updated_at&quot;: {<br>        &quot;bsonType&quot;: &quot;date&quot;,<br>        &quot;description&quot;: &quot;The date and time when the product was last updated; it must be a date.&quot;<br>      }<br>    }<br>  }<br>}</pre><p>We have successfully setup the database and created a collection, then we will start creating the application. The folder structure that we will use will be like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*h0NK5ueekH87wqwxJEfIcw.png" /></figure><p>The domain folder contains the ports or interfaces that will be the contracts for the adapters. The adapter folder contains the implementation required for the application. The infrastructure folder contains models and connection objects to the database. And we will save the business logic in the app folder. Next, we will create the model and db client first.</p><pre>package model<br><br>import (<br> &quot;time&quot;<br><br> &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br>)<br><br>type Product struct {<br> ID          primitive.ObjectID `json:&quot;id&quot; bson:&quot;_id,omitempty&quot;`<br> ProductName string             `json:&quot;productName&quot; bson:&quot;product_name&quot;`<br> Stock       int                `json:&quot;stock&quot; bson:&quot;stock&quot;`<br> CreatedAt   time.Time          `json:&quot;createdAt&quot; bson:&quot;created_at&quot;`<br> UpdateAt    time.Time          `json:&quot;updatedAt&quot; bson:&quot;updated_at&quot;`<br>}</pre><p>The model is also used for body parsing. In the original project, you need to make 2 versions to make it cleaner, because this is just a simple example, so to avoid being long I will make 1. Next we will create a db client</p><pre>package mongodb<br><br>import (<br> &quot;context&quot;<br> &quot;os&quot;<br><br> &quot;go.mongodb.org/mongo-driver/mongo&quot;<br> &quot;go.mongodb.org/mongo-driver/mongo/options&quot;<br>)<br><br>func NewClient() (*mongo.Client, error) {<br> clientOptions := options.Client().ApplyURI(os.Getenv(&quot;MONGODB_URI&quot;))<br> client, err := mongo.Connect(context.Background(), clientOptions)<br> if err != nil {<br>  return nil, err<br> }<br><br> if err := client.Ping(context.Background(), nil); err != nil {<br>  return nil, err<br> }<br><br> return client, nil<br>}</pre><p>After that we will create a port for the http handler and repository.</p><pre>package domain<br><br>import &quot;github.com/gofiber/fiber/v2&quot;<br><br>type Handler interface {<br> GetProducts(c *fiber.Ctx) error<br> GetProduct(c *fiber.Ctx) error<br> Insert(c *fiber.Ctx) error<br> Update(c *fiber.Ctx) error<br> Delete(c *fiber.Ctx) error<br>}</pre><pre>package domain<br><br>import (<br> &quot;warehouse/infrastructure/mongodb/model&quot;<br><br> &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br> &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>)<br><br>type Repository interface {<br> FindAll() ([]model.Product, error)<br> Insert(product model.Product) (*mongo.InsertOneResult, error)<br> FindByID(id primitive.ObjectID) (model.Product, error)<br> Update(id primitive.ObjectID, product model.Product) (*mongo.UpdateResult, error)<br> Delete(id primitive.ObjectID) (*mongo.DeleteResult, error)<br>}</pre><p>After that we will create an adapter for the repository.</p><pre>package app<br><br>import (<br> &quot;context&quot;<br> &quot;warehouse/domain&quot;<br><br> &quot;warehouse/infrastructure/mongodb/model&quot;<br><br> &quot;go.mongodb.org/mongo-driver/bson&quot;<br> &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br> &quot;go.mongodb.org/mongo-driver/mongo&quot;<br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/trace&quot;<br>)<br><br>type repository struct {<br> client     *mongo.Client<br> db         string<br> collection string<br> tracer     trace.Tracer<br>}<br><br>func NewRepository(client *mongo.Client, db, collection string) domain.Repository {<br> return &amp;repository{<br>  client:     client,<br>  db:         db,<br>  collection: collection,<br>  tracer:     otel.Tracer(&quot;warehouse/repository&quot;),<br> }<br>}<br><br>func (r *repository) FindAll() ([]model.Product, error) {<br> collection := r.client.Database(r.db).Collection(r.collection)<br> ctx, span := r.tracer.Start(context.Background(), &quot;FindAll&quot;)<br> defer span.End()<br><br> cur, err := collection.Find(ctx, map[string]interface{}{})<br> if err != nil {<br>  span.RecordError(err)<br>  return nil, err<br> }<br> defer cur.Close(context.Background())<br><br> var products []model.Product<br> if err := cur.All(context.Background(), &amp;products); err != nil {<br>  return nil, err<br> }<br> return products, nil<br>}<br><br>func (r *repository) FindByID(id primitive.ObjectID) (model.Product, error) {<br> collection := r.client.Database(r.db).Collection(r.collection)<br> ctx, span := r.tracer.Start(context.Background(), &quot;FindByID&quot;)<br> defer span.End()<br><br> filter := bson.M{&quot;_id&quot;: id}<br> var product model.Product<br> err := collection.FindOne(ctx, filter).Decode(&amp;product)<br> if err != nil {<br>  span.RecordError(err)<br>  return model.Product{}, err<br> }<br><br> return product, nil<br>}<br><br>func (r *repository) Insert(product model.Product) (*mongo.InsertOneResult, error) {<br> collection := r.client.Database(r.db).Collection(r.collection)<br> ctx, span := r.tracer.Start(context.Background(), &quot;Insert&quot;)<br> defer span.End()<br><br> result, err := collection.InsertOne(ctx, product)<br> if err != nil {<br>  span.RecordError(err)<br>  return nil, err<br> }<br><br> return result, nil<br>}<br><br>func (r *repository) Update(id primitive.ObjectID, product model.Product) (*mongo.UpdateResult, error) {<br> collection := r.client.Database(r.db).Collection(r.collection)<br> ctx, span := r.tracer.Start(context.Background(), &quot;Update&quot;)<br> defer span.End()<br><br> filter := bson.M{&quot;_id&quot;: id}<br> update := bson.M{&quot;$set&quot;: product}<br><br> result, err := collection.UpdateOne(ctx, filter, update)<br> if err != nil {<br>  span.RecordError(err)<br>  return nil, err<br> }<br><br> return result, nil<br>}<br><br>func (r *repository) Delete(id primitive.ObjectID) (*mongo.DeleteResult, error) {<br> collection := r.client.Database(r.db).Collection(r.collection)<br> ctx, span := r.tracer.Start(context.Background(), &quot;Delete&quot;)<br> defer span.End()<br><br> filter := bson.M{&quot;_id&quot;: id}<br> result, err := collection.DeleteOne(ctx, filter)<br> if err != nil {<br>  span.RecordError(err)<br>  return nil, err<br> }<br><br> return result, nil<br>}</pre><p>In this implementation we only perform normal CRUD operations, because our focus here is the architecture. Next we will create an adapter for the http handler.</p><pre>package http<br><br>import (<br> db &quot;warehouse/adapter/db&quot;<br> &quot;warehouse/app&quot;<br> &quot;warehouse/infrastructure/mongodb/model&quot;<br><br> &quot;github.com/gofiber/fiber/v2&quot;<br> &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br> &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>)<br><br>type Handler struct {<br> service *app.Service<br>}<br><br>func NewHandler(dbClient *mongo.Client) *Handler {<br> repo := db.NewRepository(dbClient, &quot;warehouse&quot;, &quot;products&quot;)<br> service := app.NewService(repo)<br> return &amp;Handler{service: service}<br>}<br><br>func (h *Handler) GetProducts(c *fiber.Ctx) error {<br> products, err := h.service.GetProducts()<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).SendString(err.Error())<br> }<br> return c.JSON(products)<br>}<br><br>func (h *Handler) GetProduct(c *fiber.Ctx) error {<br> idHex := c.Params(&quot;id&quot;)<br> id, err := primitive.ObjectIDFromHex(idHex)<br> if err != nil {<br>  return c.Status(fiber.StatusBadRequest).SendString(err.Error())<br> }<br><br> product, err := h.service.GetProduct(id)<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).SendString(err.Error())<br> }<br><br> return c.JSON(product)<br>}<br><br>func (h *Handler) Insert(c *fiber.Ctx) error {<br> var product model.Product<br> if err := c.BodyParser(&amp;product); err != nil {<br>  return c.Status(fiber.StatusBadRequest).SendString(err.Error())<br> }<br><br> result, err := h.service.Insert(product)<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).SendString(err.Error())<br> }<br><br> return c.JSON(result)<br>}<br><br>func (h *Handler) Update(c *fiber.Ctx) error {<br> idHex := c.Params(&quot;id&quot;)<br> id, err := primitive.ObjectIDFromHex(idHex)<br> if err != nil {<br>  return c.Status(fiber.StatusBadRequest).SendString(err.Error())<br> }<br><br> var product model.Product<br> if err := c.BodyParser(&amp;product); err != nil {<br>  return c.Status(fiber.StatusBadRequest).SendString(err.Error())<br> }<br><br> result, err := h.service.Update(id, product)<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).SendString(err.Error())<br> }<br><br> return c.JSON(result)<br>}<br><br>func (h *Handler) Delete(c *fiber.Ctx) error {<br> idHex := c.Params(&quot;id&quot;)<br> id, err := primitive.ObjectIDFromHex(idHex)<br> if err != nil {<br>  return c.Status(fiber.StatusBadRequest).SendString(err.Error())<br> }<br><br> result, err := h.service.Delete(id)<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).SendString(err.Error())<br> }<br><br> return c.JSON(result)<br>}</pre><p>The adapter for the http handler is complete, but if you look at the port repository, the parameters and return type are not general. So if you want to be general, you need to create a type alias to make it general, or you can also use generic features. Next we will create business logic.</p><pre>package app<br><br>import (<br> &quot;time&quot;<br> &quot;warehouse/domain&quot;<br> &quot;warehouse/infrastructure/mongodb/model&quot;<br><br> &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br> &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>)<br><br>type Service struct {<br> repo domain.Repository<br>}<br><br>func NewService(repo domain.Repository) *Service {<br> return &amp;Service{repo: repo}<br>}<br><br>func (s *Service) GetProducts() ([]model.Product, error) {<br> return s.repo.FindAll()<br>}<br><br>func (s *Service) GetProduct(id primitive.ObjectID) (model.Product, error) {<br> return s.repo.FindByID(id)<br>}<br><br>func (s *Service) Insert(product model.Product) (*mongo.InsertOneResult, error) {<br> now := time.Now()<br> product.CreatedAt = now<br> product.UpdateAt = now<br><br> result, err := s.repo.Insert(product)<br> if err != nil {<br>  return nil, err<br> }<br><br> return result, nil<br>}<br><br>func (s *Service) Update(id primitive.ObjectID, product model.Product) (*mongo.UpdateResult, error) {<br> now := time.Now()<br> product.UpdateAt = now<br><br> result, err := s.repo.Update(id, product)<br> if err != nil {<br>  return nil, err<br> }<br><br> return result, nil<br>}<br><br>func (s *Service) Delete(id primitive.ObjectID) (*mongo.DeleteResult, error) {<br> result, err := s.repo.Delete(id)<br> if err != nil {<br>  return nil, err<br> }<br><br> return result, nil<br>}</pre><p>Next we will create the main file.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;warehouse/adapter/http&quot;<br> &quot;warehouse/domain&quot;<br> &quot;warehouse/infrastructure/mongodb&quot;<br><br> &quot;github.com/gofiber/fiber/v2&quot;<br> &quot;github.com/joho/godotenv&quot;<br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/exporters/stdout/stdouttrace&quot;<br> &quot;go.opentelemetry.io/otel/sdk/trace&quot;<br>)<br><br>func main() {<br> if err := godotenv.Load(); err != nil {<br>  log.Println(&quot;Error loading .env file&quot;)<br> }<br><br> logFile, err := os.OpenFile(&quot;app.log&quot;, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to open log file: %v&quot;, err)<br> }<br> defer logFile.Close()<br> log.SetOutput(logFile)<br><br> exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())<br> if err != nil {<br>  log.Fatalf(&quot;Failed to create trace exporter: %v&quot;, err)<br> }<br><br> tp := trace.NewTracerProvider(<br>  trace.WithBatcher(exporter),<br> )<br> otel.SetTracerProvider(tp)<br><br> app := fiber.New()<br><br> dbClient, err := mongodb.NewClient()<br> if err != nil {<br>  log.Fatalf(&quot;Failed to connect to MongoDB: %v&quot;, err)<br> }<br><br> var handler domain.Handler = http.NewHandler(dbClient)<br> app.Get(&quot;/product&quot;, handler.GetProducts)<br> app.Get(&quot;/product/:id&quot;, handler.GetProduct)<br> app.Post(&quot;/product&quot;, handler.Insert)<br> app.Patch(&quot;/product/:id&quot;, handler.Update)<br> app.Delete(&quot;/product/:id&quot;, handler.Delete)<br><br> port := os.Getenv(&quot;PORT&quot;)<br> if port == &quot;&quot; {<br>  port = &quot;3000&quot;<br> }<br> app.Listen(&quot;:&quot; + port)<br>}</pre><p>We have completed the application. That’s my article. Hope it is useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=369277bda26f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Upload with NestJs and AngularJs]]></title>
            <link>https://medium.com/@riffkikris13/file-upload-with-nestjs-and-angularjs-eea85b564d48?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea85b564d48</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 09:41:52 GMT</pubDate>
            <atom:updated>2024-07-03T09:41:52.676Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, today I will discuss how to create a file upload feature with NestJs and Angular. In the backend I will add BullMQ for asynchronous processes. Without wasting any more time, let’s get started.</p><h4>1. Database Setup</h4><p>Here we will use 2 databases, namely PostgreSql and Redis. Redis is used as a message broker function integrated with BullMQ. I will use docker to install the two databases.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  postgresql:<br>    image: postgres<br>    container_name: db_book<br>    environment:<br>      POSTGRES_USER: user<br>      POSTGRES_PASSWORD: 123<br>    ports:<br>      - &quot;5432:5432&quot;<br>  redis:<br>    image: redis<br>    container_name: bullmq<br>    ports:<br>      - &quot;6379:6379&quot;</pre><p>Run docker compose and create a table in PostgreSql.</p><pre>CREATE TABLE books (<br>    id SERIAL PRIMARY KEY,<br>    title VARCHAR(255) NOT NULL,<br>    author VARCHAR(100) NOT NULL,<br>    published_year VARCHAR(5)<br>);</pre><h4>2. Backend</h4><p>First, make sure you have installed the Nest CLI on your device. If not, you can use the command below.</p><pre>npm install -g @nestjs/cli</pre><p>If it is installed, create a nest project and enter the directory then create a module and controller.</p><pre>nest new file-upload-be<br>nest generate module book<br>nest generate controller book</pre><p>After that we will install the required libraries. In this project I used TypeORM as the ORM.</p><pre>npm install @nestjs/config @nestjs/bull @nestjs/typeorm bull csvtojson multer typeorm</pre><p>Next we will create a books table entity.</p><pre>@Entity({ name: &#39;books&#39; })<br>export class Book {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column({ length: 255 })<br>  title: string;<br><br>  @Column({ length: 100 })<br>  author: string;<br><br>  @Column({ length: 5 })<br>  published_year: string;<br>}</pre><p>Go to BookModule then add the entity that we created earlier and create a BullMQ queue for the file upload process.</p><pre>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([Book]),<br>    BullModule.registerQueue({<br>      name: &#39;upload-queue&#39;,<br>    }),<br>  ],<br>  providers: [BookService, BookProcessor],<br>  controllers: [BookController],<br>})<br>export class BookModule {}</pre><p>Next we will provide configuration to the AppModule. First create a module that handles env variables. After that, create a TypeORM configuration via env variable, and finally provide the configuration to BullMQ.</p><pre>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>    }),<br>    TypeOrmModule.forRootAsync({<br>      imports: [ConfigModule],<br>      useFactory: async (configService: ConfigService) =&gt; ({<br>        type: &#39;postgres&#39;,<br>        host: configService.get&lt;string&gt;(&#39;POSTGRES_HOST&#39;),<br>        port: parseInt(configService.get&lt;string&gt;(&#39;POSTGRES_PORT&#39;), 10),<br>        username: configService.get&lt;string&gt;(&#39;POSTGRES_USER&#39;),<br>        password: configService.get&lt;string&gt;(&#39;POSTGRES_PASSWORD&#39;),<br>        database: configService.get&lt;string&gt;(&#39;POSTGRES_DATABASE&#39;),<br>        autoLoadEntities: true,<br>        synchronize: false,<br>      }),<br>      inject: [ConfigService],<br>    }),<br>    BullModule.forRoot({<br>      redis: {<br>        host: &#39;localhost&#39;,<br>        port: 6379,<br>      },<br>    }),<br>    BookModule,<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>To receive messages via Redis, we need to create a processor, so we will create one.</p><pre>@Processor(&#39;upload-queue&#39;)<br>export class BookProcessor {<br>  constructor(<br>    @InjectRepository(Book) private bookRepository: Repository&lt;Book&gt;,<br>  ) {}<br><br>  @Process(&#39;csv-book&#39;)<br>  async handleCSVBook(job: Job) {<br>    const bookArray = await csv().fromFile(<br>      process.cwd() + &#39;/&#39; + job.data.file.path,<br>    );<br>    console.log(bookArray);<br><br>    this.bookRepository.save(bookArray);<br>  }<br>}</pre><p>On this processor we use “upload-queue” as the BullMQ queue. In the handleCSVBook method we name the process as “csv-book”. This is similar to Kafka, but the difference is that we need Redis as an intermediary. In this method we also convert the CSV file that is sent and then insert it into PostgreSql. Next we will create a controller.</p><pre>@Controller(&#39;book&#39;)<br>export class BookController {<br>  constructor(@InjectQueue(&#39;upload-queue&#39;) private fileQueue: Queue) {}<br><br>  @Post()<br>  @UseInterceptors(<br>    FileInterceptor(&#39;file&#39;, {<br>      storage: diskStorage({<br>        destination: &#39;./csv/book&#39;,<br>        filename: (_, file, cb) =&gt; {<br>          const epochTimeMillis = Date.now();<br>          const randomChars = Math.random().toString(36).substring(2, 6);<br>          const newFileName = `${epochTimeMillis}-${randomChars}-${file.originalname}`;<br>          cb(null, newFileName);<br>        },<br>      }),<br>    }),<br>  )<br>  async uploadBookCSV(@UploadedFile() file) {<br>    this.fileQueue.add(&#39;csv-book&#39;, { file });<br>  }<br>}</pre><p>In this controller we only create 1 method and in that method we create an interceptor which functions to save the CSV file sent by the user into the “./csv/book” folder. We also change the file name format to “Epoch Time Millis+4 char random+file name”. In this method we only send messages to Redis which will be captured by the processor. And don’t forget to configure CORS and create an env file.</p><pre>POSTGRES_HOST=localhost<br>POSTGRES_PORT=5432<br>POSTGRES_USER=user<br>POSTGRES_PASSWORD=123<br>POSTGRES_DATABASE=postgres</pre><p>Please try running the application, try checking Redis, if there is a bull folder, then the application is connected to PostgreSql and Redis. We will do API testing at the end of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*HWY0szR-oK7UcUe0KQnxaw.png" /></figure><h4>3. Frontend</h4><p>Before creating an Angular project, you need to install the CLI so you can generate an Angular project. If so, you can generate an Angular project with the command.</p><pre>ng new student-fe --standalone=false</pre><p>In this Angular project, we will use the help of Angular-Material to make it easier to create the application layout. Install Angular-Material using command.</p><pre>ng add @angular/material</pre><p>Next we will generate services and components.</p><pre>ng g c components/navbar<br>ng g c components/book<br>ng g c components/dashboard<br>ng g s services/book/book</pre><p>Go to AppModule and import several modules needed for the application to run. In this module we also add routing.</p><pre>@NgModule({<br>  declarations: [AppComponent, BookComponent, NavbarComponent, DashboardComponent],<br>  imports: [<br>    BrowserModule,<br>    AppRoutingModule,<br>    HttpClientModule,<br>    BrowserAnimationsModule,<br>    MatToolbarModule,<br>    MatButtonModule,<br>    MatIconModule,<br>    ReactiveFormsModule,<br>    MatInputModule,<br>    RouterModule.forRoot([<br>      { path: &#39;&#39;, redirectTo: &#39;/dashboard&#39;, pathMatch: &#39;full&#39; },<br>      { path: &#39;dashboard&#39;, component: DashboardComponent },<br>      { path: &#39;book&#39;, component: BookComponent },<br>    ]),<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent],<br>})<br>export class AppModule {}</pre><p>For app template, provide an outlet for routing to run.</p><pre>&lt;app-navbar&gt;&lt;/app-navbar&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Next we will create a service. In this service we only create 1 method to send CSV files to the Backend.</p><pre>const url = &#39;http://localhost:3000/book&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class BookService {<br><br>  constructor(private http: HttpClient) {}<br><br>  createBooks(data: FormData): Observable&lt;any&gt; {<br>    return this.http.post(url, data);<br>  }<br>}</pre><p>After that we will create a Navbar.</p><pre>&lt;mat-toolbar color=&quot;primary&quot;&gt;<br>  &lt;mat-toolbar-row&gt;<br>    &lt;span&gt;North Library&lt;/span&gt;<br>    &lt;div class=&quot;navigation&quot;&gt;<br>        &lt;button mat-button routerLink=&quot;/dashboard&quot;&gt;Dashboard&lt;/button&gt;<br>        &lt;button mat-button routerLink=&quot;/book&quot;&gt;Book&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/mat-toolbar-row&gt;<br>&lt;/mat-toolbar&gt;</pre><p>There is nothing special about the Navbar, just a simple Navbar because here we are only testing the API that we created earlier. And for the dashboard we leave the default. Next we will create a book component.</p><pre>@Component({<br>  selector: &#39;app-book&#39;,<br>  templateUrl: &#39;./book.component.html&#39;,<br>  styleUrl: &#39;./book.component.scss&#39;<br>})<br>export class BookComponent {<br>  uploadForm: FormGroup;<br>  fileSelected: boolean = false;<br>  fileError: boolean = false;<br>  fileToUpload: File | null = null;<br><br>  constructor(<br>    private fb: FormBuilder,<br>    private bookService: BookService<br>  ) {<br>    this.uploadForm = this.fb.group({<br>      csvFile: [null, Validators.required]<br>    });<br>  }<br><br>  onFileChange(event: any) {<br>    const file = event.target.files[0];<br>    if (file &amp;&amp; file.type === &#39;text/csv&#39;) {<br>      this.fileToUpload = file;<br>      this.fileSelected = true;<br>      this.fileError = false;<br>    } else {<br>      this.fileError = true;<br>      this.fileSelected = false;<br>    }<br>  }<br><br>  onSubmit() {<br>    if (this.fileToUpload) {<br>      const formData = new FormData();<br>      formData.append(&#39;file&#39;, this.fileToUpload);<br><br>      this.bookService.createBooks(formData).subscribe(() =&gt; {<br>        console.log(&quot;success&quot;);<br>      });<br>    }<br>  }<br>}</pre><p>In the book component we will use reactive forms for form handling. And there we create several methods, the first is onFileChange which is used to receive file input provided by the user, and the second is onSubmit which is used to send requests to the API. Next we will create a book component template.</p><pre>&lt;form [formGroup]=&quot;uploadForm&quot; (ngSubmit)=&quot;onSubmit()&quot; class=&quot;upload-form&quot;&gt;<br>  &lt;label for=&quot;file&quot; class=&quot;file-label&quot;&gt;Upload CSV File&lt;/label&gt;<br>  &lt;input<br>    type=&quot;file&quot;<br>    id=&quot;file&quot;<br>    (change)=&quot;onFileChange($event)&quot;<br>    class=&quot;file-input&quot;<br>    required<br>  /&gt;<br>  &lt;mat-error *ngIf=&quot;fileError&quot;<br>    &gt;CSV file is required and must be valid&lt;/mat-error<br>  &gt;<br>  &lt;button<br>    mat-raised-button<br>    color=&quot;primary&quot;<br>    type=&quot;submit&quot;<br>    [disabled]=&quot;!fileSelected&quot;<br>  &gt;<br>    Submit<br>  &lt;/button&gt;<br>&lt;/form&gt;</pre><p>As usual in this template we use the form group that we have created in the book component and bind the onSubmit method. In it we input the file type and bind it to the onFileChange method, then the button and error message. Next, we will carry out testing on the application that we have created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQA8tEcsxsEL_Xk_IJyKLA.png" /><figcaption>Frontend</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*E7JC-Z43k38ZTyeiDhwMBg.png" /><figcaption>csv file folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*jiC4GDM9-1B0-h8lJdekjA.png" /><figcaption>Postgre</figcaption></figure><p>If the test goes smoothly, then my article will end here. Thank you for reading my article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea85b564d48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple App with NestJs and AngularJs]]></title>
            <link>https://medium.com/@riffkikris13/simple-app-with-nestjs-and-angularjs-5fad3e703d59?source=rss-dbd5ab6199e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fad3e703d59</guid>
            <dc:creator><![CDATA[Riffki Krisdiyanto]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 10:04:35 GMT</pubDate>
            <atom:updated>2024-07-01T10:04:35.972Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, today I will share how to create an application using NestJs and Angular. This article only explains the basics that you need to know when creating applications with this technology. Apart from the 2 technologies mentioned above, we will use 2 databases, namely MySql and MongoDb.</p><h4><strong>1. Database Setup</strong></h4><p>To install the database, we will use Docker. First, we create docker compose to create containers for the two databases.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  mysql:<br>    image: mysql<br>    container_name: mysql_container<br>    environment:<br>      MYSQL_ROOT_PASSWORD: 123<br>      MYSQL_USER: main<br>      MYSQL_PASSWORD: 123<br>    ports:<br>      - &quot;3306:3306&quot;<br><br>  mongodb:<br>    image: mongo<br>    container_name: mongo_container<br>    ports:<br>      - &quot;27017:27017&quot;</pre><p>After that, enter the MySql container and create a database and table there.</p><pre>CREATE TABLE students (<br>    nis INT PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    email VARCHAR(50) NOT NULL,<br>    phone VARCHAR(30) NOT NULL,<br>    class_name VARCHAR(10) NOT NULL<br>);</pre><h4>2. Backend</h4><p>If you have used Spring before, then when you learn NestJs you won’t have any difficulty, because the pattern is almost the same. What differentiates NestJs from Spring is that NestJs uses module based, whereas Spring uses layer based. To generate a NestJs project, we need to install the NestJs CLI on our device.</p><pre>npm install -g @nestjs/cli</pre><p>If you install the CLI, then we will generate it with the command below.</p><pre>nest new student-be</pre><p>After that, go to the project directory and we will create a module, controller and service.</p><pre>nest generate module student<br>nest generate controller student<br>nest generate service student </pre><p>This is one of the advantages of NestJs over Spring, we can create controllers and services just with the help of commands. For installed dependencies, you can see the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*cpb5xjlVEWl4GKuw9VOQxg.png" /></figure><p>There I use the mysql2 driver because the version of MySql we are using is version 8. After that we will configure the database connection.</p><pre>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>    }),<br>    TypeOrmModule.forRootAsync({<br>      imports: [ConfigModule],<br>      useFactory: async (configService: ConfigService) =&gt; ({<br>        type: &#39;mysql&#39;,<br>        host: configService.get&lt;string&gt;(&#39;MYSQL_HOST&#39;),<br>        port: parseInt(configService.get&lt;string&gt;(&#39;MYSQL_PORT&#39;), 10),<br>        username: configService.get&lt;string&gt;(&#39;MYSQL_USER&#39;),<br>        password: configService.get&lt;string&gt;(&#39;MYSQL_PASSWORD&#39;),<br>        database: configService.get&lt;string&gt;(&#39;MYSQL_DATABASE&#39;),<br>        autoLoadEntities: true,<br>        synchronize: false,<br>      }),<br>      inject: [ConfigService],<br>    }),<br>    MongooseModule.forRootAsync({<br>      imports: [ConfigModule],<br>      useFactory: async (configService: ConfigService) =&gt; ({<br>        uri: configService.get&lt;string&gt;(&#39;MONGO_URI&#39;),<br>      }),<br>      inject: [ConfigService],<br>    }),<br>    StudentModule,<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>We configure it in the AppModule. First, we configure the env so that the application can read configuration files. In this project we use TypeORM for MySql and Mongoose for MongoDb. For business logic, we will only perform CRUD operations on the students table. After inserting, deleting, and updating, we will carry out the same process on MongoDb, here MongoDb is only a data backup. Next we will create an env file that the application will read.</p><pre>MYSQL_HOST=localhost<br>MYSQL_PORT=3306<br>MYSQL_USER=root<br>MYSQL_PASSWORD=123<br>MYSQL_DATABASE=school<br><br>MONGO_URI=mongodb://localhost:27017/school</pre><p>Adjust the configuration to the container that we created at the beginning. We can now test run the application to check whether it can connect to the database. If it is possible then we will continue to create entities for MySql and schema for MongoDb.</p><pre>@Entity({ name: &#39;students&#39; })<br>export class StudentSQL {<br>  @PrimaryGeneratedColumn()<br>  nis: number;<br><br>  @Column({ length: 100 })<br>  name: string;<br><br>  @Column({ length: 50 })<br>  email: string;<br><br>  @Column({ length: 30 })<br>  phone: string;<br><br>  @Column({ length: 10 })<br>  class_name: string;<br>}</pre><pre>@Schema({ collection: &#39;students&#39; })<br>export class Student extends Document {<br>  @Prop()<br>  nis: number;<br><br>  @Prop()<br>  name: string;<br><br>  @Prop()<br>  email: string;<br><br>  @Prop()<br>  phone: string;<br><br>  @Prop()<br>  class_name: string;<br>}<br><br>export const StudentSchema = SchemaFactory.createForClass(Student);</pre><p>Next, we will set up the service that was generated earlier.</p><pre>@Injectable()<br>export class StudentService {<br>  constructor(<br>    @InjectRepository(StudentSQL)<br>    private studentRepository: Repository&lt;StudentSQL&gt;,<br>    @InjectModel(Student.name)<br>    private studentModel: Model&lt;Student&gt;,<br>  ) {}<br><br>  async create(student: StudentSQL) {<br>    const savedStudent = await this.studentRepository.save(student);<br><br>    const studentMongo = new this.studentModel({<br>      nis: savedStudent.nis,<br>      name: savedStudent.name,<br>      email: savedStudent.email,<br>      phone: savedStudent.phone,<br>      class_name: savedStudent.class_name,<br>    });<br>    studentMongo.save();<br><br>    return savedStudent;<br>  }<br><br>  async findAll(<br>    name: string,<br>    page: number = 1,<br>    size: number = 10,<br>  ): Promise&lt;{ data: StudentSQL[]; total: number }&gt; {<br>    const [data, total] = await this.studentRepository.findAndCount({<br>      where: {<br>        name: ILike(`%${name || &#39;&#39;}%`),<br>      },<br>      skip: (page - 1) * size,<br>      take: size,<br>    });<br><br>    return { data, total };<br>  }<br><br>  async findByNis(nis: number): Promise&lt;StudentSQL&gt; {<br>    const entity = await this.studentRepository.findOne({<br>      where: {<br>        nis: nis,<br>      },<br>    });<br>    if (!entity) {<br>      throw new NotFoundException(`Student with NIS ${nis} not found`);<br>    }<br>    return entity;<br>  }<br><br>  async update(nis: number, updateData: StudentSQL): Promise&lt;StudentSQL&gt; {<br>    const entity = await this.studentRepository.findOne({<br>      where: {<br>        nis: nis,<br>      },<br>    });<br>    if (!entity) {<br>      throw new NotFoundException(`Entity with NIS ${nis} not found`);<br>    }<br><br>    await this.studentRepository.update(nis, updateData);<br>    await this.studentModel.findOneAndUpdate({ nis }, updateData, {<br>      new: true,<br>    });<br><br>    return { ...entity, ...updateData };<br>  }<br><br>  async delete(nis: number): Promise&lt;{ deleted: boolean }&gt; {<br>    const entity = await this.studentRepository.findOne({<br>      where: {<br>        nis: nis,<br>      },<br>    });<br>    if (!entity) {<br>      throw new NotFoundException(`Entity with NIS ${nis} not found`);<br>    }<br><br>    await this.studentRepository.delete(nis);<br>    await this.studentModel.findOneAndDelete({ nis });<br><br>    return { deleted: true };<br>  }<br>}</pre><p>In this service we only create methods that are commonly used for CRUD processes. In the service class there is the <a href="http://twitter.com/Injectable">@Injectable</a>() decorator which functions to mark a class whose objects will be created automatically and can be injected into other components, this is similar to the bean concept in Spring. And classes that use this decorator are singletons, which means they are only created once. After that, we will inject the repository from ORM and ODM using the entities and schema that have been created.</p><p>If the service is ready, then we will set up the controller that we generated earlier.</p><pre>@Controller(&#39;student&#39;)<br>export class StudentController {<br>  constructor(private studentService: StudentService) {}<br><br>  @Post()<br>  async addStudent(@Body() student: StudentSQL) {<br>    return this.studentService.create(student);<br>  }<br><br>  @Get()<br>  async findAll(<br>    @Query(&#39;name&#39;) name: string,<br>    @Query(&#39;page&#39;) page: number = 1,<br>    @Query(&#39;size&#39;) size: number = 10,<br>  ): Promise&lt;{ data: StudentSQL[]; total: number }&gt; {<br>    return this.studentService.findAll(name, page, size);<br>  }<br><br>  @Get(&#39;:nis&#39;)<br>  async findByNis(@Param(&#39;nis&#39;) nis: number): Promise&lt;StudentSQL&gt; {<br>    return this.studentService.findByNis(nis);<br>  }<br><br>  @Patch(&#39;:nis&#39;)<br>  async update(<br>    @Param(&#39;nis&#39;) nis: number,<br>    @Body() updateData: StudentSQL,<br>  ): Promise&lt;StudentSQL&gt; {<br>    return this.studentService.update(nis, updateData);<br>  }<br><br>  @Delete(&#39;:nis&#39;)<br>  async delete(@Param(&#39;nis&#39;) nis: number): Promise&lt;{ deleted: boolean }&gt; {<br>    return this.studentService.delete(nis);<br>  }<br>}</pre><p>In the controller we only create an api to connect to the service we created earlier. For controllers there is the <a href="http://twitter.com/Controller">@Controller</a>() decorator, which is similar in concept to Spring. Next, we need to import the entity and schema into the student module so they can be used.</p><pre>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([StudentSQL]),<br>    MongooseModule.forFeature([<br>      {<br>        name: Student.name,<br>        schema: StudentSchema,<br>      },<br>    ]),<br>  ],<br>  controllers: [StudentController],<br>  providers: [StudentService],<br>})<br>export class StudentModule {}</pre><p>Now we have finished creating the Backend application, next we will create the Frontend application.</p><h4>3. Frontend</h4><p>Before creating an Angular project, you need to install the CLI so you can generate an Angular project. If so, you can generate an Angular project with the command.</p><pre>ng new student-fe --standalone=false</pre><p>In this Angular project, we will use the help of Angular-Material to make it easier to create the application layout. Install Angular-Material using command.</p><pre>ng add @angular/material</pre><p>Next, we will create a Student model for query processing needs to the Backend.</p><pre>export interface Student {<br>  nis: number;<br>  name: string;<br>  email: string;<br>  phone: string;<br>  class_name: string;<br>}</pre><p>Once the model has been created, we will generate the required service and components.</p><pre>ng g s services/student/student<br>ng g c components/student<br>ng g c components/student-add<br>ng g c components/student-detail<br>ng g c components/student-update</pre><p>Next we will create the service.</p><pre>const url = &#39;http://localhost:3000/student&#39;;<br><br>interface StudentFetch {<br>  data: Student[];<br>  total: number;<br>}<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class StudentService {<br>  constructor(private http: HttpClient) {}<br><br>  getStudent(nis: number): Observable&lt;Student&gt; {<br>    return this.http.get&lt;Student&gt;(url + &#39;/&#39; + nis);<br>  }<br><br>  getStudents(<br>    name: string,<br>    page: number,<br>    size: number<br>  ): Observable&lt;StudentFetch&gt; {<br>    const params = new HttpParams()<br>      .set(&#39;page&#39;, page.toString())<br>      .set(&#39;size&#39;, size.toString())<br>      .set(&#39;name&#39;, name);<br>    return this.http.get&lt;StudentFetch&gt;(url, { params });<br>  }<br><br>  createStudent(data: any): Observable&lt;any&gt; {<br>    return this.http.post(url, data);<br>  }<br><br>  updateStudent(data: Student): Observable&lt;any&gt; {<br>    return this.http.patch(url + &#39;/&#39; + data.nis, data);<br>  }<br><br>  deleteStudent(nis: number): Observable&lt;any&gt; {<br>    return this.http.delete(url + &#39;/&#39; + nis);<br>  }<br><br>  deleteStudentAndRefresh(<br>    nis: number,<br>    page: number,<br>    size: number,<br>    name: string<br>  ): Observable&lt;StudentFetch&gt; {<br>    return this.deleteStudent(nis).pipe(<br>      switchMap(() =&gt; this.getStudents(name, page, size))<br>    );<br>  }<br>}</pre><p>In this service we create methods that will be used to perform queries to the API. Just like NestJs, in Angular we can also do Dependency Injection by marking a class with the <a href="http://twitter.com/Injectable">@Injectable</a>() decorator. The deleteStudentAndRefresh method is used to refresh the table after performing a delete query. And in this service we create a model for the get data response.</p><pre>@NgModule({<br>  declarations: [AppComponent, StudentComponent, StudentAddComponent],<br>  imports: [<br>    BrowserModule,<br>    AppRoutingModule,<br>    HttpClientModule,<br>    MatTableModule,<br>    MatInputModule,<br>    MatButtonModule,<br>    FormsModule,<br>    ReactiveFormsModule,<br>    BrowserAnimationsModule,<br>    MatIconModule,<br>    RouterModule.forRoot([<br>      { path: &#39;&#39;, redirectTo: &#39;/student&#39;, pathMatch: &#39;full&#39; },<br>      { path: &#39;student&#39;, component: StudentComponent },<br>      { path: &#39;student-add&#39;, component: StudentAddComponent },<br>      { path: &#39;student-detail/:nis&#39;, component: StudentDetailComponent },<br>      { path: &#39;student-update/:nis&#39;, component: StudentUpdateComponent },<br>    ]),<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent],<br>})<br>export class AppModule {}</pre><p>In AppModule we import the required modules and create routing for the application, don’t forget to create an outlet router for routing needs in the main html.</p><pre>&lt;div class=&quot;container&quot;&gt;&lt;router-outlet&gt;&lt;/router-outlet&gt;&lt;/div&gt;</pre><p>Next we will move on to the main component, namely student.</p><pre>@Component({<br>  selector: &#39;app-student&#39;,<br>  templateUrl: &#39;./student.component.html&#39;,<br>  styleUrl: &#39;./student.component.scss&#39;,<br>})<br>export class StudentComponent implements AfterViewInit {<br>  students: Student[] = [];<br>  name: string = &#39;&#39;;<br>  total: number = 0;<br>  displayedColumns: string[] = [<br>    &#39;nis&#39;,<br>    &#39;name&#39;,<br>    &#39;email&#39;,<br>    &#39;phone&#39;,<br>    &#39;class&#39;,<br>    &#39;action&#39;,<br>  ];<br><br>  constructor(private studentService: StudentService) {}<br><br>  ngAfterViewInit(): void {<br>    this.studentService.getStudents(this.name, 1, 10).subscribe((data) =&gt; {<br>      this.students = data.data;<br>      this.total = data.total;<br>    });<br>  }<br><br>  deleteStudent(id: number): void {<br>    this.studentService<br>      .deleteStudentAndRefresh(id, 1, 10, this.name)<br>      .subscribe((data) =&gt; {<br>        this.students = data.data;<br>        this.total = data.total;<br>      });<br>  }<br></pre><p>In this component we query the API to get student data which we then display in a table. You can also see there that we create an array containing headers that will represent each column in the table. Next we will create a layout template for the student component.</p><pre>&lt;div class=&quot;table-control&quot;&gt;<br>  &lt;mat-form-field class=&quot;full-width&quot;&gt;<br>    &lt;mat-label&gt;First name&lt;/mat-label&gt;<br>    &lt;input matInput /&gt;<br>  &lt;/mat-form-field&gt;<br>  &lt;button mat-raised-button class=&quot;flex-item&quot;&gt;Search&lt;/button&gt;<br>  &lt;button<br>    mat-raised-button<br>    color=&quot;primary&quot;<br>    class=&quot;flex-item&quot;<br>    [routerLink]=&quot;[&#39;/student-add&#39;]&quot;<br>  &gt;<br>    Add Student<br>  &lt;/button&gt;<br>&lt;/div&gt;<br>&lt;table<br>  *ngIf=&quot;students &amp;&amp; students.length &gt; 0&quot;<br>  mat-table<br>  [dataSource]=&quot;students&quot;<br>  class=&quot;mat-elevation-z8&quot;<br>&gt;<br>  &lt;ng-container matColumnDef=&quot;nis&quot;&gt;<br>    &lt;th mat-header-cell *matHeaderCellDef&gt;NIS&lt;/th&gt;<br>    &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;{{ element.nis }}&lt;/td&gt;<br>  &lt;/ng-container&gt;<br>  &lt;ng-container matColumnDef=&quot;name&quot;&gt;<br>    &lt;th mat-header-cell *matHeaderCellDef&gt;Name&lt;/th&gt;<br>    &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;{{ element.name }}&lt;/td&gt;<br>  &lt;/ng-container&gt;<br>  &lt;ng-container matColumnDef=&quot;email&quot;&gt;<br>    &lt;th mat-header-cell *matHeaderCellDef&gt;Email&lt;/th&gt;<br>    &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;{{ element.email }}&lt;/td&gt;<br>  &lt;/ng-container&gt;<br>  &lt;ng-container matColumnDef=&quot;phone&quot;&gt;<br>    &lt;th mat-header-cell *matHeaderCellDef&gt;Phone&lt;/th&gt;<br>    &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;{{ element.phone }}&lt;/td&gt;<br>  &lt;/ng-container&gt;<br>  &lt;ng-container matColumnDef=&quot;class&quot;&gt;<br>    &lt;th mat-header-cell *matHeaderCellDef&gt;Class&lt;/th&gt;<br>    &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;{{ element.class_name }}&lt;/td&gt;<br>  &lt;/ng-container&gt;<br>  &lt;ng-container matColumnDef=&quot;action&quot;&gt;<br>    &lt;th mat-header-cell *matHeaderCellDef&gt;&lt;/th&gt;<br>    &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;<br>      &lt;button mat-icon-button [routerLink]=&quot;[&#39;/student-detail&#39;, element.nis]&quot;&gt;<br>        &lt;mat-icon&gt;<br>          &lt;span class=&quot;material-symbols-outlined&quot;&gt;visibility&lt;/span&gt;<br>        &lt;/mat-icon&gt;<br>      &lt;/button&gt;<br>      &lt;button mat-icon-button [routerLink]=&quot;[&#39;/student-update&#39;, element.nis]&quot;&gt;<br>        &lt;mat-icon<br>          &gt;&lt;span class=&quot;material-symbols-outlined&quot;&gt; edit &lt;/span&gt;<br>        &lt;/mat-icon&gt;<br>      &lt;/button&gt;<br>      &lt;button mat-icon-button (click)=&quot;deleteStudent(element.nis)&quot;&gt;<br>        &lt;mat-icon<br>          &gt;&lt;span class=&quot;material-symbols-outlined&quot;&gt; delete &lt;/span&gt;<br>        &lt;/mat-icon&gt;<br>      &lt;/button&gt;<br>    &lt;/td&gt;<br>  &lt;/ng-container&gt;<br>  &lt;tr mat-header-row *matHeaderRowDef=&quot;displayedColumns&quot;&gt;&lt;/tr&gt;<br>  &lt;tr mat-row *matRowDef=&quot;let row; columns: displayedColumns&quot;&gt;&lt;/tr&gt;<br>&lt;/table&gt;</pre><p>In this template we create an input that will be used for filters and there is a button to add new student data. Student data resulting from the query will be displayed in a mapped table based on the fields obtained. There are also buttons for detail, update, and delete actions on a row. Next we will move on to the student-add component.</p><pre>@Component({<br>  selector: &#39;app-student-add&#39;,<br>  templateUrl: &#39;./student-add.component.html&#39;,<br>  styleUrl: &#39;./student-add.component.scss&#39;,<br>})<br>export class StudentAddComponent {<br>  form: FormGroup;<br><br>  constructor(<br>    fb: FormBuilder,<br>    private studentService: StudentService,<br>    private router: Router<br>  ) {<br>    this.form = fb.group({<br>      nis: [&#39;&#39;, Validators.required],<br>      name: [&#39;&#39;, Validators.required],<br>      email: [&#39;&#39;, Validators.required],<br>      phone: [&#39;&#39;, Validators.required],<br>      className: [&#39;&#39;, Validators.required],<br>    });<br>  }<br><br>  onSubmit(): void {<br>    if (this.form.valid) {<br>      this.studentService<br>        .createStudent({<br>          nis: this.form.get(&#39;nis&#39;)?.value,<br>          name: this.form.get(&#39;name&#39;)?.value,<br>          email: this.form.get(&#39;email&#39;)?.value,<br>          phone: this.form.get(&#39;phone&#39;)?.value,<br>          class_name: this.form.get(&#39;className&#39;)?.value,<br>        })<br>        .subscribe(() =&gt; {<br>          this.router.navigate([&#39;/student&#39;]);<br>        });<br>    }<br>  }<br>}</pre><p>In this component we create a FormGroup which is used for validation and create an onSubmit method for querying the API. In validation you can set anything. In the example above I only set required. Next we will create a template for the student-add component.</p><pre>&lt;div class=&quot;add&quot;&gt;<br>  &lt;p class=&quot;title&quot;&gt;Add Student&lt;/p&gt;<br>  &lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>    &lt;div class=&quot;form-area&quot;&gt;<br>      &lt;mat-form-field class=&quot;example-full-width&quot;&gt;<br>        &lt;mat-label&gt;NIS&lt;/mat-label&gt;<br>        &lt;input matInput formControlName=&quot;nis&quot; /&gt;<br>        &lt;mat-error *ngIf=&quot;form.get(&#39;nis&#39;)?.invalid&quot;&gt;NIS is required&lt;/mat-error&gt;<br>      &lt;/mat-form-field&gt;<br>      &lt;mat-form-field class=&quot;example-full-width&quot;&gt;<br>        &lt;mat-label&gt;Name&lt;/mat-label&gt;<br>        &lt;input matInput formControlName=&quot;name&quot; /&gt;<br>        &lt;mat-error *ngIf=&quot;form.get(&#39;name&#39;)?.invalid&quot;<br>          &gt;Name is required&lt;/mat-error<br>        &gt;<br>      &lt;/mat-form-field&gt;<br>      &lt;mat-form-field class=&quot;example-full-width&quot;&gt;<br>        &lt;mat-label&gt;Email&lt;/mat-label&gt;<br>        &lt;input matInput formControlName=&quot;email&quot; /&gt;<br>        &lt;mat-error *ngIf=&quot;form.get(&#39;email&#39;)?.invalid&quot;<br>          &gt;Email is required&lt;/mat-error<br>        &gt;<br>      &lt;/mat-form-field&gt;<br>      &lt;mat-form-field class=&quot;example-full-width&quot;&gt;<br>        &lt;mat-label&gt;Phone&lt;/mat-label&gt;<br>        &lt;input matInput formControlName=&quot;phone&quot; /&gt;<br>        &lt;mat-error *ngIf=&quot;form.get(&#39;phone&#39;)?.invalid&quot;<br>          &gt;Phone is required&lt;/mat-error<br>        &gt;<br>      &lt;/mat-form-field&gt;<br>      &lt;mat-form-field class=&quot;example-full-width&quot;&gt;<br>        &lt;mat-label&gt;Class Name&lt;/mat-label&gt;<br>        &lt;input matInput formControlName=&quot;className&quot; /&gt;<br>        &lt;mat-error *ngIf=&quot;form.get(&#39;className&#39;)?.invalid&quot;<br>          &gt;Class Name is required&lt;/mat-error<br>        &gt;<br>      &lt;/mat-form-field&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;button-area&quot;&gt;<br>      &lt;button<br>        routerLink=&quot;/student&quot;<br>        mat-stroked-button<br>        class=&quot;cancel&quot;<br>        color=&quot;warn&quot;<br>        type=&quot;button&quot;<br>      &gt;<br>        Cancel<br>      &lt;/button&gt;<br>      &lt;button<br>        mat-flat-button<br>        class=&quot;submit&quot;<br>        type=&quot;submit&quot;<br>        color=&quot;primary&quot;<br>        [disabled]=&quot;form.invalid&quot;<br>      &gt;<br>        Submit<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>&lt;/div&gt;</pre><p>In the template above, we create a form with the help of the FormGroup that we created earlier in the component. For input, we use the input provided by Angular-Material and create several inputs to create the data needed to be able to add new student data. Don’t forget to put the submit button in the form tag and if you have another button in the form tag, you need to set the type to button so that the form can be executed when you enter. If so, all you have to do is create detailed components and update them. The update pattern is almost the same as add, but the difference is that we have to first get the data with the nis, then in the details you just have to display the student data based on the nis attached. If everything has been created, you can test the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3t1l_DxjJPbiR-ZBQZgUQ.png" /></figure><p>If the application testing goes smoothly and shows that the Frontend is connected to the Backend, then I finish the application creation process here. Thank you for reading my article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fad3e703d59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>