<?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 Jose Luis Campos Bautista on Medium]]></title>
        <description><![CDATA[Stories by Jose Luis Campos Bautista on Medium]]></description>
        <link>https://medium.com/@bautistaj20?source=rss-df03dc92eb68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*COvZISxfgudwcsxp_qmMJA.jpeg</url>
            <title>Stories by Jose Luis Campos Bautista on Medium</title>
            <link>https://medium.com/@bautistaj20?source=rss-df03dc92eb68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:53:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bautistaj20/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[Security on Your PostgreSQL Setup: The Basics I Learned]]></title>
            <link>https://javascript.plainenglish.io/security-on-your-postgresql-setup-the-basics-i-learned-c3d54e7054bd?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d54e7054bd</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[database-security]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 20:33:17 GMT</pubDate>
            <atom:updated>2025-09-10T17:00:03.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*nyhHHin7WyShX9nNT_1z2A.png" /><figcaption>PostgreSQL</figcaption></figure><p>Nowadays, there are plenty of tools and services that make database management fast, cheap, and effortless. But even if you’re just starting out — like me — I believe it’s worth understanding how to set up a database securely and grasp the basics behind it.</p><p>Here’s what I learned (and applied) about basic PostgreSQL security, from a beginner’s perspective.</p><p><em>📝 Learning Note: I’m sharing my learning journey with server and database security. These fundamentals worked for me, but security has many layers — there’s always more to explore. Experienced DBAs, drop your wisdom in the comments! 🙏</em></p><p><strong>Note:</strong> The steps I’m sharing were applied on Ubuntu Server 22.04 and PostgreSQL 16</p><h3>1. Separate Development and Production</h3><p>This prevents test code or bugs from corrupting live data. Simple, but important.</p><pre># Install updates<br>sudo apt-get update<br>sudo apt-get install wget gnupg lsb-release -y</pre><pre># Install updates<br># Configure the system to securely download and install PostgreSQL<br># from the official repository, verifying authenticity with GPG keys<br>wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -<br>sudo sh -c &#39;echo &quot;deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main&quot; &gt; /etc/apt/sources.list.d/pgdg.list&#39;<br>sudo apt-get update</pre><pre># Install PostgreSQL and review the version<br>sudo apt-get install postgresql-16 -y<br>sudo -u postgres psql -c &quot;SELECT version();&quot;</pre><h3>2. Don’t Use the Superuser in Your App</h3><p>By default, I was using the main PostgreSQL user for everything. <strong>Big mistake.</strong></p><p>Configure two different users:</p><ul><li>An <strong>application user</strong> with limited permissions (only SELECT, INSERT, UPDATE on needed tables)</li><li>An <strong>admin user</strong> (me) for maintenance and migrations only</li></ul><p>This limits what can go wrong if the app or server is compromised.</p><pre># Switch to the postgres user<br>sudo -i -u postgres</pre><pre># Switch to the postgres user<br>sudo -i -u postgres<br><br># Create the database<br>createdb database_name<br><br># Connect to the database with the postgres user<br>psql</pre><pre>-- Create a user and set permission to connect<br>CREATE USER database_user WITH PASSWORD &#39;secure_password&#39;;<br>GRANT CONNECT ON DATABASE database_name TO database_user;<br><br>-- Create a user for database administration  <br>CREATE USER user_admin WITH PASSWORD &#39;secure_password&#39;;<br>GRANT CONNECT ON DATABASE database_name TO user_admin;<br>-- Configure permissions for the admin user<br>-- Make sure to connect as the owner of the database<br>GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO user_admin;<br>-- Ensure new tables also inherit permissions<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public<br>GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO user_admin;<br>\q</pre><h3>3. Configure pg_hba.conf Properly</h3><p>PostgreSQL controls connection access with a file called pg_hba.conf.</p><p>I updated it to:</p><ul><li>Allow only connections from my app server’s IP</li><li>Block everything else by default</li></ul><p>No more “open to the world” database.</p><pre># Open postgresql.conf (check your PostgreSQL version)<br>sudo vi /etc/postgresql/16/main/postgresql.conf</pre><p>In the file postgresql.conf:</p><pre>listen_addresses = &#39;*&#39;          # what IP address(es) to listen on<br># Alternative: listen_addresses = &#39;localhost,your_app_server_ip&#39;</pre><p>Edit the pg_hba.conf file (PostgreSQL Host-Based Authentication):</p><pre># Open pg_hba.conf (check your PostgreSQL version)<br>sudo vi /etc/postgresql/16/main/pg_hba.conf</pre><p>In the pg_hba.conf file:</p><pre># TYPE    DATABASE         USER        ADDRESS             METHOD<br>host      database_name    user_admin  YOUR_PC_IP/32       md5<br>host      database_name    user_app    APP_SERVER_IP/32    md5</pre><h3>Columns explained:</h3><p><strong>1. TYPE (Connection type):</strong></p><ul><li>local → Local connections (same server)</li><li>host → TCP/IP connections</li><li>hostssl → SSL/TLS connections only</li><li>hostnossl → Non-SSL connections only</li></ul><p><strong>2. DATABASE:</strong></p><ul><li>all → All databases</li><li>database_name → Specific database</li><li>sameuser → DB with same name as user</li></ul><p><strong>3. USER:</strong></p><ul><li>all → All users</li><li>username → Specific user</li><li>@file → List of users from file</li></ul><p><strong>4. ADDRESS:</strong></p><ul><li>127.0.0.1/32 → Localhost only</li><li>192.168.1.0/24 → Specific local network</li><li>0.0.0.0/0 → Any IP (DANGEROUS!)</li><li>No value → Local connections only</li></ul><p><strong>5. METHOD (Authentication method):</strong></p><ul><li>trust → No password (DANGEROUS!)</li><li>md5 → MD5 encrypted password</li><li>scram-sha-256 → Most secure method (recommended)</li><li>peer → System user = PostgreSQL user</li><li>reject → Reject connection</li></ul><p>After making changes, restart PostgreSQL:</p><pre># Restart the service<br>sudo systemctl restart postgresql</pre><h3>4. Backups (and Testing Them)</h3><p>I used pg_dump to create backups:</p><pre># Create the backup<br>pg_dump -U my_user database_name &gt; backup.sql</pre><p>But more importantly: <strong>I tested restoring them.</strong></p><pre># Test restore (on a test database)<br>createdb test_restore<br>psql -U my_user test_restore &lt; backup.sql</pre><p>A backup is useless if you’ve never tried a restore.</p><h3>5. Why This Matters</h3><p>I know what you’re thinking: <em>“But I use Supabase/Firebase/PostgreSQL-as-a-service.”</em></p><p>Still, understanding how to protect your data is valuable. Even if you won’t manage your own DB forever, the concepts stay with you.</p><p>Here are the simplified steps that may be useful for quick application in your projects <a href="https://github.com/bautistaj/notes/blob/master/BD/PSQL/PostgreSQL_Security_Cheat_Sheet.md">Psql Security Cheat Sheet</a>.</p><h3>Final Thoughts</h3><p>Again, I’m no expert. I’m just sharing the step-by-step process I followed in my personal projects.</p><p>This setup helped me feel more confident that:</p><ul><li>✅ My app isn’t using root access for everything</li><li>✅ My data won’t vanish without a trace</li><li>✅ I’m building habits that scale</li></ul><p><strong>What’s your experience with PostgreSQL security? Have you made similar mistakes? Let me know in the comments!</strong></p><p><em>Follow me for more beginner-friendly posts about databases, development, and the lessons learned from my mistakes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d54e7054bd" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/security-on-your-postgresql-setup-the-basics-i-learned-c3d54e7054bd">Security on Your PostgreSQL Setup: The Basics I Learned</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security on your Linux (Ubuntu) Server]]></title>
            <link>https://javascript.plainenglish.io/security-on-your-linux-ubuntu-server-8d7b5695a729?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7b5695a729</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[linux-server-security]]></category>
            <category><![CDATA[server-security]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 22:38:02 GMT</pubDate>
            <atom:updated>2025-09-09T17:30:06.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*O5eoWD9llkElftnfuuBuKw.png" /><figcaption>Ubuntu server security.</figcaption></figure><h3>First steps to protect your Linux server</h3><p>Every minute, your server faces hundreds of automated attacks.<br>When I had to recover a compromised VPS, I learned that the first line of defense is the operating system itself.</p><p>Here are the <strong>basic steps I implemented</strong>:</p><blockquote><em>📝 </em><strong><em>Learning Note:</em></strong><em> I’m documenting my journey as I learn server security.<br> These are fundamental steps that worked in my case, but security is layered — there’s always more to learn.<br> Experienced sysadmins, please share your additional recommendations!</em></blockquote><h3>🚫 Don’t use root for everything</h3><p><strong>The Problem:</strong> Using root for daily tasks is like driving with no seatbelt — one mistake can be catastrophic.</p><p><strong>The Solution:</strong></p><pre># Create an administrative user<br>sudo adduser admin</pre><pre># Give them sudo permissions<br>sudo usermod -aG sudo admin<br><br># Switch to the new user<br>su - admin</pre><p><strong>Why this matters:</strong> This prevents an accidental error from deleting or compromising everything.<br> Even if someone gains access to your regular user, they still need sudo privileges for critical changes.</p><h3>Secure access via SSH</h3><p><strong>The Problem:</strong> Password authentication is vulnerable to brute force attacks.</p><p><strong>The Solution:</strong> Disable password authentication and configure <strong>SSH key authentication</strong>.</p><h4>1. Edit SSH configuration</h4><pre>#Open file<br>sudo nano /etc/ssh/sshd_config</pre><p>Change these settings:</p><pre># Changes in the file sshd_config<br>PermitRootLogin no<br>PasswordAuthentication no<br>PubkeyAuthentication yes</pre><p>Restart SSH:</p><pre># Restar to enable the configuration<br>sudo systemctl restart sshd</pre><h4>2. Generate SSH keys (on your local machine)</h4><pre># Generate ssh keys<br>ssh-keygen -t rsa -b 4096 -C &quot;your@email.com&quot;</pre><h4>3. Copy your public key to the server</h4><p>On your local machine:</p><pre># Copy the public key<br>cat ~/.ssh/id_rsa.pub</pre><p>On your server (logged in as the new user):</p><pre># Switch to the user<br>sudo su - admin<br><br># Crete the directory<br>mkdir -p ~/.ssh<br># -p create parent directories if it not exist<br><br># Change the permissions to the directory<br>chmod 700 ~/.ssh<br># 700 = permissions only for the owner<br><br># 7 = rwx (read, write, execute) to the Owner<br># 0 = --- (withouth permissions) for the group<br># 0 = --- (withouth permissions) fot others<br><br># Add the pub key to the authorized key of your vps<br>echo &quot;your_public_key_here&quot; &gt;&gt; ~/.ssh/authorized_keys<br><br># Chane the permissions<br>chmod 600 ~/.ssh/authorized_keys<br><br># 600 = permissions only for the owner<br><br># 6 = rw- (read, write) to the Owner<br># 0 = --- (withouth permissions) for the group<br># 0 = --- (withouth permissions) fot others</pre><h4>4. Test the connection</h4><p>Open another terminal:</p><pre># Test you configuration<br>ssh admin@your_vps_ip</pre><blockquote><em>⚠️ </em><strong><em>CRITICAL WARNING:</em></strong><em> Always test SSH key access in a separate terminal </em>before disabling password authentication<em>. Keep a backup session open!</em></blockquote><h3>Install Fail2Ban</h3><p><strong>The Problem:</strong> Automated bots constantly try to brute force your server.</p><p><a href="https://github.com/fail2ban/fail2ban"><strong>Fail2Ban</strong></a><strong> </strong>is a powerfull tool that read the system logs <em>/var/log/auth.log </em>and and bans IP addresses that trayed to access to the server with a wrong passwword and updating system firewall rules to reject new connections from those IP addresses.</p><p><strong>The Solution:</strong> Install and configure <strong>Fail2Ban</strong>.</p><pre>sudo apt update<br>sudo apt install fail2ban<br>sudo systemctl start fail2ban<br>sudo systemctl enable fail2ban</pre><p>Check status:</p><pre># Check status of fail2ban<br>sudo fail2ban-client status sshd</pre><p><strong>What it does:</strong> If someone tries to log in multiple times with incorrect passwords, their IP is automatically blocked for a specified time.</p><p>Verify it’s working:</p><pre># Check blocked IPs<br>sudo fail2ban-client status sshd</pre><pre># View failed login attempts<br>sudo grep &quot;Failed password&quot; /var/log/auth.log</pre><h3>Configure Firewall (UFW)</h3><p><strong>The Problem:</strong> By default, many ports are open and accessible from the internet.</p><p><strong>The Solution:</strong> Use <a href="https://help.ubuntu.com/community/UFW"><strong>UFW</strong></a><strong> (Uncomplicated Firewall)</strong> to block everything by default and only allow what you need.</p><pre># Set default policies<br>sudo ufw default deny incoming<br>sudo ufw default allow outgoing<br><br># Allow SSH (CRITICAL: do this first!)<br>sudo ufw allow 22<br># The most important rule, becasue is the ssh port that we user to connet<br><br># Allow other services as needed<br>sudo ufw allow 80    # HTTP<br>sudo ufw allow 443   # HTTPS<br>sudo ufw allow 5432  # PostgreSQL (if needed)<br># You can add more ports, onmy tha port you need<br><br># Enable the firewall<br>sudo ufw enable<br><br># Check status<br>sudo ufw status verbose</pre><p><strong>Strategy:</strong> This is the <strong>principle of least privilege</strong> — block everything by default, only allow what you need.</p><h3>Verify everything is working</h3><p>After implementing these changes, verify your setup:</p><pre># Check active connections (modern alternative to netstat)<br>ss -tuln<br><br># Review authentication logs<br>sudo tail -f /var/log/auth.log<br><br># Verify UFW rules<br>sudo ufw status numbered<br><br># Test SSH key authentication from your local machine<br>ssh admin@your-server-ip</pre><h3>Benefits achieved</h3><ul><li>Prevented unauthorized access through <strong>strong authentication</strong></li><li>Stopped brute force attacks with <a href="https://github.com/fail2ban/fail2ban"><strong>Fail2Ban</strong></a></li><li>Minimized attack surface with <strong>firewall rules </strong><a href="https://help.ubuntu.com/community/UFW"><strong>UFW</strong></a></li><li>Reduced privilege escalation risks by <strong>avoiding root usage</strong></li></ul><h3>Risks avoided</h3><ul><li>Automated bots breaking weak passwords</li><li>Accidental system damage from root access</li><li>Unauthorized services exposure</li><li>Privilege escalation attacks</li></ul><h3>Quick Checklist</h3><ul><li>Create non-root sudo user</li><li>Configure SSH keys and disable passwords</li><li>Install and configure Fail2Ban</li><li>Configure UFW firewall</li><li>Verify logs and connections</li></ul><p>Here are the simplified steps that may be useful for quick application in your projects <a href="https://github.com/bautistaj/notes/blob/master/SERVER/SECURITY_SERVER/cheat_sheet.md">Linux Server Security Cheat Sheet</a>.</p><h3>What’s next?</h3><p>This is just the foundation. In the next article, I’ll cover <strong>PostgreSQL security configuration</strong> — because databases need protection too.</p><p><strong>Next in this series:</strong></p><ul><li>PostgreSQL security and user management</li><li>Container security with Docker and Trivy</li><li>HTTPS configuration with Certbot</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7b5695a729" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/security-on-your-linux-ubuntu-server-8d7b5695a729">Security on your Linux (Ubuntu) Server</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learned from recovering a server at risk: beyond AI and automation]]></title>
            <link>https://javascript.plainenglish.io/what-i-learned-from-recovering-a-server-at-risk-beyond-ai-and-automation-3adb75eca96c?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/3adb75eca96c</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[information-technology]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 18:52:54 GMT</pubDate>
            <atom:updated>2025-09-10T16:45:28.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*YzgfuAEm-smGBWtbN4DOfw.png" /><figcaption>Security</figcaption></figure><p>These days, it’s easy to rely on automation and artificial intelligence to manage servers. Many guides tell you, “run this script and you’re good to go,” without explaining what’s happening behind the scenes. But when your server gets compromised or fails, what do you do if you don’t truly understand how it works?</p><p>That’s what happened to me: I had to face a cloud server that was at risk. And instead of solving it with a quick fix, I decided to do something different: I’d learn, investigate, execute, and document every single step.</p><p><strong>Disclaimer:</strong> I am a beginner in this subject, so I may be wrong on some points. My goal is to document my learning process and receive feedback from the community. If you’re an experienced sysadmin or DevOps engineer reading this, I’d love to hear your thoughts on my approach and any best practices I might have missed.</p><h3>🚨 The Problem</h3><p>One day, I received an email from my provider of VPS service. Services were failing, there were strange processes running, and pending updates were blocking the system. In short: the server was vulnerable and at risk.</p><p>At that moment, I had two options:</p><ol><li>Look for a quick fix with an automated script or a “copy and paste” guide.</li><li>Stop, understand what was happening, and solve it step by step.</li></ol><p>I chose the second option.</p><h3>🛠️ The Path of Learning by Doing</h3><p>In this process, I learned much more than simple commands. I learned how to:</p><ul><li>Safely update a server.</li><li>Correctly install and configure PostgreSQL.</li><li>Create users with different permission levels to protect data.</li><li>Implement and validate backups.</li><li>Set up basic security: administrative users, SSH keys, Fail2Ban, and a firewall.</li><li>Install Docker and scan containers with Trivy to detect vulnerabilities.</li></ul><p>Each step was a challenge, but also an opportunity to understand how applications are truly protected in the cloud. Obviously it is only the basic, but is a good way to start to learn.</p><h3>🔑 My Main Takeaway</h3><p>Automation and AI are powerful tools, and oviusly I used then to solve my problem, but if we depend on them without understanding the underlying mechanisms, we’re one click away from a serious problem.</p><p>Recovering this server reminded me that practical knowledge is a safety net in the cloud. And while it requires more effort, it also gives you something no script ever will: judgment and control.</p><p><em>As someone still learning, I’m sure there are more efficient or secure ways to handle some of these tasks, and I welcome any corrections or suggestions from more experienced practitioners.</em></p><h3>🚀 What’s Next</h3><p>This is the first post in a series where I’ll share what I learned <em>(and hopefully get feedback on what I could improve)</em>:</p><ul><li><a href="https://bautistaj20.medium.com/security-on-your-linux-ubuntu-server-8d7b5695a729">Securing your server (users, SSH, Fail2Ban, firewall)</a>.</li><li>Managing PostgreSQL databases (users, permissions, backups).</li><li>Network and container security (Docker, Trivy, port review).</li><li>How to apply HTTPS on your server with certbot</li><li>Conclusion: the value of learning by doing.</li></ul><p><em>Note: I’m documenting my learning journey as it happens, so if you spot any mistakes or have suggestions for better approaches, please don’t hesitate to share them in the comments. Learning from the community is just as valuable as learning by doing.</em></p><p>I hope this journey serves someone who, like me, like to understand the process that execute using AI.</p><p>👉 Interested in following the series? Give a 👏🏽 or share your experience with servers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3adb75eca96c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/what-i-learned-from-recovering-a-server-at-risk-beyond-ai-and-automation-3adb75eca96c">What I learned from recovering a server at risk: beyond AI and automation</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Steps to create and publish a library in NPM]]></title>
            <link>https://javascript.plainenglish.io/steps-to-create-and-publish-a-library-in-npm-8b1ffc46994d?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b1ffc46994d</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[npm-libraries]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm-publish]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 02:04:21 GMT</pubDate>
            <atom:updated>2025-09-04T00:03:07.095Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create a library with js and publish in npm.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*5Ct3rmYgsSvZJIsPnsVsZA.png" /><figcaption>Steps to create and publish a library in NPM [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><h3>Introduction</h3><p>Some days ago in my job, we needed to create documentation of all the APIS, we had a little problem cause we only had the postman collection and the requirement was to create a README.md file with all info on the endpoints of each project.</p><p>For this reason, I decided to learn how the developers publish libraries in <a href="https://www.npmjs.com/">NPM</a>, so I investigated a little bit and create my own library to convert collection.json file created by Postma to a file to markdown syntaxis.</p><p>So, this publication is only to have the documentation of the steps to create a library and the process to publish it, cause some days ago I decided to maintain my library and I didn’t remember the steps haha if I forget the process I can review this publication.</p><h4>Prerequisites</h4><ul><li><a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">node: v14.19.1</a></li><li><a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">npm: 8.14.0</a></li><li><a href="https://www.npmjs.com/">npm</a> account</li><li><a href="https://github.com/">GitHub</a> account</li></ul><h4>What does NPM?</h4><p><strong>N</strong>ode <strong>P</strong>ackage <strong>M</strong>anager is the default package manager for the JavaScript runtime environment Node.js, it consists of a CLI Command Line Interface called npm, and an online database of public and paid-for private packages called the npm registry.</p><h4>Creating the library</h4><p>Is time to create a repository in <a href="https://github.com/">GitHub</a>, once you have the repository clone it in your local environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQBtck1usvmAtl0DiXfPrw.png" /><figcaption>Create a repository on GitHub [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*RXjt34C8FuOm5aRnSEYsAA.png" /><figcaption>Clone you repository[<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><pre>git clone git@github.com:bautistaj/postman-to-markdown.git</pre><p>Onece you have your repository, change the directory to your project and initialize your project with npm.</p><pre>npm init -y </pre><p>The last command allows us to create the initial project with npm, the -y flag is used to create a default configuration as shown in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mGAP6RlLx_czvBLsVgMYA.png" /><figcaption>package.json file [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>Now, we can create our source code for the library in the src directory.</p><pre>mkdir src<br>cd src <br>touch index.js</pre><p>For the practical case, I’ll only type in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*HV8Lz1NLqqoM22IvoRMCVA.png" /><figcaption>Source code of our library [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>The last code just creates an arrow function and exports it to use it in other files.</p><p>The library needs a way to access to source code, so I’ll create a new directory called <strong>bin</strong>, this directory will contain the executable of our library.</p><pre>mkdir bin<br>cd bin<br>touch global.js</pre><p>In the global file, we going to export the source file and the function to execute it as shoe the next file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*Kbggd-hzeNv4RbwmF-vW3Q.png" /><figcaption>The executable file of our library [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>To configure our executable file, I’m going to modify the package.json as follows.</p><pre>&quot;bin&quot;: {<br>  &quot;postman-to-markdown&quot;: &quot;./bin/globlal.js&quot;<br>},<br>&quot;preferGlobal&quot;: true<br></pre><p>The last code configures the executable file of our library and put it as a global.</p><p>We finished the configuration, no is time to test it, for this purpose we can use the next command.</p><pre>npm link</pre><p>The last command allows us to install the library locally without the need to publish it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*P_PnaPllpghvTj0umWbasA.png" /><figcaption>Publis in local env [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>Once the last command finished, we can execute the library and print the log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*7X58LYPBR-Tivwdns4zP2g.png" /><figcaption>Testing the library [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>Our library is working very well, so the next step is to publish it in <a href="https://docs.npmjs.com/">NPM</a>.</p><h4>Publish the library</h4><p>As I commented in the Prerequisites section we need an account in <a href="https://www.npmjs.com/signup">NPM</a>, once you have the account, add your user with the next command.</p><pre>npm adduser</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*_C5mEq1JVtBFJ8jFVdbOHw.png" /><figcaption>npm adduser [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>Now that you have your account linked, it’s time to publish your bookstore.</p><pre>npm publish</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*MbuNbRIVD3FHkwbAKjOWwQ.png" /><figcaption>Publish the library [<a href="https://github.com/bautistaj">bautistaj</a>]</figcaption></figure><p>Now we can see our library in NPM, <a href="https://www.npmjs.com/package/postman-to-markdown">postman-to-markdown</a>, let me share the GitHub repository in case you want to collaborate <a href="https://github.com/bautistaj/postman-to-markdown">https://github.com/bautistaj/postman-to-markdown</a>.</p><h4>Recommendations</h4><p>Before I finish, I would like to say two recommendations, first read about software licenses, it is very important because the lawful use of software not only provides guarantees to the user but also increases the opportunities for competitiveness, productivity, and improvement of the industry, to the benefit of the user, here you can read about <a href="https://www.synopsys.com/blogs/software-security/5-types-of-software-licenses-you-need-to-understand/">Five types of software licenses you need to understand</a>; The second one is about how to handle the versions of your libraries, here is this publication where you can learn about <a href="https://semver.org/">Semantic Versioning 2.0.0</a>.</p><h4>Conclusion</h4><p>Let’s look at what we have learned.</p><ul><li>How we can create a little library using npm</li><li>The way to publish a library in <a href="https://www.npmjs.com/">npm</a></li></ul><p>Thanks for reading.</p><p>Kindest Regards.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1ffc46994d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/steps-to-create-and-publish-a-library-in-npm-8b1ffc46994d">Steps to create and publish a library in NPM</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Rest API with Express, PostgreSQL, TypeOrm, and TypeScript]]></title>
            <link>https://javascript.plainenglish.io/create-a-rest-api-with-express-postgresql-typeorm-and-typescript-ac42a20b66c7?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac42a20b66c7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Sat, 13 Mar 2021 02:31:33 GMT</pubDate>
            <atom:updated>2021-03-14T23:24:06.621Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create a simple Rest API using Express framework, PostgreSQL, and coding with TypeScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*xaVOIVhbI8ol8PK1vy1yrg.png" /><figcaption>Create a Rest API with Express, PostgreSQL, TypeOrm, and TypeScript.</figcaption></figure><h3>Prerequisites</h3><p>Please make sure that <a href="https://nodejs.org/">Node.js</a> (&gt;= 10.13.0) is installed on your operating system and <a href="https://www.docker.com/get-started">docker</a>.</p><h3>Init project</h3><p>We need to create our project, firstly create blog directory.</p><pre>mkdir blog</pre><p>Later, go to blog directory and init the project.</p><pre>cd blog</pre><pre>npm init</pre><p>The last command going to create a <strong>package.json</strong> file, its purpose is to handle the history of all dependencies installed in our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*vsjO6BQm9aSdiot1_YPgQA.png" /><figcaption>package.json</figcaption></figure><h3>Install dependencies</h3><p>To our API Rest, we need the next dependencies, express, pg, TypeOrm, typescript.</p><p>Install dependencies dev dependencies.</p><pre>npm install typescript @types/express @types/node --save-dev</pre><p>We will only use the last dependencies to develop our API.</p><p>Now, install the dependencies that we’ll use in the production environment.</p><pre>npm install express pg typeorm</pre><p><a href="https://www.npmjs.com/package/express"><strong>express</strong></a>: This is a web application framework for NodeJS.</p><p><a href="https://www.npmjs.com/package/pg"><strong>pg</strong></a>:<strong> </strong>It is a collection of NodeJS modules for interfacing with your PostgreSQL database.</p><p><a href="https://www.npmjs.com/package/typescript"><strong>Typescript</strong></a>: It’s a language for application-scale JavaScript, this module helps us to add optional types to JavaScript that support tools for large-scale JavaScript applications for any browser.</p><p><a href="https://www.npmjs.com/package/typeorm"><strong>typeorm</strong></a>: It’s an ORM that runs in Node JS that can use with TypeScript and JavaScript (ES5, ES6, ES7, ES8).</p><p><strong>@types/express, @types/node</strong>: these packages help us with the type definitions for Express and NodeJS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*HIfxDAszTOA1Ot-y4AUe1Q.png" /><figcaption>packahe.json file with our dependencies.</figcaption></figure><h3>Configuring TypeScript</h3><p>First, we need to add a command into the <strong>package.json</strong> file to execute commands of the <strong>typescript</strong> module. In the section of scripts add the next line.</p><pre>“tsc”: “tsc “</pre><p>Now, we going to configure TypeScript in our project, execute the command below:</p><pre>npm run tsc -- --init</pre><p>The last command generates <strong>tsctsconfig.json</strong>, this file indicates that we are going to working with TypeScript. This file contains the working setup for TypeScript transpillation.</p><p>In the file, we add the next lines, those lines help us with the configuration of the build and root directories.</p><pre>“outDir”: “./build”, <br>“rootDirs”: [“./src”],</pre><p><strong>rootDirs</strong>: This configuration list who combined represent the project.</p><p><strong>outDir</strong>: This line redirects the output of compiled files.</p><h3>Configuring our server</h3><p>We going to create the <strong>src</strong> directory and <strong>server.ts</strong> file.</p><pre>mkdir src<br>cd src<br>touch server.ts </pre><p>Once created our sever.ts file we going to create a class called Server and the constructor, configuration, routes, and start method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*58gI-JI-JO2c63L7sAq8Sg.png" /><figcaption>Basic server configuration.</figcaption></figure><p>Once created the class and methods execute the command below to convert our TypeScript code to JavaScript.</p><pre>npm run tsc</pre><p>Remember the <strong>tsctsconfig.json </strong>configurations, the JavaScript files will generate into the build directory.</p><p>Now, start the server with the next command.</p><pre>node ./build/server.js</pre><p>After that. try to go to the next link <a href="http://localhost:3000/">http://localhost:3000/</a>.</p><h4>Create controllers</h4><p>In this example of API, we going to use controllers to handle the routes, we need to create the controller directory and the post.controller.ts file.</p><p>In this controller, we going to handle the methods to the CRUD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*vhCxLW1Hjff05M6QD8roZg.png" /><figcaption>Example of controller file.</figcaption></figure><p>Now into our class server, we need to import the controller and configure new routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*w_rV5aycQeoxrVJKBQP7BQ.png" /><figcaption>Server with the post controller configuration.</figcaption></figure><p>Next, execute the command below:</p><pre>npm run tsc<br>node ./build/server.js</pre><p>And try to access the new routes of the post controller. <a href="http://localhost:3001/api/posts">http://localhost:3001/api/posts</a></p><p>If you want to prove all the methods of post controller use <a href="https://www.postman.com/">postman</a>.</p><h4>Create services</h4><p>In some cases, we need to get data from different places thus database or another API, for this reason, we need to handle this operation in an exclusive file. In this practice, we’ll use services to handle these tasks.</p><p>Create a new directory called services and the file post.service.ts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*t7niz3HmkR1gOe3Um3fhWA.png" /><figcaption>Example of post-service file.</figcaption></figure><p>Import the new service into the controller file and execute each method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*eu1n-8bCgls6XlM0cxNqVg.png" /><figcaption>Now, in the controller, we execute the method from service.</figcaption></figure><p>Now execute commands to transpillate our code and start the server.</p><pre>npm run tsc<br>node ./build/server.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*4IBQqwtUxgu8SsrBjG1UYQ.png" /><figcaption>Now you get the message from the post-service.</figcaption></figure><p>In the next section, we’ll configure the database and execute some queries.</p><h3>Create the database</h3><p>For this practice, we going to use Docker containers, you can get some information about how to install docker in <a href="https://docs.docker.com/get-docker/">the documentation</a>.</p><p>Once Docker installed, run the next command:</p><pre>docker run -d -p 5433:5432 — name blog -e POSTGRES_USER=blog -e POSTGRES_PASSWORD=blog — mount src=db-blog,dst=/var/lib/postgresql/data postgres</pre><p>The flag -d indicates that the container going to execute in detach mode in the background.</p><p>The flag -p 5433:5432 specifies that the container will configure the port 5432 and we can access it with the 5444 from localhost.</p><p>— name <strong>blog</strong> specify the name of our container.</p><p>In the line -e POSTGRES_PASSWORD=password we specified an environment variable POSTGRES_PASSWORD.</p><p>You can validate if the container was launched correctly using <a href="https://www.pgadmin.org/">PgAdmin</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*-2CSBgkxK5KZH6XXfAjpKg.png" /><figcaption>Start session in our database.</figcaption></figure><h3>Configure the database connection</h3><p>In this section, we going to configure the database connection with our API using <a href="https://typeorm.io/#/">typeorm</a>.</p><h4>Create the connection</h4><p>In the server file, we import createConnection function from TypeOrm, in this section we use async functions, so if you want to learn more about this topic visit the <a href="https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Statements/async_function">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*4J8tg2wpl2d4CCKZqI4pFQ.png" /><figcaption>Database configuration.</figcaption></figure><p>The last picture shows how to create a new connection, It needs the type of database, port, host, username, password, database name. The method <strong>createConnection</strong> was imported from the TypeOrm module.</p><p>Our method database Configuration going to execute into routes method and wait until the connection finished. It’s important the connection before starting with routes configuration.</p><p>If you want to know more about the different ways to create a connection visit <a href="https://typeorm.io/#/connection">typeorm’s documentation.</a></p><h4>Create entities</h4><p>Well, we have the database connection, so the next step is to configure the entities of our application. According to TypeOrm’s documentation, an entity is a class that maps to a database table, you can define an entity using the annotation @Entity().</p><p>If you remember, in the configuration of the database we have these line entities<strong>: [“build/database/entities/**/*.js”]</strong>, so we need to create the directory <strong>src/database/entities</strong>,<strong> </strong>and this directory will contain our entities.</p><p>Create a class called PostEntity and in this class, we define our table posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*IYyx_FtB4AapSYTyCIkt8Q.png" /><figcaption>Post entity example.</figcaption></figure><p>@PrimaryGeneratedColumn() generate a primary column which value will be automatically generated and @Column() define a column of our database.</p><h4>Create custom repository</h4><p>All the actions that we need to do, we’ll do in the repository file, in this file we connect to a specific table and execute some actions such as update, create, delete, and other DML operations.</p><p>Create the <strong>src/repository</strong> directory and a file called post.repository.ts and create the class PostRepository like class bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*bzRLHd_XKF-0rnw4ZMfvKQ.png" /><figcaption>Example of a repository with TypeOrm.</figcaption></figure><p>The class PostRepository extends from the Repository class, this class lets us work with our entity objects. Find entities, insert, update, delete, etc, and @EntityRepository() is used to declare a class as a custom repository.</p><h3>Integrate services with the repositories</h3><p>Now we have all necessary to finish our API, we have the controllers, services, and repositories, in this section we integrate all the components.</p><p>First, we’ll import PostRepository into the class PostService, and initialize the repository with some commands from TypeOrm module. The methods that we’ll use are getConnection() this method helps us to get a specific connection, for example, our connection was called <strong>blog</strong> and getCustomRepository() get the custom repository for example <strong>PostRepository</strong>, once initialized the service we can execute some methods, for example, find(), this method retrieves all registers into the table posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*8xcFtoqxtKrRNSxeSmtDCA.png" /><figcaption>Implementation of PostRepository.</figcaption></figure><p>Now transpillate the code and start the server.</p><pre>npm run tsc<br>node ./build/server.js</pre><p>Insert some data into posts table and you can access to the next url <a href="http://localhost:3001/api/posts">http://localhost:3000/api/posts</a> and get data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qp9F2kzsLyN7H3R-BpowPg.png" /><figcaption>Get data from database with our API.</figcaption></figure><p>Now, we implemetn the create, update and delete methods, Its necesary to update the controller and the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*xH-8fhON-iybPGONaHzuPA.png" /><figcaption>Post Controller.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*vx6ENC-lyugi7bDg14Z-7w.png" /><figcaption>Post-service.</figcaption></figure><p>Now you can compile the code test the API, with Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*HmI1FIhCMI5zalasUnY4Yg.png" /><figcaption>Get all posts.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*oxcOCo5V33nam_zfJDphIg.png" /><figcaption>Creta a post.</figcaption></figure><p>With this, we finish the practice, but you can see the complete code on <a href="https://github.com/bautistaj/expressApi">GitHub</a>.</p><h3>Conclusion</h3><p>Let’s look at what we have learned.</p><ul><li>How to create a single Rest API with express.</li><li>Configuration of typescript.</li><li>Configuration of Typeform.</li><li>How to configure controllers, services, and repositories.</li><li>How to configure PostgreSQL Docker container.</li></ul><p>First of all, thanks for reading and I hope this little tutorial will help you.</p><p>Kindest Regards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac42a20b66c7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/create-a-rest-api-with-express-postgresql-typeorm-and-typescript-ac42a20b66c7">Create a Rest API with Express, PostgreSQL, TypeOrm, and TypeScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a NestJS application in Heroku with GitLab CI/CD pipelines]]></title>
            <link>https://javascript.plainenglish.io/deploy-a-nestjs-application-in-heroku-with-gitlab-ci-cd-pipelines-9773e6a8eb71?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/9773e6a8eb71</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 20:33:08 GMT</pubDate>
            <atom:updated>2021-03-15T07:43:54.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to deploy a NestJS Application in Heroku using GitLab CI/CD pipelines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*gz01gxIuodn9EErMqYrsDg.png" /></figure><h3>Introduction</h3><p>In previous days I wrote a little tutorial explaining how to create a NestJS application <a href="https://medium.com/swlh/create-an-api-rest-with-nestjs-1954723e8234">Create an API Rest With NestJS and PostgreSQL</a> and now I will explain how to deploy it using GitLab Pipelines.</p><h3>Prerequisites</h3><p>We need to create an account in <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">Heroku</a> and <a href="https://about.gitlab.com/">GitLab</a>.</p><p>Please make sure that <a href="https://nodejs.org/">Node.js</a> (&gt;= 10.13.0) is installed on your operating system.</p><h3>Installation</h3><h4>NestJS</h4><p>Once installed NodeJS we doing to install <a href="https://docs.nestjs.com/cli/overview">NestJS CLI</a>, Command Line Interface that help us to maintain our application.</p><p>Once installed, we going to execute the next command to create our project.</p><pre>$ nest new project-name</pre><p>You can find the core files in the src directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*J0haSvrd0Dlrb-D5o4ucJQ.png" /><figcaption>Core files</figcaption></figure><ul><li>app.controller.ts: A basic controller with a simple route.</li><li>app.service.ts: A simple service.</li><li>app.module.ts: The root module of the application.</li><li>main.ts: The entry file of the application which uses the core function NestFactory to create a Nest application instance.</li></ul><p>To start the application type the next commands.</p><pre>$ cd project-name</pre><pre>$ npm run start</pre><p>Now you can open your browser and navigate to <a href="http://localhost:3000/">http://localhost:3000</a>.</p><p>We will create a service to manage the configuration of each environment and read the environment variables of <a href="https://nodejs.org/dist/latest-v8.x/docs/api/process.html"><strong>process.env</strong></a><strong>, </strong>in our case we only need the port.</p><pre>$ nest g service configuration/configuration</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*reJaJlSTAriBJuWvQ1FQ8g.png" /><figcaption>Configuration service.</figcaption></figure><p>Now create an instance of the service in AppModule class and add a new static attribute called port, in the constructor initialize this attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*lCp_a_F-vxMOEXuq8Xf2PA.png" /><figcaption>AppModule.</figcaption></figure><p>In the main.ts file add the port configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*6CtJYBUbFPLOcvB8FAGXug.png" /><figcaption>main.ts file</figcaption></figure><p>These are all setting that we need to deploy our application.</p><h4>Heroku</h4><p>Is time to install Heroku, you can find how to install it <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">https://devcenter.heroku.com/articles/heroku-cli#download-and-install</a>.</p><p>Once installed login into your account.</p><pre>$ heroku login</pre><pre>$ heroku create application-name</pre><p>Now we need to configure an environment variable called <strong>NPM_CONFIG_PRODUCTION</strong> into false, it’s because our pipeline needs to generate the build of our project before to start the server, and <strong>PORT </strong>its the port that the app uses for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaJsg8DjR2MtzESm8b73oA.png" /><figcaption>Environment variable</figcaption></figure><h4>GitLab</h4><p>Is time to create an account in <a href="https://gitlab.com/">GitLab</a>, once the account was created we going to create a new repository.</p><p>Now got to the NestJS project and add the first commit and push the changes in the new repository.</p><pre>$ cd projectname</pre><pre>$ git add -A .</pre><pre>$ git commit -m&quot;First commit&quot;</pre><pre>$ git remote add origin <a href="/service/mailto:git@gitlab.com">git@gitlab.com</a>:groupname/projectname-api.git</pre><pre>$ git push -u origin — all</pre><p>Now go to the Settings / CI/CD / Variables, add <strong>APP</strong> and <strong>HEROKU_API_KEY</strong> variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*VVY_12thOf1cgBQzbHXI7w.png" /><figcaption>Environment variables</figcaption></figure><p>To obtain the API key of Heroku go to Account Settings and bottom you can find the value and <strong>APP </strong>is the application&#39;s name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PS3Ikz6aRDYDFWEp6SGYTg.png" /><figcaption>Heroku API key.</figcaption></figure><p>Now in the project create the .gitlab-ci.yml file, in this file we going to configure our pipelines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faf829357e5fb640e73a9105973e398c/href">https://medium.com/media/faf829357e5fb640e73a9105973e398c/href</a></iframe><p>In our pipeline, we have 4 specifications.</p><ul><li><strong>image</strong>: specifying the version of NodeJS.</li><li><strong>before_script</strong>: Override a set of commands that are executed before the job.</li><li><strong>stages</strong>:<strong> </strong>Defines a job stage.</li><li><strong>staging</strong>:<strong> </strong>It’s our environment to deploy.</li></ul><p>We install <strong>dpl </strong>dependency, dpl is a deploy tool made for continuous deployment that’s and developed and used by Travis CI but can also be used with GitLab CI/CD, you can find more information about it in <a href="https://docs.gitlab.com/ee/ci/examples/deployment/">https://docs.gitlab.com/ee/ci/examples/deployment/</a>.</p><p>In the section of staging, we specify the type of the task “Deploy”, the image that we use, define the job stage and the script that we use to deploy.</p><pre>dpl --provider=heroku --app=$HEROKU_APP_STAGING --api-key=$HEROKU_API_KEY</pre><p>In the script we specify the provider, in our case is Heroku, the name of our app, and the API key.</p><p>Now create the <strong>Procfile</strong> and add the next line:</p><pre>web: npm run start:prod</pre><p>This command starts the project in production mode.</p><p>In the package.json we add new scripts.</p><pre>&quot;postinstall&quot;: &quot;npm run prestart:prod&quot;</pre><pre>&quot;prestart:prod&quot;: &quot;rimraf dist &amp;&amp; npm run build&quot;</pre><p>After the <strong>install</strong> command was finished the next command is <strong>prestart:prod</strong> its because we need to create the build of our project before executing <strong>start:prod</strong>.</p><p>The configurations were finished now we commit all the changes and create a new branch called <strong>staging</strong> and push it to GitLab.</p><p>GitLab will recognize our pipeline and start with the deployment of our app in Heroku.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njsYra4AgUl70OBB7Dg3iw.png" /><figcaption>Deploying app.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQLzZ-AIAPSd6YzCpNIPYg.png" /><figcaption>Log.</figcaption></figure><p>Once the process of deployment finished we could open out the app by clicking the button Open App.</p><p>You could find the project in the <a href="https://gitlab.com/speakchron/speakchron-api">https://gitlab.com/speakchron/speakchron-api</a></p><h3>Conclusion</h3><p>Let’s look at what we have learned.</p><ul><li>How to create a simple application with NestJS CLI.</li><li>Configure environment variables in our application.</li><li>Configure scripts of our project to deploy.</li><li>The configurations of the environment on Heroku and GitLab.</li></ul><p>First of all thanks for reading and I hope this little tutorial will help you.</p><p>Kindest Regards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9773e6a8eb71" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/deploy-a-nestjs-application-in-heroku-with-gitlab-ci-cd-pipelines-9773e6a8eb71">Deploy a NestJS application in Heroku with GitLab CI/CD pipelines</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an API Rest With NestJS]]></title>
            <link>https://medium.com/swlh/create-an-api-rest-with-nestjs-1954723e8234?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/1954723e8234</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 03:33:36 GMT</pubDate>
            <atom:updated>2024-02-06T04:05:48.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create an API Rest With NestJS and PostgreSQL</h3><p>In this tutorial, I will try to explain how to create an API Rest with NestJS framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*b7OvcXde_yQl8j7rXcjskA.png" /><figcaption>NestJS</figcaption></figure><h3>Before start</h3><p>We are going to talk about some topics such as TypeScript, Promises, asyc, await and Docker commands which we will not be going in depth about but we will share information related to them.</p><h3>Introduction</h3><p>NestJS is a framework for building NodeJS server-side applications, it uses progressive JavaScript, is built and support TypeScript but let developers to code in pure JavaScript, but in this case we use TypeScript.</p><p>NestJS combine OOP(Oriented Object Programming), FP(Functional Programing), and FRP(Functional Reactive Programing).</p><p>NestJS makes use of the <a href="https://github.com/expressjs/express">Express</a> library, so every technique for using the MVC (Model-View-Controller) pattern in Express applies to NestJS as well.</p><h3>Prerequisites</h3><p>Please make sure that <a href="https://nodejs.org/">Node.js</a> (&gt;= v18.17.1) is installed on your operating system.</p><h3>Installation</h3><p>To start working with NestJS we need to install <a href="https://docs.nestjs.com/cli/overview">Nest CLI</a>, it’s a command-line interface tool that will help you to maintain your Nest Applications, it assists in different manners, for example, scaffolding the project, serving the apps in development mode, and building the app for production distributions.</p><p>So let&#39;s start to create our project with the next command.</p><pre>$ npm install -g @nestjs/cli</pre><p>To scaffold a project with NestJS CLI, run the following command, the command going to create a new directory with the initial core configuration.</p><pre>$ nest new tours-api</pre><p>We can find core files in the src/ directory.</p><figure><img alt="Initial configuration of Nest JS Application" src="https://cdn-images-1.medium.com/max/590/1*YK9kr1vtxcJSHWHEKlYRpw.png" /><figcaption>Initial configuration of Nest JS Application</figcaption></figure><ul><li>app.controller.ts: A basic controller with a simple route.</li><li>app.service.ts: A simple service.</li><li>app.module.ts: The root module of the application.</li><li>main.ts: The entry file of the application which uses the core function NestFactory to create a Nest application instance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*BYmJxFFRMdFrN9_UDggBwg.png" /><figcaption>Entry file of the application.</figcaption></figure><p>To start the application type the nest commands.</p><pre>$ cd tours-api<br>$ npm run start</pre><p>Now you can open your browser and navigate to <a href="http://localhost:3000/">http://localhost:3000</a>.</p><h3>Controllers</h3><p>The controllers are the most important in Api because they are in charge to handle requests and responses to the client and the routing mechanism controls which controller receives the request.</p><p>For our project we will use a module for each endpoint, it helps us to keep the code relevant to a specific feature organized, so type the following command which will create new directories above the module.</p><pre>$ nest generate module country</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCPavKxNW7b3yX0MSzFdwA.png" /><figcaption>Country module</figcaption></figure><p>The command adds the user module in the main application module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nnz7LgcY6AT9bCSG9Z1z0Q.png" /><figcaption>New module added</figcaption></figure><p>The next step we goingto to create the country controller with the next command:</p><pre>$ nest generate controller /country/country</pre><p>The command will generate a basic controller with the next structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kb42s2h2_k5HKeEdPXMm0g.png" /><figcaption>Basic controller</figcaption></figure><p>NestJS help us modifying the CountryModule adding the new controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3Y5riN_OZrLCH65zwpoNw.png" /><figcaption>CountryController added</figcaption></figure><p>A controller is a simple class with the decorator @Controller(&#39;country&#39;)which is required to define a controller and specifies the prefix <strong>country </strong>it<strong> </strong>allows us to easily group a set of related routes, and minimize repetitive code.</p><p>To handle the different methods NestJS provides us methods: @Get, @Post, @Put(), @Delete(), @Patch() and there is another decorator that handles all of them @All() .</p><p>In the next piece of code, we defined two methods with @Get, @Post decorators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ml53sYYVdq1-c_X14ajkQQ.png" /><figcaption>Basic controller with post and get methods</figcaption></figure><p>Now you can use <a href="https://www.postman.com/">postman</a> and test the methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNnFsVQ2dV9blH5lRV-N9w.png" /><figcaption>Testing get method</figcaption></figure><h3>Service</h3><p>Services are important because it is in charge of data storage and retrieve it, the service is designed to be used by the controller so lets to create a basic service with the next command.</p><pre>$ nest generate service /country/country</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhN6q_QEFrdhc0Ozm81E3w.png" /><figcaption>Country service</figcaption></figure><p>As you can see we have the decorator @Injectable() marks a class as a provider, <a href="https://docs.nestjs.com/providers">providers</a> are a fundamental concept in nest, the main idea of a provider is that it can inject dependencies, this means that objects can create various relationships with each other and these instances be delegated to Nest runtime.</p><p>Providers can be injected into other classes via constructor parameter injection using Nest’s built-in <a href="https://docs.nestjs.com/providers#dependency-injection">Dependency Injection (DI)</a> system.</p><p>The service was configured in UserModule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJB5Lgh-c75KsieP96Nnkg.png" /><figcaption>CountryService configurated</figcaption></figure><p>To keep organized the data entries to our api we are going to use a DTO (Data Transfer Object) and for this we are going to create a class.</p><pre>$ nest generate class /country/dto/country.dto</pre><p>This DTO will help us to receive data in the post method of our api in each request, for this reason we need to add some validations, so we will use the <a href="https://www.npmjs.com/package/class-validator">class-validator</a> libraty.</p><p>With install comman we will add the library in our project.</p><pre>$ npm install class-validator</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8h2e6atKEs6LlUrcysj5g.png" /><figcaption>class-validator configured in package.json file</figcaption></figure><p>Now, for our case, to create a country we need two attributes iso and name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zzm-Ipl4Mt7AdxDy8luucQ.png" /><figcaption>Country DTO</figcaption></figure><p>The @IsNumber() and @IsString() decorators help us to validate the data type of the DTO, you can learn more about <a href="https://github.com/typestack/class-validator#readme">class-validator in the documentation</a>.</p><p>We add two methods in our service, one returns the list of the countries, and the other add a new country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bQlOawPeqAHKr6PE6t8Dg.png" /><figcaption>New mehtods for country service</figcaption></figure><p>As I mentioned we inject user service into CountryController’s constructor and use the service methods to get data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0JajXq8wn1v0whBBcsSYA.png" /><figcaption>UserController injected CountryService</figcaption></figure><p>As you can see we add a new decorator @Body() to handle the body of the request, it extracts the entire body object from the request and populates the decorated parameter with the values of the body.</p><p>Now we can test our API with postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wI1g95Xiav29PEFUt_U_g.png" /><figcaption>Post Method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SGhiNXjWRlBF0r-dwhnNA.png" /><figcaption>Get method</figcaption></figure><p>Now in the next sections, we will configure our database, entities, and repositories to execute some queries.</p><h3>Database configuration</h3><p>NestJS allowing you to easily integrate with any SQL or NoSQL database for this reason is considered agnostic. It is simply a matter of loading an appropriate Node.js driver for the database.</p><p>For convenience Nest provides integration with <a href="https://docs.nestjs.com/recipes/sql-typeorm#sql-typeorm">TypeORM</a>, <a href="https://docs.nestjs.com/recipes/sql-sequelize#sql-sequelize">Sequalize</a>, and <a href="https://docs.nestjs.com/techniques/mongodb">Mongose</a>, those integrations provide us Nest JS features such as model/repository injection and testability.</p><p>In our case we will use TypeORM and PostgreSQL so we need to install the next dependencies.</p><pre>$ npm install --save @nestjs/typeorm typeorm pg</pre><p>For our database we are going to use a <a href="https://docs.docker.com/">Docker</a> container, so for this task we need to <a href="https://www.docker.com/get-started">install Docker</a>, once installed we are going to load a container with PostgreSql with the following command.</p><pre>$ docker run -d -p 5444:5432 --name toursdb -e POSTGRES_USER=toursapi POSTGRES_DB=toursdb POSTGRES_PASSWORD=toursapi postgres</pre><p>The flag -d indicates that the container going to execute in detach mode in the background.</p><p>The flag -p 5444:5432 specifies that the container will configure the port 5432 and we can access it with the 5444 from localhost.</p><p>— name toursdb specify the name of our container.</p><p>-e POSTGRES_PASSWORD, -e POSTGRES_DB and -e POSTGRES_USER we spesify environment variables of our data base.</p><p>Once the dependencies are installed and our container was configure we can import the TypeORM into root module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWe15Y4omQDsoJ27xqjH7Q.png" /><figcaption>Database configuration</figcaption></figure><p>The TypeOrmModule.forRoot() methods supports all the configurations bellow describe. You can learn more about this subject in <a href="https://typeorm.io/#/connection-options">the official documentation</a>.</p><pre>type: &#39;postgres&#39;,<br>host: &#39;localhost&#39;,<br>port: 5444,<br>username: &#39;toursapi&#39;,<br>password: &#39;toursapi&#39;,<br>database: &#39;toursdb&#39;,<br>entities: [&#39;**/entity/*.entity.ts&#39;],<br>synchronize: true,<br>autoLoadEntities: true</pre><p>In this case we used a basic configiuration in the app.module.ts file.</p><h3>Repository pattern</h3><p>Repositories are classes or components that encapsulate the logic required to access data sources, this pattern decoupling the infrastructure or technology used to access databases from the domain model layer.</p><p>NestJS support repository pattern, for this task we need to create entities, n entity is a class that let us map to a database table or collection if you use MongoDB, you can create an entity by defining a new class and mark it with @Entity() decorator.</p><p>Each entity has its own repository that can be obtained from the database connection, to continue the example we create a class and configure a user entity, we create the class into entities directory.</p><pre>$ nest generate class country/entity/country.entity</pre><p>Once created the country class we add new attributes such as uuid, name, and iso.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEZagd8n7Ipo_0BxQcvErA.png" /><figcaption>Conutry entity</figcaption></figure><p>We configured different decorators:</p><p>@Entity(): This decorator is used to mark classes that will be an entity (table or document depend on database type). Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.</p><p>@PrimaryGeneratedColumn(“uuid”): A column decorator is used to marking a specific class property as a table column.</p><p>@Column(): Column decorator is used to marking a specific class property as a table column. Only properties decorated with this decorator will be persisted in the database when the entity be saved.</p><p>You could learn more in <a href="https://typeorm.io/#/entities">TypeORM’s</a> documentation.</p><p>In our database configuration have the synchronize: true value, this configuration let us automatically loaded models will be synchronized, so when we execute the command $ npm run start:dev TypeORM will create the table in our database, don’t used for prod environment.</p><p>And other important configuration that we did is the next:</p><pre>entities: [&#39;**/entity/*.entity.ts&#39;],<br>autoLoadEntities: true</pre><p>The last configuration permit TypeOrm find our entities and load the entities creating the database.</p><p>The next step is to configure the repository to access the database in the service, we are going to modify the service and implement a class Repository which helps us to work with our entity objects. Find entities, insert, update, delete, etc.</p><p>Now we use the instance of the repository to insert data and find the registers.</p><p>We are going to configure forFeature() a method in the CountryModule to define the repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrIQ-Wyus9IWbdQMdQhB2A.png" /><figcaption>CountryEntity configuration</figcaption></figure><p>This module uses the forFeature() method to define which repositories are registered in the current scope. With that in place, we can inject the CountryRepository into the CountryService using the @InjectRepository() decorator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKHsYRoYmxPrrh1W2RVh8Q.png" /><figcaption>Example of service.</figcaption></figure><p>As you can see we modified the types to return the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgT8nbb-jp-oodKntSNKRQ.png" /><figcaption>Conutry Cotroller</figcaption></figure><p>We used the async, await and promises in this part of the code, if you want to know more about these topics review the next post <a href="https://kamilmysliwiec.com/typescript-2-1-introduction-async-await">Introduction to async / await </a>and the <a href="https://kamilmysliwiec.com/typescript-2-1-introduction-async-await">NestJS doumentation</a>.</p><p>It’s time to test our API with Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkImNwYXLWVHg9y9lRjtDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3w7eEU0G5eq9KV1oOoFqZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAzKZXsV56IeGhoOUA4phA.png" /></figure><h3>Conclusion</h3><p>Let’s look at what we have learned.</p><ul><li>How to create an API Rest with NestJS using CLI.</li><li>Some important NestJS decorators.</li><li>How to configure controllers, services, and repositories.</li><li>How to configure the database connection.</li><li>How to configure PostgreSQL Docker container.</li></ul><p>Thanks for reading and I hope this little tutorial will help you.</p><p>Kindest Regards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1954723e8234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/create-an-api-rest-with-nestjs-1954723e8234">Create an API Rest With NestJS</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy an Angular App in Apache Tomcat With Azure DevOps]]></title>
            <link>https://medium.com/swlh/how-to-deploy-an-angular-app-in-apache-tomcat-with-azure-devops-900e67a21122?source=rss-df03dc92eb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/900e67a21122</guid>
            <category><![CDATA[apache-tomcat]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jose Luis Campos Bautista]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 18:59:59 GMT</pubDate>
            <atom:updated>2021-03-12T23:43:11.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploy an Angular App in Tomcat Server using Azure DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*CJ4NNiStrVn5JblRBGWNtw.png" /></figure><h3>Introduction</h3><p>Currently, there are a lot of posts about this topic, but any of those pipeline configurations work for me, for this reason, I decided to write this little tutorial.</p><h3>Background</h3><p>When I trying to deploy my Angular app in Tomcat Server using Azure DevOps I had a lot of problems and I found different ways to do it, but any of these ways convinced me.</p><p>One way is to convert the build of Angular app into a war file then deploy using Apache Tomcat Manager.</p><p>So in this tutorial, I tried to explain who to configure Apache Tomcat and how to create a pipeline in Azure DevOps.</p><h3><strong>Tomcat configuration</strong></h3><p>First, we need to configure the user and password of Apache Tomcat, if you want to learn about it <a href="https://tomcat.apache.org/tomcat-9.0-doc/manager-howto.html">https://tomcat.apache.org/tomcat-9.0-doc/manager-howto.html</a>.</p><p>To configure a user for deploy apps, you should edit the file tomcat-users.xml there is in %TOMCAT_HOME%\conf.</p><p>Add the next lines of code:</p><pre>&lt;role rolename=”manager-gui”/&gt;<br>&lt;role rolename=”manager-script”/&gt;<br>&lt;role rolename=”manager-status”/&gt;<br>&lt;role rolename=”manager-jmx”/&gt;</pre><p>The last four lines are roles that have the next porpuse:</p><ul><li><strong>maneger-gui</strong>: Access to the HTML interface.</li><li><strong>manager-status</strong>: Access to the “Server status” page only.</li><li><strong>manager-script</strong>: Access to the tools-friendly plain text interface.</li><li><strong>manager-jmx</strong>: Access to JMX proxy interface and to the server status page.</li></ul><p>After configured the roles we going to add the user with the next line of code:</p><pre>&lt;user username=&quot;tomcat&quot; password=&quot;tomcat&quot; roles=&quot;manager-gui,manager-script,manager-status,manager-jmx&quot; /&gt;</pre><p>If you want to access to remote management console you need to edit the file contex.xml, the file there is %TOMCAT_HOME%\webapps\host-manager\META-INF, and comment on the next line.</p><pre>&lt;!--<br>&lt;Valve className=&quot;org.apache.catalina.valves.RemoteAddrValve&quot;<br>allow=&quot;127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1&quot; /&gt;<br>--&gt;</pre><p>Remember that you should configure the IP of your server. You can read more about it on the next page <a href="https://tomcat.apache.org/tomcat-9.0-doc/config/valve.html">https://tomcat.apache.org/tomcat-9.0-doc/config/valve.html</a>.</p><p>Try to access Tomcat console <a href="http://localhost:8080/manager/html">http://localhost:8080/manager/html</a> and put your user name and password.</p><figure><img alt="Login tomcat login manager." src="https://cdn-images-1.medium.com/max/1024/1*RexasinvCQ0nPRuobYljLA.png" /><figcaption>Tomcat Manager login.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqGp4msw_lavYCBD3aow1g.png" /><figcaption>Home Tomcat Manager.</figcaption></figure><h3><strong>Pipeline</strong></h3><p>A pipeline is a way to work in the culture of DevOps, it helps us to manage all cycle life of the software.</p><p>The first step is to configure the pipeline in Azure DevOps, you can create a free account at <a href="https://azure.microsoft.com/en-us/services/devops/?nav=min">https://azure.microsoft.com/en-us/services/devops/?nav=min</a>.</p><h4><strong>Pipeline configuration</strong></h4><p>First, create a project in Azure DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ZFwsmF0_J69rQOwt6OWuLQ.png" /><figcaption>Create project.</figcaption></figure><p>Is necessary to create our variable groups, those variables will be available in the process of the deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*jrTt9xJ_oqDU-jsWwhQQPw.png" /><figcaption>Configurating vars.</figcaption></figure><p>We need 6 variables:</p><ul><li><strong>output.directory</strong>: This is the directory where we put our build that will generate a script.</li><li><strong>artifact.name</strong>: For deploy in tomcat we use a war file, this war file will create after we generate the build of the app.</li><li><strong>artifact.azure.name</strong>: We need to save our war file for deploy in another environment.</li><li><strong>server.dev.user</strong>: User that we configured in the file tomcat-users.xml.</li><li><strong>server.dev.password</strong>: Password that we configured in the file tomcat-users.xml</li><li><strong>server.dev.host</strong>: Is the host where is out tomcat.</li></ul><p>We going to create an environment STAGING.</p><p>An environment in Azure DevOps is a collection of resources that can include virtual machines and others, one of the most advantages is the deployment history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNikblDF8la8b9DE5V1kBQ.png" /><figcaption>Creating environment.</figcaption></figure><p>Azure Artifacts introduces the concept of multiple feeds that you can use to organize and control access to your packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81Bk8t75Snm06PDOpARovw.png" /><figcaption>Creating feed.</figcaption></figure><h4><strong>Creating Angular App</strong></h4><p>Is necessary to install Angular CLI <a href="https://cli.angular.io/">https://cli.angular.io/</a>.</p><p>Once installed we run the next command line.</p><pre>ng new angularApp</pre><p>We need to install gulp, gulp-war and gulp-zip pacakges.</p><pre>npm install gulp gulp-war gulp-zip –save-dev</pre><p>In our project we use gulp, so we need to add a task creating gulpfile.js, you can know more about the topic in <a href="https://www.npmjs.com/package/gulp-war.">https://www.npmjs.com/package/gulp-war.</a></p><p>Create gulpfile.js in the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c66ae473a6b5bc04ae09a1480fa0fb/href">https://medium.com/media/40c66ae473a6b5bc04ae09a1480fa0fb/href</a></iframe><p>In this task, we packaging it into a war file.</p><p>Add the next scripts in package.json, first generate a build of our project, the second run the gulp task to convert our build in a war file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50261be8a0cb6110029cf5f3585252ef/href">https://medium.com/media/50261be8a0cb6110029cf5f3585252ef/href</a></iframe><h4><strong>Crate our azure-pipelines.yml file</strong></h4><p>The next task is to create the azure-pipeline.yml in our project.</p><p>First, we configure when the pipeline trigger.</p><pre>trigger:<br> branches:<br>  include:<br>   - master<br>   - release/*</pre><p>The pipeline triggered when pushing into branch master or branch release.</p><p>Configure the version of ubuntu that we use for the task.</p><pre>pool:<br> vmImage: &#39;ubuntu-latest&#39;</pre><p>We need to specify the variables that we use.</p><pre>variables:<br> - group: angular-app-vars</pre><p>The next step is to configure the stages to generate the build and the war file.</p><pre>- script: |<br>  npm install<br>  npm run build<br>  npm run build:war<br> displayName: &#39;PublishPipelineArtifact&#39;</pre><p>It is necessary to publish our artifact to later use it. You can know about it <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/artifacts/pipeline-artifacts?view=azure-devops&amp;tabs=yaml">https://docs.microsoft.com/en-us/azure/devops/pipelines/artifacts/pipeline-artifacts?view=azure-devops&amp;tabs=yaml</a></p><pre>- task: PublishPipelineArtifact@1<br>  inputs:<br>   artifactsFeeds: anguarApp<br>   targetPath: &#39;$(output.directory)/$(artifact.name)&#39;<br>   artifactName: &#39;$(artifact.azure.name)&#39;<br>  displayName: &#39;PublishPipelineArtifact&#39;<br>  name: &#39;PublishPipelineArtifact&#39;</pre><p>The next stept is deploy in the STAGING environment, for this task is necessary to download the artifact.</p><pre>- task: DownloadPipelineArtifact@2<br>  inputs:<br>   targetPath: &#39;$(output.directory)/&#39;<br>   artifactName: &#39;$(artifact.azure.name)&#39;<br>  displayName: &#39;DownloadPipelineArtifact&#39;<br>  name: &#39;DownloadPipelineArtifact&#39;</pre><p>The next script is for deploy in tomcat if you can know more about it <a href="https://tomcat.apache.org/tomcat-9.0-doc/manager-howto.html">https://tomcat.apache.org/tomcat-9.0-doc/manager-howto.html</a></p><pre>- script: |<br>  curl -T &#39;$(output.directory)/$(artifact.name)&#39; &#39;https://$(server.dev.user):$(server.dev.password)@$(server.dev.host)/manager/text/deploy?path=/$(artifact.azure.name)&amp;update=true&#39;<br>  displayName: &#39;Deploying app&#39;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a66436b20f993ac70aa60261c0af6dd/href">https://medium.com/media/8a66436b20f993ac70aa60261c0af6dd/href</a></iframe><h4>Configuration of pipeline in Azure DevOps</h4><p>The next step is to configure the pipeline in Azure DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmDGV2rKxdqf1dfsNXvqhg.png" /><figcaption>Create pipeline</figcaption></figure><p>The next step is to select GitHub (YAML).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*JzqUsXIm1KFIYV9IR7fETQ.png" /><figcaption>Configuration repository</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*ZdcNB_pIGf82bm4T5zBBTw.png" /><figcaption>Select application</figcaption></figure><p>We created a pipeline, so chose the Existing Azure Pipeline YAML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*WHD387RV1oWEu2NFyNZbEg.png" /><figcaption>Existing Azure Pipeline</figcaption></figure><p>Our pipeline was created and configurated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*ctQZXrSajwvYrkg4yfdcow.png" /><figcaption>Yaml</figcaption></figure><p>Once configurated the pipeline try to push new changes into the release or master branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*fPJetFoShDfQrMN8CGjdsw.png" /><figcaption><strong>Triggered pipeline</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*qg7WY7rvRIYY7gA-NxFLjw.png" /><figcaption><strong>Triggered pipeline</strong></figcaption></figure><p>You can find the Angular project in <a href="https://github.com/bautistaj/angularApp">https://github.com/bautistaj/angularApp</a>.</p><h3>Conclusion</h3><p>Let’s look at what we have learned.</p><ul><li>How to configure User and Password Tomcat Server</li><li>How to configure pipeline in Azure DevOps</li><li>How to create Angular App and packaging into war file using gulp.</li><li>How to create an azure-pipelines.yml</li></ul><p>First of all thanks for reading and I hope this little tutorial will help you.</p><p>Kindest Regards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=900e67a21122" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-deploy-an-angular-app-in-apache-tomcat-with-azure-devops-900e67a21122">How to Deploy an Angular App in Apache Tomcat With Azure DevOps</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>