<?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 Yasir Hamm on Medium]]></title>
        <description><![CDATA[Stories by Yasir Hamm on Medium]]></description>
        <link>https://medium.com/@yasirhamm?source=rss-3fcc40bd1f2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xf-mpr0G1jmr2jE19vwIwA@2x.jpeg</url>
            <title>Stories by Yasir Hamm on Medium</title>
            <link>https://medium.com/@yasirhamm?source=rss-3fcc40bd1f2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:14:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasirhamm/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[Bulk Deleting GitHub Repositories with TypeScript]]></title>
            <link>https://yasirhamm.medium.com/bulk-deleting-github-repositories-with-typescript-819b8dc63508?source=rss-3fcc40bd1f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/819b8dc63508</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[bulk-delete-github-repos]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Yasir Hamm]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 17:52:56 GMT</pubDate>
            <atom:updated>2024-01-21T17:54:16.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96-IK6Gwytt-6nLPAMuF1A.png" /></figure><p>Have you ever wanted to delete unwanted/old repositories on GitHub? <br>If not, let me walk you through the standard manual process:</p><ol><li>Log into your GitHub account.</li><li>Click on your profile image in the upper right corner.</li><li>Select the “Your Profile” option.</li><li>Go to your Repositories.</li><li>Choose the repository you wish to delete.</li><li>Click on “Settings”.</li><li>Scroll down to the bottom and click on “Delete Repository”.</li><li>A confirmation window will pop up, asking you to copy the repository name to confirm the deletion.</li></ol><p>Kill me …</p><p>Don’t worry about this tedious process. <br>In this article, we will explore a TypeScript script designed to bulk delete GitHub repositories. This script is particularly useful when you need to clean up your GitHub account by removing multiple repositories at once.</p><h3>Setting Up</h3><p>The script begins by importing necessary dependencies:</p><pre>import { config } from &#39;dotenv&#39;;<br>config();<br>import Logging from &#39;./library/logging&#39;;<br>import axios from &#39;axios&#39;;</pre><p>The dotenv package is used to load environment variables from a .env file. The Logging module is a custom logging utility, and axios is a popular HTTP client used to make requests to the GitHub API.</p><p><em>Make sure you have them installed these packages in your project.</em></p><h3>Authenticating with GitHub API</h3><p>The script retrieves a GitHub token from the environment variables:</p><pre>const token = process.env.TOKEN;</pre><p>This token is used to authenticate with the GitHub API. If the token is not set, the script logs an error message and exits:</p><pre>if (!token) {<br>  Logging.error(&#39;GitHub token is not set in the environment variables.&#39;);<br>  process.exit(1);<br>}</pre><p>You can generate one from <a href="https://github.com/settings/tokens">here</a>. Make sure that the token allows you to write/read.</p><h3>Creating an Axios Instance</h3><p>An instance of axios is created with the base URL of the GitHub API and the authorization header set to the GitHub token:</p><pre>onst axiosInstance = axios.create({<br>  baseURL: &#39;https://api.github.com&#39;,<br>  headers: {<br>    Authorization: `token ${token}`,<br>  },<br>});</pre><h3>Fetching Repositories</h3><p>The <em>fetchRepositories</em> function fetches all repositories for the authenticated user:</p><pre>interface Repository {<br>  name: string;<br>  visibility: string;<br>}<br><br>async function fetchRepositories(): Promise&lt;Repository[]&gt; {<br>  let page = 1;<br>  const perPage = 100; // Maximum allowed<br>  let fetchedRepos: Repository[] = [];<br>  let hasMore = true;<br>  try {<br>    while (hasMore) {<br>      const response = await axiosInstance.get(<br>        `/user/repos?per_page=${perPage}&amp;page=${page}`,<br>      );<br><br>      const repos = response.data as Repository[];<br>      if (repos.length === 0) {<br>        hasMore = false; //<br>      }<br>      fetchedRepos = [...fetchedRepos, ...repos];<br>      page++;<br>    }<br><br>    Logging.info(`Total repositories fetched: ${fetchedRepos.length}`);<br>    return fetchedRepos;<br>  } catch (error: unknown) {<br>    if (error instanceof Error) {<br>      Logging.error(`Error fetching repositories: ${error.message}`);<br>    } else {<br>      Logging.error(&#39;Error fetching repositories&#39;);<br>    }<br>    return [];<br>  }<br>}</pre><p>It uses pagination to fetch all repositories, 100 at a time (the maximum allowed by the GitHub API). It continues fetching until no more repositories are returned.</p><h3>Deleting Repositories</h3><p>The <em>deleteRepository</em> function deletes a repository given its name:</p><pre>const owner = &quot;github-username&quot; // yours<br>async function deleteRepository(repoName: string): Promise&lt;void&gt; {<br>  try {<br>    await axiosInstance.delete(`/repos/${owner}/${repoName}`);<br>    Logging.info(`Repository ${repoName} deleted successfully`);<br>  } catch (error: unknown) {<br>    if (error instanceof Error) {<br>      Logging.error(`Error deleting repository<br>      [Name]:${repoName}<br>      [Message]:${error.message}`);<br>    }<br>    Logging.error(`Error deleting repository ${error}`);<br>  }<br>}</pre><p>It makes a DELETE request to the /repos/{owner}/{repo} endpoint of the GitHub API.</p><h3>Bulk Deleting Repositories</h3><p>The main function fetches all repositories, filters out those that are not in the whitelist and are public, and deletes the remaining repositories:</p><pre>// names of the public ones you dont want to delete<br>const whiteList: string[]= [&quot;repo_1&quot;, &quot;repo_2&quot;] <br>async function main(): Promise&lt;void&gt; {<br>  const repos = await fetchRepositories();<br>  const deletePromises = repos<br>    .filter(<br>      (repo: Repository) =&gt;<br>        !whiteList.includes(repo.name) &amp;&amp; repo.visibility === &#39;public&#39;,<br>    )<br>    .map((repo) =&gt; deleteRepository(repo.name));<br><br>  await Promise.all(deletePromises);<br>}<br>main();</pre><h3>The Whitelist</h3><p>In the context of this script, the whitelist is an array of repository names that should be excluded from deletion:</p><pre>const whiteList = [<br>];</pre><p>When the script is run, it fetches all repositories for the authenticated user. However, before it proceeds to delete any repositories, it checks this whitelist. If a repository’s name is found in the whitelist, it is not deleted. This allows you to protect certain repositories from being deleted by the script.</p><p>In the main function, this check is performed using the Array.prototype.includes method:</p><pre>const deletePromises = repos<br>  .filter(<br>    (repo: Repository) =&gt;<br>      !whiteList.includes(repo.name) &amp;&amp; repo.visibility === &#39;public&#39;,<br>  )<br>  .map((repo) =&gt; deleteRepository(repo.name));</pre><p>This line of code filters out any repositories that are in the whitelist or are not public, and only the remaining repositories are deleted. This is a simple yet effective way to ensure that only the desired repositories are deleted when the script is run.</p><pre>  await Promise.all(deletePromises);</pre><p>Promise.all(deletePromises) returns a single Promise that resolves when all of the promises in the deletePromises array have resolved, or rejects as soon as one of them rejects. The await keyword is used to pause the async function execution until the Promise resolves or rejects, effectively making asynchronous operations appear as synchronous. This approach is beneficial when the promises are independent of each other, as it allows for concurrent execution, which can lead to performance improvements.</p><h3>The End</h3><p>This script is a powerful tool for bulk deleting GitHub repositories, demonstrating how to interact with the GitHub API using TypeScript and axios. It’s a great example of how you can automate tedious tasks with a bit of code. And I love it.</p><p>Please feel free to correct me grammatically and technically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819b8dc63508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set up a Production-Ready Project with Node and TypeScript]]></title>
            <link>https://yasirhamm.medium.com/how-to-set-up-a-production-ready-project-with-node-and-typescript-19db65c55a4e?source=rss-3fcc40bd1f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/19db65c55a4e</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[server-setup]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Yasir Hamm]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 23:02:27 GMT</pubDate>
            <atom:updated>2024-01-14T23:02:27.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWcVpliOX0aL_WPz0e9gqw.png" /></figure><p>Hi, my name is Yasir, and I’m a full-stack developer with a strong focus on backend technologies. Currently, I primarily work with Asp.NET (C#) at <a href="https://www.oxefit.com/">OxeFit</a>. It’s been nearly 15 months since I last started and completed a project from scratch, and I’ve been eagerly waiting for a fresh idea to ignite my enthusiasm.</p><p>A few days ago, during a weekend clean-up of my GitHub repositories, I realized how tedious it was to delete each repository individually — kill me. Amidst this, an idea struck me: what if there was a CLI command to delete multiple repositories at once? Excited, I started researching, only to discover the tools have existed for years. I soon rallied with a new resolve: why not build my own version? This could be a valuable learning experience, and existing tools could serve as helpful references if needed.</p><p>Missing my work with Node.js and considering my experience with React and TypeScript, I decided to develop this project using Node.js and TypeScript, aiming to make it production-ready.</p><p>As I started on setting up the project, I realized I was a bit rusty. Despite extensive Googling and consulting ChatGPT, I couldn’t find the comprehensive guide I was looking for. So, I decided to document my process. This article is as much for my future reference as it is for you, offering a step-by-step guide to setting up a Node.js and TypeScript project.</p><p>Let’s start</p><h3>Creating a package.json File</h3><p>First, run the command:</p><pre>npm init -y</pre><blockquote><strong><em>What is npm?</em></strong><br>In Node.js, npm(Node Package Manager) is a vital tool for managing packages and their dependencies in your project. Similar to pip in Python or NuGet in C#, npm allows you to install and manage code packages from the npm registry.</blockquote><blockquote><strong><em>What does </em></strong><strong><em>init do?</em></strong><br>The init command initializes a new Node.js project. It creates a package.json file, which is crucial for managing your project&#39;s dependencies.</blockquote><blockquote><strong>What is the </strong><strong>-y flag?</strong><br>The -y flag, an optional addition, skips the questionnaire, instead filling the package.json file with default values, which can be modified later as needed.</blockquote><p><strong><em>Understanding </em></strong><strong><em>package.json</em></strong><br>Think of package.json as a recipe for your application. It lists all the packages (or &#39;ingredients&#39;) your project needs. When you run your application, it looks at this file, downloads the necessary packages from the internet if they&#39;re not already installed, and then proceeds with execution.</p><p>In essence, package.json is a key component that tells your application what it needs to run successfully.</p><h3>Installation</h3><p>Let’s begin by installing the necessary dependencies for our project.</p><p>Run the following command to install Express:</p><pre>npm install express</pre><p>Before proceeding further, it’s a good practice to test our setup. Next, we’ll set up a simple server using Express, a popular Node.js web framework known for its simplicity in server creation.</p><h4>Setting Up a Basic Server</h4><ol><li>In your project’s root directory, create a folder named src (short for &#39;source&#39;). This is a conventional name widely used by developers.</li><li>Inside the src folder, create a file named src/app.js.</li></ol><p>Paste the following code into app.js:</p><pre>// This is a simple Express server.<br>// Import the Express package<br>const express = require(&#39;express&#39;);<br>// Create an instance of an Express server<br>const app = express();<br>// Set the port number<br>const port = 8080;<br><br>// Define a route that returns a JSON object with a message when visiting the /hello endpoint<br>app.get(&#39;/hello&#39;, (req, res) =&gt; {<br>  res.status(200).json({ message: &#39;World!&#39; });<br>});<br><br>// Start the server and listen on the specified port<br>app.listen(port, () =&gt; {<br>  console.log(`Server running at http://localhost:${port}`);<br>});</pre><h4>Testing the Server</h4><ol><li>Open your terminal and navigate to your project’s root directory</li><li>Run the server using the command:</li></ol><pre>node app.js</pre><p>3. You should see the message Server running at http://localhost:8080 in your terminal.</p><p>To test the server, open your web browser and go to <em>http://localhost:8080/hello</em>. You should see the JSON response {&quot;message&quot;:&quot;World!&quot;}.</p><p>Alternatively, you can use API clients like Insomnia or Postman to send requests to your server. These tools are especially useful for more complex API testing and development.</p><h3>Integrating TypeScript into the Project</h3><p>After ensuring that we have a server running using pure Node.js, let’s introduce TypeScript to our project.</p><p><strong>TypeScript Compiler (ts-node)</strong></p><p>First, let’s transform our Node project into TypeScript:</p><ol><li>Rename src/app.js to src/app.ts.</li><li>Replace app.ts contents with</li></ol><pre>console.log(&quot;Hello World!&quot;);</pre><blockquote><strong>Why TypeScript?</strong><br>TypeScript is a superset of JavaScript that adds static typing, making our code more robust and maintainable. However, the Node.js environment doesn’t natively understand TypeScript.</blockquote><p><strong>Compiling TypeScript to JavaScript</strong><br>To execute TypeScript code in Node.js, we need to convert it to JavaScript. TypeScript comes with a built-in compiler called tsc for this purpose. To streamline this process in a Node.js environment, we use a package called ts-node.</p><p><strong>Installing and Using</strong> <strong>ts-node:</strong></p><p>To begin, install ts-node by running the following command in your terminal:</p><pre>npm install ts-node</pre><p>ts-node enables us to execute TypeScript files directly in Node.js, without manually compiling them to JavaScript first. It eliminates the need for a separate compilation step.</p><p><strong>Running the TypeScript File:</strong></p><p>Next, navigate to the src/ directory in the terminal and execute the file using ts-node with command:</p><pre>ts-node src/app.ts</pre><p>You should see “Hello World!” in your terminal.</p><p><strong>Configuring the TypeScript Compiler with </strong><strong>tsconfig.json</strong></p><p>In the root directory of your project, create a file named tsconfig.json and add the following configuration:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;lib&quot;: [&quot;es2018&quot;, &quot;dom&quot;], // Specify a list of libraries the project will use<br>    &quot;target&quot;: &quot;es2018&quot;, // Set the JavaScript version for output files<br>    &quot;module&quot;: &quot;commonjs&quot;, // Set the module system (Node.js uses CommonJS)<br>    &quot;strict&quot;: true, // Enable all strict type-checking options<br>    &quot;baseUrl&quot;: &quot;.&quot;, // Base directory to resolve non-relative module names<br>    &quot;outDir&quot;: &quot;dist&quot;, // Redirect output structure to the &#39;dist&#39; folder<br>    &quot;rootDir&quot;: &quot;.&quot;, // Specify the root directory of source files<br>    &quot;skipLibCheck&quot;: true, // Skip type checking of all declaration files (*.d.ts)<br>    &quot;esModuleInterop&quot;: true, // Enables compatibility with default imports from modules<br>    &quot;moduleResolution&quot;: &quot;node&quot;, // Choose a module resolution strategy<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;removeComments&quot;: true,<br><br>    &quot;paths&quot;: {<br>      &quot;@src/*&quot;: [&quot;src/*&quot;] // absolute paths<br>    },<br><br>    &quot;strictNullChecks&quot;: true, // Enable strict null checks<br>    &quot;strictFunctionTypes&quot;: true, // Enable strict checking of function types<br>    &quot;strictPropertyInitialization&quot;: true, // Ensure non-undefined class properties are initialized in the constructor<br>    &quot;strictBindCallApply&quot;: true, // Enable stricter checking of the bind, call, and apply methods on functions<br>    &quot;forceConsistentCasingInFileNames&quot;: true, // Disallow inconsistently-cased references to the same file<br><br>    &quot;noImplicitAny&quot;: true, // Raise error on expressions and declarations with an implied &#39;any&#39; type<br>    &quot;noImplicitThis&quot;: true, // Raise error on &#39;this&#39; expressions with an implied &#39;any&#39; type<br>    &quot;alwaysStrict&quot;: true, // Parse in strict mode and emit &quot;use strict&quot; for each source file<br><br>    &quot;noUnusedLocals&quot;: true, // Report errors on unused locals<br>    &quot;noUnusedParameters&quot;: true, // Report errors on unused parameters<br>    &quot;noImplicitReturns&quot;: true, // Report error when not all code paths in function return a value<br>    &quot;noFallthroughCasesInSwitch&quot;: true // Report errors for fallthrough cases in switch statement<br>  },<br>  &quot;include&quot;: [<br>    &quot;src/**/*&quot; // Include all files in the src directory<br>  ],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;, // Exclude the node_modules directory<br>    &quot;**/*.spec.ts&quot;,<br>    &quot;**/*.test.ts&quot; // Exclude test files<br>  ]<br>}</pre><p>This tsconfig.json file serves as a central configuration for the TypeScript compiler. Key options here include specifying the target JavaScript version, enabling strict type-checking for more robust code, and setting up paths for more straightforward module imports.</p><p><strong>Path Resolution in Development</strong></p><p>To enhance readability and maintainability, and to help Node.js understand TypeScript’s paths and baseUrl options in tsconfig.json during development, we need the tsconfig-paths package. This package resolves the paths in tsconfig.json, allowing us to use absolute paths, which simplifies imports in our project.</p><p>For example, instead of using relative paths like import User from &#39;../../../models/user.models&#39;;, we can use import User from &#39;@src/models/user.models&#39;;</p><p>Install tsconfig-paths:</p><pre>npm install --save-dev tsconfig-paths</pre><p><strong>Updating </strong><strong>package.json Scripts</strong></p><p>Now, add the following script to your package.json to run your program using these configurations:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;ts-node -r tsconfig-paths/register src/app.ts&quot;<br>  }<br>}</pre><p><strong>Testing Absolute Path Resolution</strong></p><p>To test this setup, create a folder named math inside /src, and within that folder, create a file called add.ts with the following content:</p><pre>export const add = (x: number, y: number): number =&gt; {<br>  return x + y;<br>};</pre><p>Then, update src/app.ts to use this new module:</p><pre>import { add } from &#39;@src/math/add&#39;;<br><br>console.log(add(1, 2));</pre><p>Run your program using the command:</p><pre>npm run dev</pre><p>You should see “3” in your terminal, confirming that the absolute path resolution is working correctly.</p><p>Note: Keep in mind that tsconfig-paths is used only during development. For production builds, TypeScript will be compiled to JavaScript, and standard Node.js resolution will apply.</p><h3>Setting Up .gitignore for Your Project</h3><p>In most applications, especially those using version control systems like Git, it’s essential to have a .gitignore file. This file tells Git which files or directories to ignore in your repository. For instance, we generally don&#39;t want to include the node_modules folder because it can be recreated with npm install, and we avoid committing the dist folder as it typically contains compiled code.</p><p>Creating the .gitignore File</p><ol><li>In your project’s root directory, create a file named .gitignore.</li><li>Add the following script to it:</li></ol><pre># Logs<br>logs<br>*.log<br>npm-debug.log*<br>yarn-debug.log*<br>yarn-error.log*<br><br># Runtime data<br>pids<br>*.pid<br>*.seed<br>*.pid.lock<br><br># Directory for instrumented libs generated by jscoverage/JSCover<br>lib-cov<br><br># Coverage directory used by tools like istanbul<br>coverage<br><br># nyc test coverage<br>.nyc_output<br><br># Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)<br>.grunt<br><br># Bower dependency directory (https://bower.io/)<br>bower_components<br><br># node-waf configuration<br>.lock-wscript<br><br># Compiled binary addons (https://nodejs.org/api/addons.html)<br>build/Release<br><br># Dependency directories<br>node_modules/<br>jspm_packages/<br><br># TypeScript v1 declaration files<br>typings/<br><br># Optional npm cache directory<br>.npm<br><br># Optional eslint cache<br>.eslintcache<br><br># Microbundle cache<br>.rpt2_cache/<br>.rts2_cache_cjs/<br>.rts2_cache_es/<br>.rts2_cache_umd/<br><br># Optional REPL history<br>.node_repl_history<br><br># Output of &#39;npm pack&#39;<br>*.tgz<br><br># Yarn Integrity file<br>.yarn-integrity<br><br># dotenv environment variables file<br>.env<br>.env.test<br><br># parcel-bundler cache (https://parceljs.org/)<br>.cache<br><br># next.js build output<br>.next<br><br># nuxt.js build / generate output<br>.nuxt<br>dist/<br><br># vuepress build output<br>.vuepress/dist<br><br># Serverless directories<br>.serverless/<br><br># FuseBox cache<br>.fusebox/<br><br># DynamoDB Local files<br>.dynamodb/<br><br># TSC cache<br>*.tsbuildinfo<br><br># IDE / Editor</pre><p>This script covers a broad range of files and folders typically found in Node.js and TypeScript projects, including logs, runtime data, coverage reports, and more. It’s important to tailor this file to your project’s specific needs. For example, node_modules/ and dist/ are essential to ignore in most projects, while other entries like .dynamodb/ might only be relevant for projects using DynamoDB.</p><p><strong>Understanding the Importance of Comments</strong></p><p>Notice the comments within the .gitignore file. These comments explain what each section is ignoring, making the file easier to understand and maintain. It&#39;s a good practice to keep your .gitignore well-commented, especially in collaborative projects.</p><p>With the dependencies installed, the tsconfig.json configured, and the .gitignore file set up, we have completed the basic setup for our project. This foundation will help in maintaining a clean and efficient development environment.</p><h4>Automating Server Restart with Nodemon</h4><p>During development, we often make frequent changes to our code. Imagine having to manually restart the server after every change — it can be quite a tedious process. To automate this, we’ll use nodemon, a utility that monitors our files for changes and automatically restarts the server when a change is detected.</p><p>Installing Nodemon</p><pre>npm install --save-dev nodemon</pre><p><strong>Configuring Nodemon</strong></p><p>Some developers prefer to configure nodemon directly in the package.json file, but I like to use a separate configuration file for clarity. Create a nodemon.json file in your root directory with the following configuration:</p><pre>{<br>  &quot;watch&quot;: [<br>    &quot;src&quot;<br>  ],<br>  &quot;ext&quot;: &quot;ts,js,json&quot;,<br>  &quot;ignore&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;src/**/*.spec.ts&quot;,<br>    &quot;coverage&quot;,<br>    &quot;dist&quot;<br>  ],<br>  &quot;exec&quot;: &quot;ts-node -r tsconfig-paths/register ./src/app.ts&quot;,<br>  &quot;env&quot;: {<br>    &quot;NODE_ENV&quot;: &quot;dev&quot;<br>  }<br>}</pre><p>Each option in nodemon.json is set up to optimize our development workflow:</p><blockquote>watch: → Monitors files in the src directory for changes.</blockquote><blockquote>ext: → Restarts the server if files with .ts, .js, or .json extensions are modified.</blockquote><blockquote>ignore: → Prevents restarting the server for changes in specified directories like node_modules.</blockquote><blockquote>exec: → The command to start the application, using ts-node and tsconfig-paths.</blockquote><blockquote>env: → Sets environment variables, like NODE_ENV to development, which can be used to enable specific features during development.</blockquote><p><strong>Updating </strong><strong>package.json</strong></p><p>To integrate Nodemon into our workflow, update the scripts in package.json:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;nodemon&quot;<br>  }<br>}</pre><p>Running the Application with Nodemon</p><p>Start your application with:</p><pre>npm run dev</pre><p>You should see the output “3” in the terminal. Try changing the numbers in your code and observe the automatic update in the terminal output.</p><p>Congratulations, you’re efficiently managing your development process with Nodemon!</p><h4>Adding Jest for Testing</h4><p>Let me share a story about how testing, particularly integration testing, made a significant difference in my work. Recently, while working on a React frontend feature, I encountered issues with some CRUD operations. After delving into the backend tests, I realized they lacked comprehensive integration tests that could have saved me time by showing how the application components worked together. This experience reinforced the value of thorough testing in both saving time and providing clarity in application development.</p><p><strong>Installing Jest for TypeScript Projects</strong></p><p>To set up testing in our project, we’re going to use Jest, a popular testing framework. Along with Jest, we’ll install @types/jest for TypeScript definitions and ts-jest for transpiling TypeScript test files.</p><p>Run the installation command:</p><pre>npm install --save-dev jest @types/jest ts-jest</pre><p><strong>Configuring Jest with TypeScript</strong></p><p>Next, create a jest.config.js file in your project&#39;s root directory with the following settings:</p><pre>module.exports = {<br>  preset: &#39;ts-jest&#39;,<br>  testEnvironment: &#39;node&#39;,<br>  coverageDirectory: &#39;coverage&#39;,<br>  collectCoverageFrom: [&#39;src/**/*.{js,ts}&#39;],<br>  transform: {<br>    &#39;^.+\\.tsx?$&#39;: &#39;ts-jest&#39;,<br>  },<br>  moduleNameMapper: { &#39;src/(.*)&#39;: &#39;&lt;rootDir&gt;/src/$1&#39; },<br>  moduleDirectories: [&#39;node_modules&#39;, &#39;src&#39;],<br>  coverageThreshold: {<br>    global: {<br>      branches: 0,<br>      functions: 0,<br>      lines: 0,<br>      statements: 0,<br>    },<br>  },<br>  testRegex: &#39;(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$&#39;,<br>  moduleFileExtensions: [&#39;ts&#39;, &#39;tsx&#39;, &#39;js&#39;, &#39;jsx&#39;, &#39;json&#39;, &#39;node&#39;],<br>};</pre><p>Let’s break down some key configurations:</p><blockquote>preset: &#39;ts-jest&#39;: → Informs Jest to use ts-jest for processing TypeScript files.</blockquote><blockquote>testEnvironment: &#39;node&#39;: → Sets the environment where tests will run; in our case, Node.js.</blockquote><blockquote>coverageDirector: →Specifies where Jest should output coverage reports.</blockquote><blockquote>transform: → Directs Jest to use ts-jest for .ts or .tsx files.</blockquote><blockquote>moduleNameMapper: → Helps Jest understand module aliases, particularly useful for projects using path mapping.</blockquote><p>Now that Jest is configured, let’s add some useful scripts to our package.json file to facilitate running tests.</p><pre>{<br>  &quot;scripts&quot;:{<br>    &quot;dev&quot;: &quot;nodemon&quot;,<br><br><br>    &quot;test&quot;: &quot;jest&quot;,<br>    &quot;test:watch&quot;: &quot;jest --watch&quot;,<br>    &quot;test:coverage&quot;: &quot;jest --coverage&quot;,<br>  }</pre><blockquote>test: “ jest”: →This command runs the Jest test runner on your project. It will execute all test file(like *.test.js or *.spec.js).</blockquote><blockquote>test:watch: “jest — watch”: → Jest will automatically re-run tests when it detects changes in your files. This is useful during development when you want to get immediate feedback on your changes.</blockquote><blockquote>test:coverage: “jest — coverage”: → Generate a code coverage report. Code coverage is a measure of how much of your code is actuallu covered by your tests. The — coverage flag tells Jest to collect coverage information and display a summary in the terminal. It also generates detailed HTML reports in a coverage directory.</blockquote><p><strong>Running Tests</strong><br>With Jest configured, you can now write tests in TypeScript. Jest will automatically find and run files matching the test patterns defined in jest.config.js.</p><p>Remember, effective testing involves not just verifying individual units but also how different parts of your application interact. Happy testing!</p><h4><strong>Lint configuration</strong></h4><p>Imagine you and your team are shipping a code that is:</p><ol><li>Inconsistent Coding Styles.</li><li>Potential for Bugs and Typos</li><li>Unused Variables and Imports</li><li>Lack of Best Practices Enforcement.</li></ol><p>If your code has all of these attributes, the code review would be a nightmare and I feel sorry for onboarding a new developer to your team.<br>And on top of that, maintaining the code would kill a lot of time and time is money.</p><p>we want to ship a clean and well structured code, and to do so, we are going to use a static code analysis tool to identify problematic patterns in our code called `eslint`.</p><h3>Install</h3><pre>npm install - save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin</pre><p><strong>Create a file called `.eslintrc.json`</strong> and add the following code to it:</p><pre>{<br> &quot;env&quot;: {<br> &quot;node&quot;: true,<br> &quot;jest&quot;: true<br> },<br> &quot;parser&quot;: &quot;@typescript-eslint/parser&quot;,<br> &quot;extends&quot;: [<br> &quot;eslint:recommended&quot;,<br> &quot;plugin:@typescript-eslint/recommended&quot;,<br> &quot;prettier&quot;,<br> &quot;plugin:prettier/recommended&quot;<br> ],<br> &quot;parserOptions&quot;: {<br> &quot;ecmaVersion&quot;: 2020,<br> &quot;sourceType&quot;: &quot;module&quot;<br> },<br> &quot;plugins&quot;: [&quot;@typescript-eslint&quot;],<br> &quot;rules&quot;: {<br> &quot;@typescript-eslint/no-explicit-any&quot;: &quot;warn&quot;,<br> &quot;@typescript-eslint/explicit-function-return-type&quot;: &quot;warn&quot;,<br> &quot;@typescript-eslint/no-unused-vars&quot;: &quot;warn&quot;,<br> &quot;@typescript-eslint/no-non-null-assertion&quot;: &quot;error&quot;,<br> &quot;eqeqeq&quot;: &quot;error&quot;,<br> &quot;no-console&quot;: &quot;warn&quot;,<br> &quot;no-unused-vars&quot;: &quot;warn&quot;,<br> &quot;no-constant-condition&quot;: &quot;error&quot;,<br> &quot;curly&quot;: &quot;error&quot;,<br> &quot;no-eval&quot;: &quot;error&quot;,<br> &quot;no-implied-eval&quot;: &quot;error&quot;,<br> &quot;no-redeclare&quot;: &quot;error&quot;,<br> &quot;indent&quot;: [&quot;error&quot;, 2],<br> &quot;quotes&quot;: [&quot;error&quot;, &quot;single&quot;],<br> &quot;semi&quot;: [&quot;error&quot;, &quot;always&quot;],<br> &quot;callback-return&quot;: &quot;warn&quot;,<br> &quot;handle-callback-err&quot;: &quot;error&quot;,<br> &quot;no-path-concat&quot;: &quot;error&quot;<br> }<br>}</pre><blockquote>env Sets up the environment for Node.js and ECMAScript 2021.<br> extend : Extends the recommended ESLint rules and the recommended rules from the TypeScript ESLint plugin.</blockquote><blockquote>parser : →Specifies the parser to be used (in this case, the TypeScript parser).</blockquote><blockquote>parserOptions : →Specifies the ECMAScript version and source type.</blockquote><blockquote>plugins : →Specifies the plugins to be used (in this case, the TypeScript ESLint plugin).</blockquote><blockquote>rules : → Defines custom rules.</blockquote><p>With ESLint configured, you’re taking a significant step towards ensuring high-quality, maintainable code. This not only benefits individual developers but also enhances team collaboration.</p><h3>Husky</h3><p>Sometimes, we make changes, committed, and pushed it, and then the CI builds failed, why? Well for many reasons but one of them is linting. It’s a good to lint before commit, and because we are human and our minds have thousands of thoughts that makes you forget not matter how careful you are, there’s a plugin called husky that would run before the commit and exit the `git commit` when the code does not pass linting.</p><h4>Install</h4><pre>npm install husky --save-dev</pre><p>Husky is a tool that allows you to set up Git hooks easily, ensuring scripts like lint checks are run before specific actions such as committing code.</p><p>Add the following to your package.json</p><pre>  &quot;husky&quot;: {<br>    &quot;hooks&quot;: {<br>      &quot;pre-commit&quot;: &quot;npm run lint&quot;<br>    }</pre><blockquote>In this case, the pre-commit: “npm run lint” hook runs the linting script before every commit, which helps catch and fix linting errors before they’re committed to the repository</blockquote><p>By integrating Husky into your workflow, you reduce the chances of committing code that doesn’t meet your project’s quality standards, thereby streamlining the development process and reducing errors in your CI builds.</p><h3>Environments variables</h3><p>There are times when hard-coding configuration details, such as database connection strings or secret keys, directly in your code is not ideal, especially when these details are sensitive and should not be exposed publicly.</p><p>Fortunately, Node has a package called `dotenv` that allows you to load environment variables from a `.env` file into `process.env`. This package is very useful when you want to keep your secret keys and configuration in a safe place.</p><p>for example:<br>In the root directory creae a file called .envand add the following code to it:</p><pre>TEST=&#39;test&#39;</pre><p>And then in your code, you can access the variable like this:</p><pre>import { config } from &#39;dotenv&#39;;<br>config();<br>const test = process.env.TEST;<br>console.log(test);</pre><p>Importing dotenv at the beginning of your file is important because it allows you to use the environment variables in the rest of your code.</p><p>When you call dotenv.config() it reads the .env file, parses the contents, and adds them to the process.envobject in Node.js. This process.env object is then available throughout your application.</p><p>If you import dotenv later in your file, any code before the import won’t have access to the environment variables from your .env file. Errors.</p><p>Run your server, and you should see “test” inside your terminal.</p><p>Remember it is important to note that the .env file should not be committed to the repository to prevent exposing sensitive information.</p><h3>Prettier</h3><p>Ok, since im going to mention something about beauty, let’s me start by talking about myself — so humble 😆. JK</p><p>All jokes aside, Prettier is a powerful code formatter that ensures your code is not only functional but also aesthetically pleasing and consistently styled.</p><p><strong>Install</strong></p><pre>npm install --save-dev prettier</pre><p>Create file under your root directory called .prettierrc and add the following code to it:</p><pre>{<br> &quot;semi&quot;: true,<br> &quot;trailingComma&quot;: &quot;all&quot;,<br> &quot;singleQuote&quot;: true,<br> &quot;printWidth&quot;: 80,<br> &quot;tabWidth&quot;: 2<br>}</pre><p>This configuration does the following:</p><blockquote>semi: Ensures that statements are ended with semicolons.</blockquote><blockquote>trailingComma: → Includes trailing commas wherever possible.<br> singleQuote: → Uses single quotes instead of double quotes.<br> printWidth: → Wraps lines longer than 80 characters.</blockquote><blockquote>tabWidth: → Specifies the number of spaces per indentation-level.</blockquote><p>Now, to format your code using prettier, run the following command:</p><pre>npx prettier --write</pre><p>Or you can add this script to your package.json file:</p><pre>&quot;scripts&quot;: {<br> &quot;format&quot;: &quot;prettier --write .&quot;<br> }</pre><h3>Creating a Custom Logging Module.</h3><p>To enhance our application’s logging capabilities and make the output more readable, I’m going to create a custom logging module.</p><p>Im going to use a library called chalk version 4. <br>Chalk is a library that allows us to style terminal output with colors, making logs more distinguishable and readable.</p><p>Install:</p><pre>npm install chalk@4</pre><p>Now, inside the src directory create another directory called library and inside the library directory create a file called logging.ts and copy and paste this code:</p><pre>// src/library/logging.ts<br>import chalk from &#39;chalk&#39;;<br>export default class Logging {<br>  public static info = (args: any): void =&gt; {<br>    // eslint-disable-next-line no-console<br>    console.log(<br>      chalk.blue(`<br>[${new Date().toLocaleString()}]<br>[Log]:`),<br>      typeof args === &#39;string&#39; ? chalk.blueBright(args) : args,<br>    );<br>  };<br><br>  public static warn = (args: any): void =&gt; {<br>    // eslint-disable-next-line no-console<br>    console.log(<br>      chalk.yellow(`<br>[${new Date().toLocaleString()}]<br>[Info]:`),<br>      typeof args === &#39;string&#39; ? chalk.yellowBright(args) : args,<br>    );<br>  };<br><br>  public static error = (args: any): void =&gt; {<br>    // eslint-disable-next-line no-console<br>    console.log(<br>      chalk.red(`<br>[${new Date().toLocaleString()}]<br>[Warn]:`),<br>      typeof args === &#39;string&#39; ? chalk.redBright(args) : args,<br>    );<br>  };<br><br>  public static log = (args: any): void =&gt; {<br>    // eslint-disable-next-line no-console<br>    console.log(<br>      chalk.green(`<br>[${new Date().toLocaleString()}]<br>[Error]:`),<br>      typeof args === &#39;string&#39; ? chalk.greenBright(args) : args,<br>    );<br>  };<br>}</pre><p>Now that our custom logging module is set up, we can easily import and use it throughout our application to log information, warnings, errors, and general messages in a visually appealing manner.</p><p>src/app.ts</p><pre>import { config } from &#39;dotenv&#39;;<br>config();<br>import Logging from &#39;./library/logging&#39;;<br><br>Logging.info(&#39;info&#39;);<br>Logging.warn(&#39;warn&#39;);<br>Logging.error(&#39;error&#39;);<br>Logging.log(&#39;log or success&#39;);</pre><p>Run your application, and see the beauty</p><p>In this article, we’ve successfully set up a robust and efficient development environment for a Node.js and TypeScript project, ensuring it’s ready for production. Key accomplishments include:</p><ol><li>Initializing the Project: We started by creating a package.json file with npm init -y, laying the groundwork for managing dependencies.</li></ol><p>2. Building a Basic Server: Using Express, we set up a simple server, demonstrating the ease of creating web applications with Node.js.</p><p>3. Integrating TypeScript: To enhance code quality and maintainability, we integrated TypeScript into our project, along with ts-node for executing TypeScript directly.</p><p>4. TypeScript Configuration: A tsconfig.json file was configured, setting essential compiler options for TypeScript and ensuring strict type checking.</p><p>5. Path Resolution: We streamlined our development process by implementing absolute path resolution with tsconfig-paths, enhancing code readability and maintainability.</p><p>6. .gitignore Setup: A comprehensive .gitignore file was created to keep our repository clean by excluding unnecessary files from version control.</p><p>7. Server Automation with Nodemon: To facilitate development, we automated server restarts on code changes using Nodemon.</p><p>8. Testing with Jest: We added Jest for unit and integration testing, ensuring our application components work seamlessly together.</p><p>9. Linting with ESLint: To maintain code quality, we integrated ESLint, setting up custom rules for static code analysis.</p><p>10. Pre-commit Checks with Husky: Husky was configured to run lint checks before commits, ensuring code quality before it even reaches the repository.</p><p>11. Managing Environment Variables: We used dotenv to manage sensitive configuration details securely.</p><p>12. Code Formatting with Prettier: To ensure a consistent code style, we set up Prettier, making our code not only functional but also aesthetically pleasing.</p><p>13. Custom Logging Module: Finally, we created a custom logging module using Chalk, enhancing the readability of log messages with color-coded output.</p><p>This comprehensive setup forms a solid foundation for building scalable and maintainable Node.js and TypeScript applications, ready for the challenges of a production environment.</p><p>Please feel free to correct me or add something that you think it may bring value or mention something you believe I forget or I need</p><p>You can find the project on <a href="https://github.com/YasirHasn9/NodeTS-ProductionSetup">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19db65c55a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>