<?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"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://paclinjanja.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 08:09:18 GMT</lastBuildDate><atom:link href="https://paclinjanja.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Build a GraphQL API with NestJs and MongoDB, in a modern way - Part 3.]]></title><description><![CDATA[Are you ready to take your GraphQL development skills to the next level? In this part, I am talking about ci/cd actions applied to a nest.js project.]]></description><link>https://paclinjanja.hashnode.dev/build-a-graphql-api-with-nestjs-and-mongodb-in-a-modern-way-part-3</link><guid isPermaLink="true">https://paclinjanja.hashnode.dev/build-a-graphql-api-with-nestjs-and-mongodb-in-a-modern-way-part-3</guid><category><![CDATA[nestjs]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[github-actions]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Pacifique Linjanja]]></dc:creator><pubDate>Sat, 25 Mar 2023 12:22:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679746356830/7cdc3a98-1c39-4752-a5d9-46db97ae85e7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">Overview</h2>
<p>Are you ready to take your GraphQL development skills to the next level? In this series of four articles, I'll guide you through the process of building a powerful GraphQL API using Nest and MongoDB. You'll learn best practices, and see how to scale your app just as you would in a real-world scenario.</p>
<p>First, we'll kick things off by diving into the fundamentals of Nest, a powerful NodeJS framework. We'll set up the foundation for our final project, and by the end, you'll know how to manually deploy your own sample application, if you missed this part, please take a moment to read it here.</p>
<p>Next, we'll delve into the world of Test Driven Development (TDD) for GraphQL. You'll see the benefits it brings to the development process and learn how to test your current resolvers and implement new ones using this approach.</p>
<p>In the third installment(current reading), we'll explore how to apply Continuous Integration and Continuous Deployment (CI/CD) to Nest and GraphQL apps. We'll create our pipelines and, building off the concepts from the second part, you'll see the true power of this approach in action. Once set up, you won't have to worry as much about delivering to the frontend team, and you'll be able to catch errors even before the app is shipped to client apps.</p>
<p>Finally, in the fourth and final installment, we'll take things up a notch by adding features that will introduce you to the world of micro-services. You'll learn how to break down your monolithic app into smaller, independent micro-services without disrupting any existing functionality. This is the modern approach, saving you from the headache of long, drawn-out migrations. So, let's get started and take your GraphQL development skills to the next level!</p>
<p>The full source code can be found <a target="_blank" href="https://github.com/pacyL2K19/graphql-mongodb-nestjs-tuto/tree/part-3">here(part-3)</a> branch.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To fully benefit from this series, it's important you have read the first and second parts of the series, and have a basic knowledge of NodeJS, <a target="_blank" href="https://www.apollographql.com/blog/graphql/basics/graphql-vs-rest/"><strong>GraphQL</strong></a>, <a target="_blank" href="https://docs.nestjs.com/"><strong>NestJS</strong></a>, <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html"><strong>TypeScript</strong></a>, and <a target="_blank" href="https://www.mongodb.com/docs/manual/tutorial/getting-started/"><strong>MongoDB</strong></a>. However, even if you're new to these technologies, don't worry - this series will provide a comprehensive overview of our stack, including the most crucial aspects we'll be using along the way.</p>
<h2 id="heading-what-is-cicd">What is CI/CD?</h2>
<p>CI/CD stands for Continuous Integration/Continuous Deployment and refers to a software development practice where developers continuously integrate code changes into a shared repository and continuously deploy those changes to production. In the context of developing GraphQL APIs using NestJS, CI/CD would involve automating the steps involved in building, testing, and deploying the API to a production environment.</p>
<p>The following is an example of a CI/CD pipeline for a GraphQL API built using NestJS:</p>
<ol>
<li><p>Code is committed to a shared repository such as Git.</p>
</li>
<li><p>The CI/CD server (e.g. Jenkins, TravisCI, GoogleCloud Build) triggers a build whenever code is committed to the repository.</p>
</li>
<li><p>The build process compiles the code and runs automated tests to ensure that the code meets the required quality standards.</p>
</li>
<li><p>If the tests pass, the CI/CD server will deploy the code to a staging environment for further testing.</p>
</li>
<li><p>If the tests in the staging environment pass, the code will be deployed to the production environment.</p>
</li>
<li><p>The production environment is monitored, and if any issues arise, the CI/CD pipeline can be used to quickly roll back the code to a previous version.</p>
</li>
<li><p>Then we repeat the process</p>
</li>
</ol>
<p>Here is a diagram to showcase what is written above:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403963471/dbf5e480-00b5-4a40-8161-a76786817312.png" alt class="image--center mx-auto" /></p>
<p>image1 - CI/CD Overview</p>
<h2 id="heading-advantages-of-cicd">Advantages of CI/CD</h2>
<p>The benefits of using CI/CD for our GraphQL API built with NestJS include:</p>
<ol>
<li><p>Faster and more reliable deployment processes</p>
</li>
<li><p>Improved code quality through continuous testing and integration</p>
</li>
<li><p>Improved collaboration between developers and teams (frontend and backend teams for example).</p>
</li>
<li><p>Reduced risk of human error in deployment processes</p>
</li>
<li><p>Faster resolution of issues and bugs in production.</p>
</li>
</ol>
<h2 id="heading-choose-your-tools">Choose your tools</h2>
<p>There are plenty of tools that can help you achieve CI/CD pipelines, depending on your budget, the complexity of the project, and the size of your team, including:</p>
<ol>
<li><p>GitHub Actions: easy to set up and free trial available</p>
</li>
<li><p>Jenkins - an open-source automation server for building, testing, and deploying software.</p>
</li>
<li><p>Travis CI - a cloud-based continuous integration and deployment platform for open-source and private projects.</p>
</li>
<li><p>CircleCI - a cloud-based continuous integration and deployment platform that supports various languages, including JavaScript.</p>
</li>
<li><p>GitLab CI/CD - a built-in Continuous Integration, Continuous Delivery, and Continuous Deployment solution in GitLab, an open-source Git-repository manager.</p>
</li>
<li><p>AWS CodeDeploy - a deployment service that automates software deployments to a variety of computing services, including Amazon EC2, AWS Fargate, and Lambda.</p>
</li>
<li><p>etc</p>
</li>
</ol>
<p>You can use <a target="_blank" href="https://www.g2.com/products/continuous-integration-and-delivery/competitors/alternatives">this website</a> to compare these tools.</p>
<p>For this tutorial, we'll be using Github actions for their simplicity. However, as your project grows larger, you may need to consider using Docker, setting up a repository on EC2 or Google Cloud Run, and implementing CI/CD actions. And if your project becomes even bigger, you may need to have a team specifically dedicated to DevOps managing these operations.</p>
<h2 id="heading-cicd-in-action">CI/CD in action</h2>
<p>For our use case, using Github actions, this is the flow we need to implement:</p>
<ul>
<li><p>A developer works on his feature(assigned by the project manager or the team lead): PLAN &amp; CODE</p>
</li>
<li><p>Once he is done, the developer pushes his code to a feature, bugfix or hotfix branch</p>
</li>
<li><p>When the user creates a PR, we need to trigger 2 actions(BUILD):</p>
<ul>
<li><p>Build the code, using <code>yarn build</code> to make sure the code is compiling correctly</p>
</li>
<li><p>Test our unit and end-to-end test</p>
</li>
</ul>
</li>
<li><p>If those checks don’t pass, even before someone reviews the code, the developer will be able to see what is failing, is it the build? or the test?</p>
</li>
<li><p>If they pass, a code reviewer can validate the code and approve it for production, but instead of deploying them manually, by merging on the development branch, we need to trigger a staging environment and deploy them on Render (so that the QA team can test the preview) before moving in the production environment.</p>
</li>
<li><p>This repeats over and over.</p>
</li>
</ul>
<p>Let’s first write actions to check if the build and test pass:</p>
<ol>
<li><p>In the root of the project, let’s create a folder <code>.github/workflows</code></p>
</li>
<li><p>We don’t need to create actions from scratch, the <a target="_blank" href="https://github.com/marketplace?type=">GitHub marketplace</a> gets us covered, you can find a ton of actions depending on your setup, for our project, let’s create a <code>build.yaml</code> file, like the following:</p>
<pre><code class="lang-yaml"> <span class="hljs-attr">name:</span> <span class="hljs-string">Builds</span> <span class="hljs-string">&amp;</span> <span class="hljs-string">Tests</span>

 <span class="hljs-comment"># Controls when the workflow will run</span>
 <span class="hljs-attr">on:</span>
   <span class="hljs-attr">pull_request:</span>
     <span class="hljs-attr">branches:</span> [<span class="hljs-string">'develop'</span>]

 <span class="hljs-comment"># A workflow run is made up of one or more jobs that can run sequentially or in parallel</span>
 <span class="hljs-attr">jobs:</span>
   <span class="hljs-attr">build:</span>
     <span class="hljs-comment"># The type of runner that the job will run on</span>
     <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>

     <span class="hljs-comment"># Steps represent a sequence of tasks that will be executed as part of the job</span>
     <span class="hljs-attr">steps:</span>
       <span class="hljs-comment"># Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v3</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">read</span> <span class="hljs-string">.nvmrc</span>
         <span class="hljs-attr">run:</span> <span class="hljs-string">echo</span> <span class="hljs-string">::set-output</span> <span class="hljs-string">name=NVMRC::$(cat</span> <span class="hljs-string">.nvmrc)</span>
         <span class="hljs-attr">id:</span> <span class="hljs-string">nvm</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Setup</span> <span class="hljs-string">node</span> <span class="hljs-string">${{</span> <span class="hljs-string">steps.nvm.outputs.NVMRC</span> <span class="hljs-string">}}</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-node@v3</span>
         <span class="hljs-attr">with:</span>
           <span class="hljs-attr">node-version:</span> <span class="hljs-string">'$<span class="hljs-template-variable">{{ steps.nvm.outputs.NVMRC }}</span>'</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">install</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">build</span>
   <span class="hljs-attr">test:</span>
     <span class="hljs-comment"># The type of runner that the job will run on</span>
     <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>

     <span class="hljs-comment"># Steps represent a sequence of tasks that will be executed as part of the job</span>
     <span class="hljs-attr">steps:</span>
       <span class="hljs-comment"># Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v3</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">read</span> <span class="hljs-string">.nvmrc</span>
         <span class="hljs-attr">run:</span> <span class="hljs-string">echo</span> <span class="hljs-string">::set-output</span> <span class="hljs-string">name=NVMRC::$(cat</span> <span class="hljs-string">.nvmrc)</span>
         <span class="hljs-attr">id:</span> <span class="hljs-string">nvm</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Setup</span> <span class="hljs-string">node</span> <span class="hljs-string">${{</span> <span class="hljs-string">steps.nvm.outputs.NVMRC</span> <span class="hljs-string">}}</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-node@v3</span>
         <span class="hljs-attr">with:</span>
           <span class="hljs-attr">node-version:</span> <span class="hljs-string">'$<span class="hljs-template-variable">{{ steps.nvm.outputs.NVMRC }}</span>'</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">install</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">test</span>
</code></pre>
<p> Let’s break down what we have above:</p>
<ul>
<li><p>These actions will be triggered only when a pull request is raised on the branch develop, we have set this up with the <code>on</code>-property in the file above</p>
</li>
<li><p>As the name suggests, we have two jobs to execute separately, first, we build the project, to achieve the build, we need to install packages, we also set the node version in a <code>.nvmrc</code> file, that’s why we started reading on top of the build and test job scope, then the test job will install, before testing.</p>
</li>
<li><p>I have made an update where we are using .env files, as this file is not pushed on GitHub, you may see your test failing on login or sign-in, to prevent it, you can inject those variables into the GitHub repository, or add a default value to those variables like:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth.service.ts</span>
  ...
  {
      secret:
        <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'JWT_SECRET'</span>) || <span class="hljs-string">'testingEnvSecret'</span>,
  },
  ...
</code></pre>
</li>
</ul>
</li>
</ol>
<p>    Now let’s create a PR, this is what we get:</p>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675404099105/01dff05a-d4e3-44c6-a345-10e67bc269af.png" alt class="image--center mx-auto" /></p>
<p>    <em>image2A - CI in action</em></p>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675404115246/892ebc7e-f1a8-47e0-b78f-b4b63afd3701.png" alt class="image--center mx-auto" /></p>
<p>    <em>image2B - CI in action</em></p>
<p>    As you can see, both of our build and test jobs are working correctly, well done, we have done the CI part of the CI/CD.</p>
<p>    Now, let’s write an action to deploy, from the fact that our CI actions pass correctly, in the CD ones, we will only focus on deploying the app, in the GitHub marketplace, you can find such actions, no need to reinvent the wheel.</p>
<p>    In the same directory, let’s create a <code>deploy.yaml</code> file, like the following:</p>
<pre><code class="lang-yaml">    <span class="hljs-attr">name:</span> <span class="hljs-string">Trigger</span> <span class="hljs-string">Render</span> <span class="hljs-string">Deployment</span>
    <span class="hljs-attr">on:</span>
      <span class="hljs-attr">push:</span>
        <span class="hljs-attr">branches:</span> [<span class="hljs-string">'develop'</span>, <span class="hljs-string">'main'</span>]
    <span class="hljs-attr">jobs:</span>
      <span class="hljs-attr">deploy:</span>
        <span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span> <span class="hljs-string">to</span> <span class="hljs-string">Render</span>
        <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>
        <span class="hljs-attr">steps:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Trigger</span> <span class="hljs-string">deployment</span>
            <span class="hljs-attr">uses:</span> <span class="hljs-string">sws2apps/render-deployment@main</span>
            <span class="hljs-attr">with:</span>
              <span class="hljs-attr">serviceId:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.RENDER_SERVICE_ID</span> <span class="hljs-string">}}</span>
              <span class="hljs-attr">apiKey:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.RENDER_API_KEY</span> <span class="hljs-string">}}</span>
              <span class="hljs-attr">multiple:</span> <span class="hljs-literal">false</span>
</code></pre>
<p>    As you can see here, we are using secrets variables, in the render dashboard, under account settings, click on <code>API Keys</code> and generate a new secret, and save it:</p>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675404145861/06951a0c-3c02-496c-831f-c2644491cf9a.png" alt class="image--center mx-auto" /></p>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675404151104/dcfceb4e-1f47-4e73-b402-f6117938b0c6.png" alt class="image--center mx-auto" /></p>
<p>    image3 - Create a new API key</p>
<p>    Then as you are in the dashboard, select your project, the URL will look like this:</p>
<pre><code class="lang-plaintext">    https://dashboard.render.com/web/RENDER_SERVICE_ID
</code></pre>
<p>    From the URL, retrieve your service id, and save it.</p>
<p>    Now, in the GitHub repository, you need to inject those variables, under Settings → Secrets → Actions, click on <code>New repository secret</code> then add them both</p>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675404206807/bc801843-421f-4244-b73e-a413b9eb4883.png" alt class="image--center mx-auto" /></p>
<p>    <em>image4 - Add repository secrets</em></p>
<p>    🛠️ With that setup, we are good to test our actions.</p>
<ul>
<li><p>Push your changes on GitHub once again</p>
</li>
<li><p>Make sure the CI actions are still passing</p>
</li>
<li><p>Then merge the PR</p>
</li>
<li><p>Wait a couple of minutes until the project deploys, Github will add the deployment link to your repository.</p>
</li>
</ul>
<p>    Well done, our CI and CD actions are working correctly, you have made it 🚀</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this part, we have decided to use Github Actions for our CI/CD implementation for Nest and GraphQL applications, due to its simplicity, keeping in mind that the choice may vary depending on your team and project size. By setting up our pipelines and leveraging the concepts discussed in the previous installment, we will be able to streamline our delivery process and catch errors early on, if any. With GitHub Actions, we can focus on delivering the best possible experience to our end-users, and have peace of mind knowing that our CI/CD processes are working efficiently. The use of GitHub Actions highlights the importance of a streamlined CI/CD process and its positive impact on the overall development process.</p>
<h2 id="heading-additional-resources">Additional resources</h2>
<ul>
<li><p><a target="_blank" href="https://www.redhat.com/en/topics/devops/what-is-ci-cd">What is CI/CD from RedHat</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/marketplace?type=">GitHub Marketplace</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/features/actions">Understand GitHub Actions</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Build a GraphQL API with NestJs and MongoDB, in a modern way - Part 2.]]></title><description><![CDATA[In this article, I'll be discussing testing in general and taking a deep dive into the TDD workflow, applied to a Graphql API using nest.js and jest]]></description><link>https://paclinjanja.hashnode.dev/build-graphql-api-nestjs-mongodb-a-modern-way-part-2-tdd</link><guid isPermaLink="true">https://paclinjanja.hashnode.dev/build-graphql-api-nestjs-mongodb-a-modern-way-part-2-tdd</guid><category><![CDATA[nestjs]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[Jest]]></category><category><![CDATA[Mocking]]></category><dc:creator><![CDATA[Pacifique Linjanja]]></dc:creator><pubDate>Sat, 11 Mar 2023 12:03:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678535171419/23df8d73-91f2-4513-a73f-7fb62e3c85c5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">Overview</h2>
<p>Are you ready to take your GraphQL development skills to the next level? In this series of four articles, I'll guide you through the process of building a powerful GraphQL API using Nest and MongoDB. You'll learn best practices, and see how to scale your app just as you would in a real-world scenario.</p>
<p>First, we'll kick things off by diving into the fundamentals of Nest, a powerful NodeJS framework. We'll set up the foundation for our final project, and by the end, you'll know how to manually deploy your own sample application, if you missed this part, please take a moment to read it here.</p>
<p>Next(current reading), we'll delve into the world of Test Driven Development (TDD) for GraphQL. You'll see the benefits it brings to the development process and learn how to test your current resolvers and implement new ones using this approach.</p>
<p>In the third installment, we'll explore how to apply Continuous Integration and Continuous Deployment (CI/CD) to Nest and GraphQL apps. We'll create our pipelines and, building off the concepts from the second part, you'll see the true power of this approach in action. Once set up, you won't have to worry as much about delivering to the frontend team, and you'll be able to catch errors even before the app is shipped to client apps.</p>
<p>Finally, in the fourth and final installment, we'll take things up a notch by adding features that will introduce you to the world of micro-services. You'll learn how to break down your monolithic app into smaller, independent micro-services without disrupting any existing functionality. This is the modern approach, saving you from the headache of long, drawn-out migrations. So, let's get started and take your GraphQL development skills to the next level!</p>
<p>The full source code can be found <a target="_blank" href="https://github.com/pacyL2K19/graphql-mongodb-nestjs-tuto/tree/part-2">here(part-2)</a> branch.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To fully benefit from this series, it's important you have read the <a target="_blank" href="https://paclinjanja.hashnode.dev/graphql-api-nestjs-mongodb-a-modern-way-part-1">first part</a> of the series, and have a basic knowledge of NodeJS, <a target="_blank" href="https://www.apollographql.com/blog/graphql/basics/graphql-vs-rest/"><strong>GraphQL</strong></a>, <a target="_blank" href="https://docs.nestjs.com/"><strong>NestJS</strong></a>, <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html"><strong>TypeScript</strong></a>, and <a target="_blank" href="https://www.mongodb.com/docs/manual/tutorial/getting-started/"><strong>MongoDB</strong></a>. However, even if you're new to these technologies, don't worry - this series will provide a comprehensive overview of our stack, including the most crucial aspects we'll be using along the way.</p>
<h2 id="heading-what-is-tdd"><strong>What is TDD?</strong></h2>
<p>TDD stands for Test-Driven Development. It is a software development approach where tests are written before the implementation of the corresponding code. This means that the developer writes tests that will fail until the implementation is done. The tests serve as a way to specify the requirements of the code and ensure that it works as expected.</p>
<p>In the context of building a GraphQL API using NestJS, TDD can be used to write tests for the resolvers, services, and other components of the application. The tests can be used to check that the resolvers are correctly handling the GraphQL queries and mutations, that the services are interacting with the database correctly, and that the overall application is working as expected.</p>
<p>TDD is a good practice for building software, it can help ensure that the code is working correctly and it makes the development process more efficient and more productive, it also makes it easier to refactor the code and add new features.</p>
<p>The TDD workflow can be resumed as the following diagram:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675402737376/36bc54cd-9187-437c-aa93-bb1692a18e5e.png" alt class="image--center mx-auto" /></p>
<p><em>image1 - TDD workflow</em></p>
<p>From this diagram, we understand that we should adapt our code logic the way they pass the tests we first wrote, and should implement new test cases only when the ones we currently have passed the tests. Let’s see this in practice.</p>
<h2 id="heading-advantages-of-tdd">Advantages of TDD</h2>
<p>If you ever wonder, before we get started with the actual implementations, here are a few advantages of using the TDD approaches in your next projects:</p>
<ol>
<li><p><strong>Improves code quality and maintainability</strong>: TDD helps ensure that the code is written in a modular, scalable, and maintainable manner by requiring developers to break down complex functionality into smaller, testable units, this is what we did earlier by splitting the authentication features into small methods in our auth module.</p>
</li>
<li><p><strong>Early detection of bugs and regressions</strong>: By writing test cases before writing the actual implementation, TDD allows developers to catch bugs and regressions early in the development cycle, which can save time and resources.</p>
</li>
<li><p><strong>Increases confidence in code changes</strong>: TDD provides a safety net for developers, allowing them to make changes to their code with confidence, knowing that their tests will alert them if anything breaks.</p>
</li>
<li><p><strong>Better documentation of code</strong>: Writing test cases forces developers to think through how their code should behave and what the expected outputs are, which can serve as documentation for future reference.</p>
</li>
<li><p><strong>Facilitate design and architecture improvemen</strong>t: TDD can help drive the design and architecture of a GraphQL API, as developers write tests to ensure that the API meets the requirements and behaves as expected.</p>
</li>
</ol>
<p>Here are some examples:</p>
<ul>
<li><p>Writing a test to ensure that a query returns the expected data, such as checking that a query for all books returns a list of books with the correct titles, authors, and publication dates.</p>
</li>
<li><p>Writing a test to ensure that a mutation updates the data correctly, such as checking that a mutation to add a new book to the database correctly updates the list of books returned by a query.</p>
</li>
<li><p>Writing a test to ensure that a query or mutation fails with the correct error message when invalid data is passed in, such as checking that a query for a book with an invalid ID returns a "Book not found" error, or if a user already exists, by returning an exception, etc.</p>
</li>
</ul>
<p>Let’s see it all in practice by testing all our existing code logic.</p>
<h2 id="heading-test-existing-resolvers">Test existing resolvers</h2>
<ol>
<li><p><strong>Prepare the environment</strong></p>
<p> Even though Nest has made a basic testing setup with jest, we need to make a few improvements to what already exists, our environment doesn’t know anything about our database, or configuration such as helper modules(configModules, or jwtModule).</p>
<p> Let’s go step by step:</p>
<ul>
<li><p>Make sure we are at the same starting point, checking out <code>#c4aa72</code></p>
</li>
<li><p>Taking a look at the <code>user.service.specs.ts</code> file, this is what we currently have:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// app/user/user.service.spec.ts</span>

  <span class="hljs-keyword">import</span> { Test, TestingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/testing'</span>;
  <span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./user.service'</span>;

  describe(<span class="hljs-string">'UserService'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">let</span> service: UserService;

    beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> <span class="hljs-keyword">module</span>: TestingModule = await Test.createTestingModule({
        providers: [UserService],
      }).compile();

      service = <span class="hljs-built_in">module</span>.get&lt;UserService&gt;(UserService);
    });

    it(<span class="hljs-string">'should be defined'</span>, <span class="hljs-function">() =&gt;</span> {
      expect(service).toBeDefined();
    });
  });
</code></pre>
<p>  From what we have, Nest has set up a testing file with only one provider, but having a look at our <code>user.service.ts</code> file, we can see that the user service requires more than one dependency which is the UserService, and ConfigService, update the <code>providers</code> properties with:</p>
<pre><code class="lang-typescript">  ...
  providers: [UserService, ConfigService],
  ...
</code></pre>
<p>  We need our tests to be executed as fast as possible, so we can’t use a real database, instead, we will use a mocked database. The mockup setup we've got <a target="_blank" href="https://docs.nestjs.com/techniques/mongodb#testing">here from Nest is just a basic one</a>. With it, we won't be able to utilize methods like <code>save()</code> or <code>exec()</code> unless we set up proper mock functions using Jest(we will explore the jest mocking function later on). Personally, when testing services that use Mongoose, I prefer to simulate the functions without any hassle, which is why I use <a target="_blank" href="https://www.npmjs.com/package/mongodb-memory-server">mongodb-memory-server.</a> Let's go ahead and install it and configure it smoothly on our server.</p>
<p>  First, let’s install the required packages</p>
<pre><code class="lang-bash">  <span class="hljs-comment"># install packages</span>
  $ yarn add -D mongodb-memory-server
</code></pre>
<p>  Then let’s create a way for NestJS to use it in our tests. In our common folder, let’s create a folder called <code>helpers</code> with the file named <code>mongoose.helper.ts</code>  with the following:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// app/common/helpers/mongoose.helper.ts</span>

  <span class="hljs-keyword">import</span> { MongooseModule, MongooseModuleOptions } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;
  <span class="hljs-keyword">import</span> { MongoMemoryServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongodb-memory-server'</span>;

  <span class="hljs-keyword">let</span> mongo: MongoMemoryServer;

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> rootMongooseTestModule = <span class="hljs-function">(<span class="hljs-params">options: MongooseModuleOptions = {}</span>) =&gt;</span>
    MongooseModule.forRootAsync({
      useFactory: <span class="hljs-keyword">async</span> () =&gt; {
        mongo = <span class="hljs-keyword">await</span> MongoMemoryServer.create();
        <span class="hljs-keyword">const</span> mongoUri = mongod.getUri();
        <span class="hljs-keyword">return</span> {
          uri: mongoUri,
          ...options,
        };
      },
    });

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> closeInMongodConnection = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">if</span> (mongo) <span class="hljs-keyword">await</span> mongo.stop();
  };
</code></pre>
<p>  With this setup, we’ll be able to use native mongoose methods, without any need to over-mocking them.</p>
<p>  Now, let’s update the way we set up the TestingModule, in our <code>user.service.spec.ts</code> file:</p>
<pre><code class="lang-typescript">  ...

  imports: [
    rootMongooseTestModule(),
    ConfigModule.forRoot(),
    MongooseModule.forFeature([
      {
        name: User.name,
        schema: UserSchema,
      },
    ]),
  ],
  ...
</code></pre>
<p>  The <code>rootMongooseModule</code> is imported from the helper we just created.</p>
<p>  Now, what do we really need? We need 2 different things when we are using this mocked database:</p>
<ul>
<li><p>Before all test cases execution, we need to connect to it</p>
</li>
<li><p>After all test cases execution, we close the connection</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>        This will ensure that even if we have multiple files using the mocked database, none of them will interfere with the correct fullness of another, this is the purpose of unit testing.</p>
<p>        With that being said, we need to change the <strong>beforeEach</strong> to <strong>beforeAll</strong>, and add an <strong>afterAll</strong> hook to our testing files, you can read about jest hooks <a target="_blank" href="https://jestjs.io/docs/setup-teardown">here</a> for more details.</p>
<p>        After this update, this is how our file will look like:</p>
<pre><code class="lang-typescript">        <span class="hljs-comment">// app/user/user.service.spec.ts</span>

        ...
            <span class="hljs-keyword">let</span> service: UserService;
          <span class="hljs-keyword">let</span> <span class="hljs-keyword">module</span>: TestingModule;

          beforeAll(async () =&gt; {
            <span class="hljs-keyword">module</span> = await Test.createTestingModule({
              imports: [
                rootMongooseTestModule(),
                ConfigModule.forRoot(),
                MongooseModule.forFeature([
                  {
                    name: User.name,
                    schema: UserSchema,
                  },
                ]),
              ],
              providers: [UserService, ConfigService],
            }).compile();

            service = <span class="hljs-built_in">module</span>.get&lt;UserService&gt;(UserService);
          });

          afterAll(<span class="hljs-keyword">async</span> () =&gt; {
            <span class="hljs-keyword">if</span> (<span class="hljs-keyword">module</span>) {
              <span class="hljs-keyword">await</span> <span class="hljs-built_in">module</span>.close();
              <span class="hljs-keyword">await</span> closeInMongodConnection();
            }
          });
        ...
</code></pre>
<p>        You can see that we have made small changes in the way we set up TestingModule for the user module, now let’s try to run tests on this file again, and see what we get.</p>
<p>        Running <code>yarn test src/app/user/user.service.ts</code> from the root of the project, you may notice this error:</p>
<pre><code class="lang-bash">        $ jest src/app/user/user.service.spec.ts
         FAIL  src/app/user/user.service.spec.ts
          ● Test suite failed to run

            Cannot find module <span class="hljs-string">'src/app/book/entities/book.entity'</span> from <span class="hljs-string">'app/user/entities/user.entity.ts'</span>

            Require stack:
              app/user/entities/user.entity.ts
              app/user/user.service.spec.ts

              2 | import { Document, Schema as MongooSchema } from <span class="hljs-string">'mongoose'</span>;
              3 | import { Prop, Schema, SchemaFactory } from <span class="hljs-string">'@nestjs/mongoose'</span>;
            &gt; 4 | import { Book } from <span class="hljs-string">'src/app/book/entities/book.entity'</span>;
                | ^
              5 |
              6 | @ObjectType()
              7 | @Schema()

              at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:425:11)
              at Object.&lt;anonymous&gt; (app/user/entities/user.entity.ts:4:1)
              at Object.&lt;anonymous&gt; (app/user/user.service.spec.ts:1:1)

        Test Suites: 1 failed, 1 total
        Tests:       0 total
        Snapshots:   0 total
        Time:        5.206 s, estimated 8 s
        Ran all <span class="hljs-built_in">test</span> suites matching /src\\/app\\/user\\/user.service.spec.ts/i.
</code></pre>
<p>        Which is weird, since our imports are correct right? If you are not running into this error, don’t take any further action, you are good to go, but for anyone running into this, we will need to specify to jest what is the root directory of our project, or simply change the way we import modules in our project from <code>src/something/...</code> to <code>../../something/...</code> we can fix it by changing everywhere we have imported files using absolute path, another way is making changes under <code>jest</code> property in the <code>package.json</code> file:</p>
<pre><code class="lang-json">        <span class="hljs-string">"jest"</span>: {
            <span class="hljs-attr">"moduleFileExtensions"</span>: [
              <span class="hljs-string">"js"</span>,
              <span class="hljs-string">"json"</span>,
              <span class="hljs-string">"ts"</span>
            ],
            <span class="hljs-attr">"rootDir"</span>: <span class="hljs-string">"src"</span>,
            <span class="hljs-attr">"testRegex"</span>: <span class="hljs-string">".*\\\\.spec\\\\.ts$"</span>,
            <span class="hljs-attr">"transform"</span>: {
              <span class="hljs-attr">"^.+\\\\.(t|j)s$"</span>: <span class="hljs-string">"ts-jest"</span>
            },
            <span class="hljs-attr">"moduleNameMapper"</span>: {
              <span class="hljs-attr">"^src/(.*)$"</span>: <span class="hljs-string">"&lt;rootDir&gt;/$1"</span>
            },
            <span class="hljs-attr">"collectCoverageFrom"</span>: [
              <span class="hljs-string">"**/*.(t|j)s"</span>,
              <span class="hljs-string">"!main.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.module.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.input.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.entity.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.guards.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.response.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.strategy.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.args.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.helper.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.types.(t|j)s"</span>,
              <span class="hljs-string">"!**/*.helpers.(t|j)s"</span>,
              <span class="hljs-string">"!**/node_modules/**"</span>
            ],
            <span class="hljs-attr">"coverageDirectory"</span>: <span class="hljs-string">"../coverage"</span>,
            <span class="hljs-attr">"coverageThreshold"</span>: {
              <span class="hljs-attr">"global"</span>: {
                <span class="hljs-attr">"branches"</span>: <span class="hljs-number">75</span>,
                <span class="hljs-attr">"functions"</span>: <span class="hljs-number">50</span>,
                <span class="hljs-attr">"lines"</span>: <span class="hljs-number">75</span>,
                <span class="hljs-attr">"statements"</span>: <span class="hljs-number">75</span>
              }
            },
            <span class="hljs-attr">"testEnvironment"</span>: <span class="hljs-string">"node"</span>
          }
</code></pre>
<p>        With the <code>moduleWrapper</code> property, we are telling Jest how to resolve module paths, now modules that start with <code>src/</code> will be looked into <code>&lt;rootDir&gt;/</code>, which is the <code>src</code>  folder by default (this is configured a few lines above).</p>
<p>        in the <code>collectCoverageFrom</code> property, we are specifying which files will be considered when we will track the coverage of our codes, we are telling jest to avoid all the entities. guards, strategies, types, helpers, and args files when tracking the coverage. Then in the <code>coverageThreshold</code> property, we are defining our targets, thus, we are targeting 75% of branches covered(any time you create an if/else statement or switch/case you create a branch in the jest context), 50% of functions, 75% of lines, and 75% of statements, this will serve as metrics to judge how well-covered or code base is covered.</p>
<p>        With this setup, we are good to go for implementing our unit tests and testing again the user.service file and make sure it doesn’t show any errors.</p>
<p>        Kudos, we have set up our testing for the service file, now you can update the book, author, and auth service files the same way, for the auth service, don’t forget to add the mock of the user entity as we will be interacting with the user collection to test the authentication feature.</p>
<blockquote>
<p>You can check out <code>#16826</code> to have the required setup before we follow.</p>
</blockquote>
<p>        Let’s properly test our service …</p>
<ol>
<li><p><strong>Test your service files</strong></p>
<p> I will use <code>Chance</code> utility functions to create mocking values, feel free to use any tool of your choice.</p>
<p> Let’s prepare for data to use while testing, by adding the code below on top of the user.service.spec file, after installing the <a target="_blank" href="https://www.npmjs.com/package/chance">“chance”</a> package.</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// app/user/user.service.spec.ts</span>

 <span class="hljs-comment">// imports</span>
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> Chance <span class="hljs-keyword">from</span> <span class="hljs-string">'chance'</span>
 ...
 <span class="hljs-keyword">const</span> UPDATED_ADDRESS_LENGTH = <span class="hljs-number">15</span>;
 <span class="hljs-keyword">const</span> ADDRESS_LENGTH = <span class="hljs-number">20</span>;

 <span class="hljs-keyword">const</span> chance = <span class="hljs-keyword">new</span> Chance();
 <span class="hljs-keyword">let</span> userId = <span class="hljs-string">''</span>;

 <span class="hljs-keyword">const</span> createUserInput: CreateUserInput = {
   name: chance.name(),
   password: <span class="hljs-string">'FakePassword1?'</span>,
   address: chance.string({ length: ADDRESS_LENGTH }),
   email: chance.email(),
 };

 <span class="hljs-keyword">const</span> updateUserInput: UpdateUserInput = {
   _id: <span class="hljs-keyword">new</span> MongooSchema.Types.ObjectId(<span class="hljs-string">''</span>),
   name: chance.name(),
   address: chance.string({ length: UPDATED_ADDRESS_LENGTH }),
 };
 ...
 <span class="hljs-comment">// testing scopes</span>
</code></pre>
<p> We have created the <code>createUserInput</code> and the <code>updateUserInput</code> dtos, which will help us test our mocking database.</p>
<p> Now, let’s test the most simple one, the create user method in the user.service file, here is how we can test it:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// test case one: create a user</span>

 ...
 it(<span class="hljs-string">'should create a user with createUserInput'</span>, <span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> service.createUser(createUserInput);
     expect(user.id).toBeDefined();
     expect(user.name).toBe(createUserInput.name);
     expect(user.address).toBe(createUserInput.address);
     expect(user.email).toBe(createUserInput.email);
     expect(user.password).not.toBeNull();
     updateUserInput._id = user._id;
     userId = user.id;
  });
 ...
</code></pre>
<p> Here we are simulating the creation of the user, then we start asserting what we should get, we expect that the user’s name should be the same as the one we have in the <code>createUserInput</code> after creation for example. In this use case, we can test as many assertions as possible, but to be able to get the advantage of this process, we will test only the cases that give us confidence in our code.</p>
<p> You can write and watch your changes with <code>$ yarn test:watch</code> Next, in our user.service file, we would like to test the ability to update a user using the <code>updateUserInput</code> dto, get the list of users paginated, get a user by his email, and remove the user, here is how our user.service.spec file may look like, after testing all these cases:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403025717/6a33729d-0fed-4963-b427-89341b1901e4.png" alt class="image--center mx-auto" /></p>
<p> <em>image2 - user.service.spec.ts file</em></p>
<p> 🛠️ <strong>Try to replicate it on your end as above. We have tested all the methods in the user.service, let’s run the test on the user.service.spec.ts file again and see what we get:</strong></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403085146/2400de8d-fa58-4678-8bbc-b9d123da0d31.png" alt class="image--center mx-auto" /></p>
<p> <em>image3 - unit tests on the user.service.ts file</em></p>
<p> Now let’s see how covered our code is:</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># run this in the terminal</span>
 $ yarn <span class="hljs-built_in">test</span>:cov
</code></pre>
<p> Here is what we get:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403208408/021bc933-bfde-4a53-9079-bea5f31af4d4.png" alt class="image--center mx-auto" /></p>
<p> <em>image4 - coverage of the user.service file</em></p>
<p> As you can see, we have just tested the user.service.ts file, and it’s getting better in terms of coverage.</p>
<p> We will do the same for the other service files, as we did for the user.</p>
<p> 🛠️ <strong>Code along and try to add much more test cases, if you feel I forgot some</strong></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403274542/ce7ed83f-4fd1-419b-9fd2-1fcd46cec1f1.png" alt class="image--center mx-auto" /></p>
<p> <em>image5A - author.service.spec.ts</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403351768/bb3c91f9-221d-40f1-9717-7842d6a25b5f.png" alt class="image--center mx-auto" /></p>
<p> <em>image5B - book.service.ts file</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403399311/92a18cab-e1e2-4124-9843-ee35073ff6e9.png" alt class="image--center mx-auto" /></p>
<p> <em>image5C - auth.service.ts file</em></p>
<p> Here are some we have tested our service files, however, a few aspects need to be clarified:</p>
<ul>
<li><p>In the book.service.spec.ts file, we didn’t only use the book model, but also the author and user models, and when we set up the MongooseModule, here is what we did:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// book.service.spec.ts</span>

  ...
  MongooseModule.forFeature([
    {
       name: Book.name,
       schema: BookSchema,
    },
    {
       name: Author.name,
       schema: AuthorSchema,
    },
    {
       name: User.name,
       schema: UserSchema,
    },
  ]),
  ...
</code></pre>
<p>  Remember that when we create a book, we need to specify the author’s id, also, when we get a book, we populate the <code>readers</code> and the <code>author</code> fields, using a generated ObjectId couldn’t work because in the context of our mocked database, that generated objectId wouldn’t have all the required properties a reader or an author have, so before testing a book creation, notice that we first created an author(line 85) before the book, this places us in a real-world scenario where it’s impossible to have a book without an author :) like we couldn’t have Bitcoin without Satoshi Nakamoto 😜.</p>
<p>  🛠️ Take some moment to write these tests on your own before comparing them to the version at <code>#354c1</code></p>
</li>
<li><p>In the auth.service.spec.ts file, we have also injected the <code>JwtModule</code> and its service file, in addition to the UserModule and the ConfigModule, the reason, as you may guess is because the logic that generates token his held by in the JwtService.</p>
</li>
</ul>
</li>
</ol>
<p>        Well done, now check the coverage again and notice that we have made huge progress.</p>
<p>        In the next section, let’s test our resolvers. By testing service files first, we have used the “Bottom Up” principle, knowing that our resolvers only use methods from the service file, testing resolvers will be much simpler.</p>
<ol>
<li><p><strong>Test your resolvers</strong></p>
<p> To test resolver logic, assuming that our services are already tested, we won’t test them again, instead, we will mock them using a <a target="_blank" href="https://jestjs.io/docs/mock-functions#mock-return-values">mocking function from jest</a>. The idea behind is to simulate what should a well-written method from the service file should return. For example, in the user.service file, our createUser should return this a user object, which is the <code>createUserInput</code> where we added an <code>_id</code> property. Confusing? Let me get you covered, see what we have as a mocking function for the createUser method from <code>user.service.ts</code> :</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// user.resolver.spec.ts</span>

 <span class="hljs-keyword">const</span> createUserInput: CreateUserInput = {
   name: chance.name(),
   password: <span class="hljs-string">'FakePassword1?'</span>,
   address: chance.string({ length: ADDRESS_LENGTH }),
   email: chance.email(),
 };

 ...
     useValue: {
         createUser: jest.fn(<span class="hljs-function">() =&gt;</span> {
           <span class="hljs-keyword">return</span> {
              _id: userId,
              ...createUserInput,
            };
         }),
         ...
         <span class="hljs-comment">// other mocking functions</span>
 ...
</code></pre>
<p> As you can see here, we are telling jest to mock for us a provider method called <code>createUser</code> that will be consumed by our resolver, makes more sense right?</p>
<p> Now, let’s test the createUser method from our resolver:</p>
<p> The way we will test our resolver methods will be much similar to how we tested their corresponding service files, here is, for example, the tests for the <code>createUser</code> under our resolver:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// app/user/user.resolver.ts</span>

 ...
 it(<span class="hljs-string">'should be able to create a user'</span>, <span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> resolver.createUser(createUserInput);
     expect(user._id).toBeDefined();
     expect(user._id).toBe(userId);
     expect(user.name).toBe(createUserInput.name);
     expect(user.email).toBe(createUserInput.email);
     expect(user.address).toBe(createUserInput.address);
     userId = user._id;
     updateUserInput._id = user._id;
 });
 ...
</code></pre>
<p> As you can see, it is very similar to what we did, of cause we are just making sure that from the input we give(which will come from args), we can get data that our mocking functions return, for this test case, the mocking function returns <code>{ _id: userId, ...createUserInput</code></p>
<p> Well, for the rest of methods, here is how we can implement the testing:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403607268/22354cfd-483b-4136-b7af-f16d0a17d239.png" alt class="image--center mx-auto" /></p>
<p> <em>image6 - user.resolver.spec.ts file</em></p>
<p> As you can see above, we first mocked the functions that are supposed to come from our service file, then we tested the resolver methods, just the same way we tested the service ones, that’s the benefit of the “Bottom Up” approach we described above.</p>
<p> 🛠️ Take some time to test the book, author, and auth resolvers and double-check checking out <code>#258af</code></p>
</li>
<li><p><strong>End-To-End testings</strong></p>
<p> Until now, we have only tested blocks of codes separately, and we haven’t tested the nest decorators such as <code>@Query</code> or <code>@Mutation</code>. In this section, I get you covered, before we move into the TDD workflow.</p>
<p> Let’s see how we can test the <code>GetHello</code> query as the simplest one:</p>
<p> By default, nest installs <code>supertest</code> package for us, this package will help us simulate HTTP requests.</p>
<p> As you now know, all the graphql requests(mutations and queries) are just POST requests to the entry point of the app which is <code>/graphql</code></p>
<p> From a client app(as our e2e test will simulate clients’ requests), let’s see what we send:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403563227/0ec52556-fe9d-429e-9f5a-ea4b3e87ee0e.png" alt class="image--center mx-auto" /></p>
<p> <em>image7 - graphql requests</em></p>
<p> As you can see here, our <strong>graphql query</strong> is sent as a string in the query of the http request, and we are sending variables using the “variables” property. To simulate this, let’s create helper files that will hold these parameters for us:</p>
<p> Under <code>src/app/common/helpers/graphql.helper.ts</code> add this content:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GRAPHQL_ENDPOINT = <span class="hljs-string">'/graphql'</span>;
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> HELL0_WORLD = <span class="hljs-string">'Hello World!'</span>;

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_HELLO_OPERATION_NAME = <span class="hljs-string">'Query'</span>;

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_HELLO = <span class="hljs-string">`query Query {
   getHello
 }`</span>;
</code></pre>
<p> As you can see above, the GET_HELLO string will contain the <strong>graphql operation</strong> as a string, just like what we have in our Apollo playground.</p>
<p> Update the <code>app.e2e.spec.ts</code> file with the following code:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// test/app.e2e.spec.ts</span>

 <span class="hljs-keyword">import</span> { Test, TestingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/testing'</span>;
 <span class="hljs-keyword">import</span> { INestApplication } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">'supertest'</span>;
 <span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'../src/app/app.module'</span>;
 <span class="hljs-keyword">import</span> {
   GET_HELLO,
   GET_HELLO_OPERATION_NAME,
   GRAPHQL_ENDPOINT,
   HELL0_WORLD,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'../src/app/common/helpers/graphql.helper'</span>;

 jest.setTimeout(<span class="hljs-number">70000</span>);

 describe(<span class="hljs-string">'AppResolver (e2e)'</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">let</span> app: INestApplication;

   beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">const</span> moduleFixture: TestingModule = <span class="hljs-keyword">await</span> Test.createTestingModule({
       imports: [AppModule],
     }).compile();

     app = moduleFixture.createNestApplication();
     <span class="hljs-keyword">await</span> app.init();
   });

   afterEach(<span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">await</span> app.close();
   });

   it(<span class="hljs-string">'should get a hello world'</span>, <span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">return</span> request(app.getHttpServer())
       .post(GRAPHQL_ENDPOINT)
       .send({
         operationName: GET_HELLO_OPERATION_NAME,
         query: GET_HELLO,
       })
       .expect(<span class="hljs-number">200</span>)
       .expect(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
         expect(res.body.data.getHello).toBe(HELL0_WORLD);
       });
   });
 });
</code></pre>
<p> We have set up a timeout to 70000ms, sometimes you can experience timeout especially because we have made integration tests, which can be an addition of more than one method executed together.</p>
<p> We have used <code>request</code> methods from supertest to simulate HTTP requests, don’t hesitate to read more about <a target="_blank" href="https://github.com/ladjs/supertest">supertest,</a> a very popular and powerful tool for testing HTTP assertion on nodejs servers, with supertest, you can simulate a post, get, put, patch request. Here we will only use post(to simulate a post request) with its callbacks like <code>send()</code> <code>expect()</code> etc.</p>
<p> Now let’s see how we can test a user creation</p>
<p> First, let’s add helpers with operation names, variables, mutations, etc Under <code>app/common/helpers/create-user.helper.ts</code> file, just paste this:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// app/common/helpers/create-user.helper.ts</span>

 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> Chance <span class="hljs-keyword">from</span> <span class="hljs-string">'chance'</span>;
 <span class="hljs-keyword">const</span> chance = <span class="hljs-keyword">new</span> Chance();

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> CREATE_USER_OPERATION_NAME = <span class="hljs-string">'CreateUser'</span>;
 <span class="hljs-keyword">const</span> UPDATED_ADDRESS_LENGTH = <span class="hljs-number">15</span>;
 <span class="hljs-keyword">const</span> ADDRESS_LENGTH = <span class="hljs-number">20</span>;

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> CREATE_USER_MUTATION = <span class="hljs-string">`mutation CreateUser($createUserInput: CreateUserInput!) {
   createUser(createUserInput: $createUserInput) {
     _id
     address
     email
     name
     password
   }
 }`</span>;

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> generateCreateUserVariables = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">return</span> {
     createUserInput: {
       name: chance.name(),
       password: <span class="hljs-string">'FakePassword1?'</span>,
       address: chance.string({ length: ADDRESS_LENGTH }),
       email: chance.email(),
     },
   };
 };
</code></pre>
<p> As you can see here, we have created all the pieces that are required to send requests such as variables, graphql operations, etc.</p>
<p> The <code>CREATE_USER_MUTATION</code> is written just like a client app would query our API in the future, specifying what we need to have in the response.</p>
<p> Now, let’s create a file for testing the user resolvers end to end, under <code>test</code> folder, let’s add the <code>user.e2e.spec.ts</code> file, and past there this:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">import</span> { Test, TestingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/testing'</span>;
 <span class="hljs-keyword">import</span> { INestApplication } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">'supertest'</span>;
 <span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'../src/app/app.module'</span>;
 <span class="hljs-keyword">import</span> { GRAPHQL_ENDPOINT } <span class="hljs-keyword">from</span> <span class="hljs-string">'../src/app/common/helpers/graphql.helper'</span>;
 <span class="hljs-keyword">import</span> {
   CREATE_USER_MUTATION,
   CREATE_USER_OPERATION_NAME,
   generateCreateUserVariables,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'../src/app/common/helpers/create-user.helper'</span>;
 <span class="hljs-keyword">import</span> { User } <span class="hljs-keyword">from</span> <span class="hljs-string">'../src/app/user/entities/user.entity'</span>;

 jest.setTimeout(<span class="hljs-number">70000</span>);

 describe(<span class="hljs-string">'User resolver (e2e)'</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">let</span> app: INestApplication;
   <span class="hljs-keyword">let</span> user: User;

   beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">const</span> moduleFixture: TestingModule = <span class="hljs-keyword">await</span> Test.createTestingModule({
       imports: [AppModule],
     }).compile();

     app = moduleFixture.createNestApplication();
     <span class="hljs-keyword">await</span> app.init();
   });

   afterEach(<span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">await</span> app.close();
   });

   it(<span class="hljs-string">'Should create an user with user mutation'</span>, <span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> createUserInput = generateCreateUserVariables().createUserInput;
     <span class="hljs-keyword">return</span> request(app.getHttpServer())
       .post(GRAPHQL_ENDPOINT)
       .send({
         operationName: CREATE_USER_OPERATION_NAME,
         query: CREATE_USER_MUTATION,
         variables: { createUserInput },
       })
       .expect(<span class="hljs-number">200</span>)
       .expect(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
         expect(res.body.data.createUser).toBeDefined();
         user = res.body.data.createUser;
         expect(user._id).toBeDefined();
         expect(user.name).toBe(createUserInput.name);
         expect(user.email).toBe(createUserInput.email);
         expect(user.address).toBe(createUserInput.address);
       });
   });
 });
</code></pre>
<p> Looks similar to what we had before right?</p>
<p> We are expecting to receive a 200 status, and the response we get will have a <a target="_blank" href="http://body.data"><code>body.data</code></a> object with the payload of the response.</p>
<p> Now, let’s run our e2e tests:</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># run end-to-end tests</span>
 $ yarn <span class="hljs-built_in">test</span>:e2e
</code></pre>
<p> If you were following, you will be able to get something similar to:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403648510/05d00079-3b4c-45a6-9d13-4db91e3fc341.png" alt class="image--center mx-auto" /></p>
<p> <em>image8 - e2e tests</em></p>
<p> 🛠️ Now try to replicate the same process by creating e2e tests for the updateUser, removeUser, and getUser features. You can see results checking out #eef3fd to compare with your implementation</p>
</li>
</ol>
<p>Buckle up! We've just nailed the unit testing of our services and resolvers and even added some slick end-to-end tests. Time to witness the magic of TDD in action. Are you ready for liftoff?</p>
<h2 id="heading-from-the-existing-workflow-to-tdd"><strong>From the existing workflow to TDD</strong></h2>
<p>Now that we have our API covered at more than 75%, let’s see how we can add a new feature using the TDD approach.</p>
<p>We will add a <code>buyBook</code> feature, so that, a user can purchase a book, and be among readers for the specific book.</p>
<p>What if a user tries to purchase a book that he already has? Let’s cover all these user cases first in our tests, before implementing the logic.</p>
<p>This is the workflow we’ll use to implement this new feature, using the “Bottom Up” approach:</p>
<ul>
<li><p>We first write the unit test in the <code>book.service.spec.ts</code> file</p>
</li>
<li><p>Then we validate those tests by refactoring our <code>book.service.ts</code> file</p>
</li>
<li><p>Then, once our service methods are covered, we write tests for the resolvers</p>
</li>
<li><p>And at the end, we refactor our resolvers to validate the tests.</p>
</li>
</ul>
<p>Let’s get started:</p>
<p>In the <code>book.service.spec.ts</code> file, let’s add assumptions for this feature:</p>
<ul>
<li><p>A user should be able to buy a new book</p>
</li>
<li><p>A user shouldn’t be allowed to buy more than one copy of the same book</p>
</li>
<li><p>A user can buy more than one different books</p>
</li>
</ul>
<p>In terms of code, here is how we can write them:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// app/book/book.service.spec.ts</span>

...
<span class="hljs-comment">// inside the main describe scope, I have added this scope</span>

  describe(<span class="hljs-string">'User purchase features'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">let</span> user: User;
    beforeAll(<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-comment">// First we create a user who will purchase the book</span>
      user = <span class="hljs-keyword">await</span> userService.createUser(createUserInput);
    });

    it(<span class="hljs-string">'should allow a user to buy one specific book, and be among readers for the book'</span>, <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> updatedBook: Book = <span class="hljs-keyword">await</span> service.buyBook({
        bookId: updateBookInput._id,
        userId: user._id,
      });

      expect(updatedBook.readers.length).toBe(<span class="hljs-number">1</span>);
      expect(updatedBook.readers[<span class="hljs-number">0</span>].name).toBe(user.name);
    });

    it(<span class="hljs-string">'should not allow a user to buy more than one copy of the same book'</span>, <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">await</span> service.buyBook({
          bookId: updateBookInput._id,
          userId: user._id,
        });
      } <span class="hljs-keyword">catch</span> (error) {
        expect(error).toBeDefined();
        expect(error.message).toBeDefined();
        expect(error.message).toBe(
          CANNOT_PURCHASE_MORE_THAN_ONE_COPY_EXCEPTION,
        );
      }
    });

    it(<span class="hljs-string">'should allow a user to buy more than one different books'</span>, <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> newBook = <span class="hljs-keyword">await</span> service.createBook({
        ...createBookInput,
        author: author._id,
        isbn: <span class="hljs-string">'234ESJJ'</span>, <span class="hljs-comment">// To avoid having the same isbn, violating a unique constraint we put in the schema</span>
      });

      <span class="hljs-keyword">const</span> updatedBook: Book = <span class="hljs-keyword">await</span> service.buyBook({
        bookId: newBook._id,
        userId: user._id,
      });

      expect(updatedBook.readers.length).toBe(<span class="hljs-number">1</span>);
      expect(updatedBook.readers[<span class="hljs-number">0</span>].name).toBe(user.name);
    });
  });
...
</code></pre>
<p>As you can see here, we are trying to get access to the <code>buyBook</code> method inside our service that we haven’t implemented, also, on top of the new scope, I have created a new <code>beforeAll</code> hook, so that I can create a user before testing an purchase case.</p>
<p>Also notice that I have created a global <code>author</code> variable, instead of the one we had, and updated a little bit the main <code>beforeAll</code> hook like following:</p>
<pre><code class="lang-typescript">  beforeAll(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">module</span> = await Test.createTestingModule({
      providers: [BookService, AuthorService, AuthorModule],
      imports: [
        rootMongooseTestModule(),
        ConfigModule.forRoot(),
        AuthorModule,
        UserModule,
        MongooseModule.forFeature([
          {
            name: Book.name,
            schema: BookSchema,
          },
          {
            name: Author.name,
            schema: AuthorSchema,
          },
          {
            name: User.name,
            schema: UserSchema,
          },
        ]),
      ],
    }).compile();

    service = <span class="hljs-built_in">module</span>.get&lt;BookService&gt;(BookService);
    authorService = <span class="hljs-built_in">module</span>.get&lt;AuthorService&gt;(AuthorService);
    userService = <span class="hljs-built_in">module</span>.get&lt;UserService&gt;(UserService);
    <span class="hljs-comment">// We first create a new author, otherwise it will throw an error by using the generated one</span>
    author = <span class="hljs-keyword">await</span> authorService.create(createAuthorInput);
  });
</code></pre>
<p>Let’s run again the <code>$ yarn test:watch</code> command and as we could expect, we are receiving error saying that we don’t have the <code>buyBook</code> method in the <code>bookService</code></p>
<pre><code class="lang-typescript">FAIL  src/app/book/book.service.spec.ts
  ● Test suite failed to run

    src/app/book/book.service.spec.ts:<span class="hljs-number">169</span>:<span class="hljs-number">47</span> - error TS2339: Property <span class="hljs-string">'buyBook'</span> does not exist on <span class="hljs-keyword">type</span> <span class="hljs-string">'BookService'</span>.

    <span class="hljs-number">169</span>       <span class="hljs-keyword">const</span> updatedBook: Book = <span class="hljs-keyword">await</span> service.buyBook({
                                                      ~~~~~~~
    src/app/book/book.service.spec.ts:<span class="hljs-number">180</span>:<span class="hljs-number">29</span> - error TS2339: Property <span class="hljs-string">'buyBook'</span> does not exist on <span class="hljs-keyword">type</span> <span class="hljs-string">'BookService'</span>.

    <span class="hljs-number">180</span>         <span class="hljs-keyword">await</span> <span class="hljs-keyword">await</span> service.buyBook({
                                    ~~~~~~~
    src/app/book/book.service.spec.ts:<span class="hljs-number">200</span>:<span class="hljs-number">47</span> - error TS2339: Property <span class="hljs-string">'buyBook'</span> does not exist on <span class="hljs-keyword">type</span> <span class="hljs-string">'BookService'</span>.

    <span class="hljs-number">200</span>       <span class="hljs-keyword">const</span> updatedBook: Book = <span class="hljs-keyword">await</span> service.buyBook({
</code></pre>
<p>Well, we need to refactor our book.service.ts file so that we pass these test cases:</p>
<p>In the <code>book.service.ts</code> file, let’s implement the <code>buyBook</code> method, having the requirement we have set in our test file:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// book.service.ts</span>

...
    <span class="hljs-comment">// BUY BOOK FEATURE</span>
  <span class="hljs-keyword">async</span> isPurchased(buyBookInput: BuyBookInput) {
    <span class="hljs-keyword">const</span> books = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.bookModel.find({
      <span class="hljs-string">'readers._id'</span>: buyBookInput.userId,
    });

    <span class="hljs-comment">// console.log('BOOKS', books);</span>
    <span class="hljs-keyword">return</span> books.length &gt;= <span class="hljs-number">1</span>;
  }

  <span class="hljs-keyword">async</span> buyBook(buyBookInput: BuyBookInput) {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.isPurchased(buyBookInput)) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(CANNOT_PURCHASE_MORE_THAN_ONE_COPY_EXCEPTION);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.bookModel
      .findByIdAndUpdate(
        buyBookInput.bookId,
        {
          $push: {
            readers: buyBookInput.userId,
          },
        },
        { <span class="hljs-keyword">new</span>: <span class="hljs-literal">true</span> },
      )
      .populate(<span class="hljs-string">'readers'</span>);
  }
...
</code></pre>
<p>Using this code above, we can see now our tests pass, bingo we have added a new feature a tdd way.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675403736854/9d215d09-99d8-4c4e-ab21-430c459ce65f.png" alt class="image--center mx-auto" /></p>
<p><em>image8 - Added buyBook using a TDD approach</em></p>
<p>🛠️ Now, let’s do the same for the resolvers, starting with the book.spec.ts file</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, this reading delves into the subject of Test Driven Development (TDD) for GraphQL, showing the advantages it offers to the development process. By the end, readers will have a clear understanding of how to test existing resolvers and implement new ones using TDD for GraphQL. This knowledge is invaluable in ensuring the quality and reliability of GraphQL applications.</p>
<p>Have you enjoyed this reading? Let’s connect on <a target="_blank" href="https://twitter.com/PacifiqueLinja1?t=e7uqnNZVMv8HEAjRP2lL0w&amp;s=09">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/pacifique-linjanja">LinkedIn</a>, and <a target="_blank" href="https://github.com/pacyL2K19">GitHub</a> for more content like this.</p>
<p>Thank you for reading, and sharing with your network, let’s meet in the CI/CD part.</p>
<h2 id="heading-additional-resources">Additional resources</h2>
<ul>
<li><p><a target="_blank" href="https://nestjs.com/">Nest.js official documentation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/nestjs/graphql">@nestjs/graphql documentation</a></p>
</li>
<li><p><a target="_blank" href="https://jestjs.io/">Jest official documentation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/ladjs/supertest">Supertest official documentation</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Build a GraphQL API with NestJs and MongoDB, in a modern way - Part 1.]]></title><description><![CDATA[Are you ready to take your GraphQL development skills to the next level? This series of articles may be the right place to be.]]></description><link>https://paclinjanja.hashnode.dev/graphql-api-nestjs-mongodb-a-modern-way-part-1</link><guid isPermaLink="true">https://paclinjanja.hashnode.dev/graphql-api-nestjs-mongodb-a-modern-way-part-1</guid><category><![CDATA[nestjs]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[Apollo GraphQL]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Pacifique Linjanja]]></dc:creator><pubDate>Mon, 27 Feb 2023 15:54:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677511651405/3554cbdb-8ffa-4a94-b971-e3a92171fea9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">Overview</h2>
<p>Are you ready to take your GraphQL development skills to the next level? In this series of four articles, I'll guide you through the process of building a powerful GraphQL API using Nest and MongoDB. You'll learn best practices, and see how to scale your app just as you would in a real-world scenario.</p>
<p>First, we'll kick things off by diving into the fundamentals of Nest, a powerful NodeJS framework. We'll set up the foundation for our final project, and by the end, you'll know how to manually deploy your own sample application.</p>
<p>Next, we'll delve into the world of Test Driven Development (TDD) for GraphQL. You'll see the benefits it brings to the development process and learn how to test your current resolvers and implement new ones using this approach.</p>
<p>In the third installment, we'll explore how to apply Continuous Integration and Continuous Deployment (CI/CD) to Nest and GraphQL apps. We'll create our pipelines and, building off the concepts from the second part, you'll see the true power of this approach in action. Once set up, you won't have to worry as much about delivering to the frontend team, and you'll be able to catch errors even before the app is shipped to client apps.</p>
<p>Finally, in the fourth and final installment, we'll take things up a notch by adding features that will introduce you to the world of micro-services. You'll learn how to break down your monolithic app into smaller, independent micro-services without disrupting any existing functionality. This is the modern approach, saving you from the headache of long, drawn-out migrations. So, let's get started and take your GraphQL development skills to the next level!</p>
<p>The full source code can be found <a target="_blank" href="https://github.com/pacyL2K19/graphql-mongodb-nestjs-tuto/tree/part-1">here(part-1)</a> branch.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To fully benefit from this series, it's important to have a basic knowledge of NodeJS, <a target="_blank" href="https://www.apollographql.com/blog/graphql/basics/graphql-vs-rest/"><strong>GraphQL</strong></a>, <a target="_blank" href="https://docs.nestjs.com/"><strong>NestJS</strong></a>, <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html"><strong>TypeScript</strong></a>, and <a target="_blank" href="https://www.mongodb.com/docs/manual/tutorial/getting-started/"><strong>MongoDB</strong></a>. However, even if you're new to these technologies, don't worry - this series will provide a comprehensive overview of our stack, including the most crucial aspects we'll be using along the way.</p>
<h2 id="heading-why-nestjs">Why Nest.js</h2>
<p>NestJS(we will use <strong>Nest</strong> often) is a popular framework for building efficient, scalable Node server-side applications. Some reasons why developers might choose NestJS for API development include its use of modern JavaScript and TypeScript, its modular architecture, you don’t have to care much about the architecture of your project since Nest provides modern patterns, and its ability to easily integrate with other common libraries and frameworks such as Express. Additionally, NestJS provides a powerful CLI that can be used to generate boilerplate code, which can be a time-saver, making it easier to get started with building an API. Overall, NestJS can make it easier for developers to build efficient and maintainable APIs in a relatively short amount of time, read more about the fundamental of Nest <a target="_blank" href="https://docs.nestjs.com/#philosophy">here</a>.</p>
<p>Apart from what has been mentioned already, Nest has several advantages that make it a popular choice for building server-side applications, including:</p>
<ol>
<li><p><strong>Modular structure</strong>: Nest uses a modular architecture, which allows developers to organize their code into reusable modules and components. This makes it easy to build, test, and maintain large-scale applications.</p>
</li>
<li><p><strong>TypeScript support</strong>: built with TypeScript, improves code organization and eliminates the need for manual type rewriting by addressing the challenge of consistent types across server, client, schema, and resolvers.</p>
</li>
<li><p><strong>Built-in testing support</strong>: Nest comes with built-in testing support, making it easy to write and run unit tests for your application.</p>
</li>
<li><p><strong>Strong performance</strong>: Nest uses Express.js under the hood, which means that it is built on a solid foundation and can handle a large number of requests.</p>
</li>
<li><p><strong>Large and active community</strong>: Nest has a large and active community of developers, which means that there are plenty of resources and tutorials available to help you learn and troubleshoot.</p>
</li>
<li><p><strong>Integrations</strong>: Nest easily integrates with other common libraries and frameworks such as Express, MongoDB, and <a target="_blank" href="http://Socket.io">Socket.io</a>, which makes it easy to connect to databases and other services.</p>
</li>
</ol>
<p>In our use case, we are building Graphql API and there are several reasons why Nest is the better choice for us:</p>
<ul>
<li><p>It provides a powerful set of decorators and tools for implementing GraphQL resolvers, making it easy to define and organize the schema for a GraphQL API, that way we don’t have to write all from scratch ourselves, which makes us save countless time.</p>
</li>
<li><p>It allows you to use GraphQL in a modular way, which makes it easy to organize and test your GraphQL code, which we will see in the second part in practice.</p>
</li>
<li><p>It also provides the ability to easily integrate with the Apollo Server, which is a popular library for building GraphQL APIs.</p>
</li>
</ul>
<p>Nest's modular architecture and support for GraphQL make it a great choice for building scalable and maintainable GraphQL APIs.</p>
<p>Too much talk, let’s see all of this in practice.</p>
<h2 id="heading-setup-your-codebase"><strong>Setup your codebase</strong></h2>
<h3 id="heading-what-are-we-going-to-build">What are we going to build</h3>
<p>Before starting with actual coding, it’s better to have an overview of what we are building. In our first parts, we will keep the app as basic as possible, while exploring the most important concepts of our stack.</p>
<p>We will build a bookstore application, the data model will look like the chart below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675399413126/644cd01a-487f-4ce1-8ccb-9e0db6ab28b2.png" alt class="image--center mx-auto" /></p>
<p><em>image1 - ER model</em></p>
<p>As you can see above, we have a simple Entity Relationship(ER) representing our bookstore database. This will be our starting point. These are the entities we have for now:</p>
<ul>
<li><p>Book entity: representing a book, that has a title, a description, a price, an ISBN(International Standard Book Number), and an author, in MongoDB world, the author field will be a reference to pointing to the author model, containing the author’s object id. Read more about ObjectIds in MongoDB <a target="_blank" href="https://www.mongodb.com/docs/manual/reference/method/ObjectId/">here</a>.</p>
</li>
<li><p>Author entity: representing an author, we need information like name, bio and his books, and an array of references from the book model.</p>
</li>
<li><p>User entity: representing a customer, this will be the user of the bookstore app, he can create an account and purchase books for now.</p>
</li>
</ul>
<p>Now, let’s set up the project …</p>
<h3 id="heading-project-setup">Project setup</h3>
<p>Before we start coding, please make sure to have <a target="_blank" href="https://nodejs.org/en/download/">node v14</a> or higher, <a target="_blank" href="https://docs.nestjs.com/cli/overview">nest CLI</a> and yarn v.1.22 (our package manager).</p>
<p>You can check it all out now, to make sure you have all installed and running</p>
<pre><code class="lang-bash">$ node -v
<span class="hljs-comment"># =&gt; outputs the node version currently installed</span>
$ yarn -v
<span class="hljs-comment"># =&gt; outputs the version of yarn</span>
$ nest info
<span class="hljs-comment"># =&gt; outputs information about the current nest CLI installed and its dependency, make sure the node version matches the version required by your CL</span>
</code></pre>
<p>Once you have all the required packages, we can set up the codebase.</p>
<p>We create a new Nest project with the following command</p>
<pre><code class="lang-bash">$ nest new bookstoreApp
<span class="hljs-comment"># choose yarn as a package manager, or the one you feel more comfortable with</span>
</code></pre>
<p>The output should look like the screenshot below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675399605834/753ee2b2-7107-412f-9f17-be627218c07b.png" alt class="image--center mx-auto" /></p>
<p><em>image2 - Create a new nest project, the output.</em></p>
<p>The scaffold created has the below structure</p>
<pre><code class="lang-bash"><span class="hljs-comment"># PROJECT INITIAL STRUCTURE</span>

├─ package.json
├─ src
│  ├─ app.controller.spec.ts
│  ├─ app.controller.ts
│  ├─ app.module.ts
│  ├─ app.service.ts
│  └─ main.ts
├─ <span class="hljs-built_in">test</span>
│  ├─ app.e2e-spec.ts
│  └─ jest-e2e.json
├─ tsconfig.build.json
├─ tsconfig.json
└─ yarn.lock
</code></pre>
<p>In the code structure, we can notice that Nest also creates testing files under <code>test/</code> directory, and the project is essentially written in typescript.</p>
<p>Let’s run the project generated for us, and see what we have:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># use the command below</span>
$ yarn start
</code></pre>
<p>Then, go to <a target="_blank" href="http://localhost:3000">localhost:3000</a> and make sure you GET <code>Hello World!</code></p>
<p>Kudos, you have created a Rest API with Nest, let’s understand the nest architecture in detail now.</p>
<h2 id="heading-understanding-the-nest-architecture"><strong>Understanding the Nest architecture</strong></h2>
<p>From the project structure, let’s dive into the nest architecture:</p>
<ul>
<li><p>First, you may notice it has a package.json file, which makes it a node project, in addition, we have a tsconfig.json, which makes it a typescript project, then a yarn.lock file, as we chose to use yarn as a package manager. Under the hood, Nest has installed for us all the required packages to start the node environment.</p>
</li>
<li><p>Having a look at our package.json file, you will see that Nest CLI has installed a bunch of packages for us such as jest and @types/jest for testing, @types/express eslint, prettier, etc, which prevents us from installing them from scratch, making the developer save an important amount of time, still you can customize the .eslintrc.js and .prettierrc files, but what nest set for us is based on high-level standards and we mostly don’t have to touch those created files. You can also notice that Nest has configured jest for us, the project is ready to test, which we will explore more in our second part.</p>
</li>
<li><p>Nest has created an <code>src/</code> folder for use, that is the place we will mostly work, still possible to customize it by your preferences, you can update the <code>nest-cli.json</code> file and define a custom <code>sourceRoot</code> but, as I said, what nest creates for us is inspired by most performant architecture so we really don’t have to touch those config files.</p>
</li>
<li><p>In the src, let’s make a light update, let’s create a folder <code>src/app</code> then past all the <code>app.*.ts</code> files there</p>
<pre><code class="lang-bash">  <span class="hljs-comment"># from the project root, let's run</span>
  $ mkdir src/app &amp;&amp; mv src/app.*.ts src/app
  <span class="hljs-comment"># this command will create the src/app folder, then it will paste all the app files inside</span>
</code></pre>
<p>  Then rectify the import inside the <code>main.ts</code> file, from <code>import { AppModule } from './app.module';</code> to <code>import { AppModule } from './app/app.module';</code> If you run your project again, you will see that the app is still running.</p>
</li>
<li><p>The <code>app/app.module.ts</code> file currently looks like this:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
  <span class="hljs-keyword">import</span> { AppController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.controller'</span>;
  <span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

  <span class="hljs-meta">@Module</span>({
    imports: [],
    controllers: [AppController],
    providers: [AppService],
  })
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<p>  When I hover over the <code>@Module</code> decorator, this is what I get:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675399809589/f38df310-9992-46a9-8213-d8107780dbaf.png" alt class="image--center mx-auto" /></p>
<p>  <em>image3 - Module decorator</em></p>
<p>  We can see that <code>@Module</code> returns a <code>ClassDecorator</code> nest/common has exported a lot of decorators just like @Module, which we will explore while building but, what is a decorator in Nest(or Angular, for Angular developers)?</p>
<p>  Based on the <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/decorators.html#decorators">typescript official documentation</a>, decorators are <strong>a feature of typeScript</strong> that is used to add metadata to a class, method, or property. This metadata can then be used by the Nest framework to perform various tasks, such as routing, dependency injection, and error handling.</p>
<p>  In Nest, decorators are used to define controllers, services, pipes, guards, and more. Here are a few examples of decorators used in NestJS:</p>
<ol>
<li><p><strong>@Controller</strong>: Used to define a class as a NestJS controller. Controllers handle incoming HTTP requests and return appropriate responses, useful for Restful APIs.</p>
</li>
<li><p><strong>@UseGuards</strong>: Used to apply one or more guards to a controller or route handler method. Guards can be used to protect routes or to perform authentication or authorization.</p>
</li>
<li><p><strong>@Query</strong>: Used to define a property in a class as a GraphQL query.</p>
</li>
<li><p><strong>@Mutation</strong>: Used to define a property in a class as a GraphQL mutation.</p>
</li>
<li><p><strong>@Resolver</strong>: Used to define a class as a GraphQL resolver.</p>
</li>
<li><p><strong>@Get</strong>: Used to define a method in a controller as a route handler for HTTP GET requests.</p>
</li>
<li><p><strong>@Post:</strong> Used to define a method in a controller as a route handler for HTTP POST requests, useful for Restful APIs.</p>
</li>
<li><p><strong>@UsePipes</strong>: Used to apply one or more pipes to a controller or route handler method. Pipes can be used to validate or transform incoming data.</p>
</li>
<li><p><strong>@Injectable</strong>: Used to define a class as a service that can be injected into other parts of the application.</p>
</li>
</ol>
</li>
</ul>
<p>    These are just a few examples, but there are many other decorators available in NestJS that can be used to perform various tasks, such as handling errors, injecting dependencies, and more, read more about decorators <a target="_blank" href="https://docs.nestjs.com/openapi/decorators#decorators">here</a>.</p>
<p>    This is an overview of the Nest architecture, as we build all of those aspects will become clearer and clearer.</p>
<h2 id="heading-from-rest-to-graph"><strong>From Rest to Graph</strong></h2>
<p>Currently, we have created a Rest API with one exposed endpoint, the GET defined in the <code>src/app/app.controller.ts</code> file, in this section, we will transition from the Rest API to Graphql API the painless way.</p>
<p>In our <code>app.module.ts</code> file, we have used the <code>@Module</code> decorator, diving into the <a target="_blank" href="https://docs.nestjs.com/modules">Nest documentation</a>, we understand that it provides metadata that <strong>Nest</strong> makes use of to organize the application structure, in other words, each Nest application has at least one Module to make it work, that we’ll call the root module, it’s our starting point, meaning, if we need to transform our API from Rest to Graph, we will need to detect and update our route module, in the way it starts listening only one endpoint, the <code>graphql/</code>.</p>
<p>Getting back to the module decorator, according to its documentation, a module can become a <code>Provider</code> to another module, all linked to the root module, the module-provider relationship is implementing a <a target="_blank" href="https://www.educative.io/answers/what-is-a-graph-data-structure">GRAPH data structure</a> under the hood shown in the image below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675399941621/60f417a5-ca72-4664-af5a-d6708b60b3e0.png" alt class="image--center mx-auto" /></p>
<p><em>image3A - module-providers relationship - image credit:</em><a target="_blank" href="https://docs.nestjs.com/"><em>THE NEST OFFICIAL DOC</em></a></p>
<p>The module decorator takes a single object as a set of properties that defines the module, we will use those properties to transform our API into a graphql, the most important ones for now are:</p>
<ul>
<li><p><code>imports</code>: the list of imported modules that export the providers which are required in this module.</p>
</li>
<li><p><code>providers</code>: the providers that will be instantiated by the Nest injector and that may be shared at least across this module.</p>
</li>
<li><p><code>controllers</code>: the set of controllers defined in this module that have to be instantiated.</p>
</li>
</ul>
<p>Let’s go ahead and improve our root module so that our app will become a graphql app:</p>
<ol>
<li><p>In the <code>imports</code> array, let’s use the <code>GraphQLModule</code> exported from <code>@nestjs/graphql</code> package, after the required packages below.</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># install the required packages</span>
 $ yarn add @nestjs/graphql @nestjs/apollo graphql apollo-server-express apollo-server-core
</code></pre>
<p> Then, in the <code>app/app.module.ts</code> file, change the empty <code>imports</code> array to:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// app/app.module.ts </span>

 imports: [
     GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({
       driver: ApolloDriver,
     autoSchemaFile: join(process.cwd(), <span class="hljs-string">'src/schema.gql'</span>),
     playground: <span class="hljs-literal">false</span>,
     plugins: [ApolloServerPluginLandingPageLocalDefault()],
   }),
 ],
</code></pre>
<p> With <code>GraphQLModule</code> imported from <code>@nestjs/graphql</code>, <code>ApolloDriver</code> and <code>ApolloDriverConfig</code> from <code>@nestjs/apollo</code>, join from <code>path</code>, and <code>ApolloServerPluginLandingPageLocalDefault</code> from <code>apollo-server-core.</code></p>
<p> In the GraphQLModule. we have added a couple of other properties:</p>
<ul>
<li><p>By setting the autoSchemaFile property to <code>join(process.cwd(), 'src/schema.gql')</code>, we can use the code-first approach instead of the schema-first approach. This way, Nest will automatically generate our schemas based on our model classes. We've chosen to store the schema file in the <code>src/schema.gql</code> location, but you can also let Nest determine the location by simply setting autoSchemaFile to true. To learn more about the pros and cons of the schema-first vs code-first approach, you can check out <a target="_blank" href="https://blog.graphqleditor.com/graphql-schemafirst-codefirst">this resource</a>.</p>
</li>
<li><p><strong>playground</strong>: set to <code>false</code> To use <code>Apollo Sandbox</code> instead of the <code>graphql-playground</code> as a GraphQL IDE for local development.</p>
</li>
<li><p><strong>plugins</strong>: we need to define it as <strong>ApolloServerPluginLandingPageLocalDefault</strong> based on the playground value, if it’s set to true, we don’t necessarily need to add it as part of our plugins.</p>
</li>
</ul>
</li>
<li><p>Then, let’s rename the <code>app.controller.ts</code> file to <code>app.resolver.ts</code> and just enter the code below:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// app/app.resolver.ts</span>

 <span class="hljs-keyword">import</span> { Query, Resolver } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/graphql'</span>;
 <span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

 <span class="hljs-meta">@Resolver</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppResolver {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> appService: AppService</span>) {}

   <span class="hljs-meta">@Query</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">String</span>)
   getHello(): <span class="hljs-built_in">string</span> {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.appService.getHello();
   }
 }
</code></pre>
<p> From the previous content, we can see these differences:</p>
<ul>
<li><p>The <code>@Controller</code> decorator has been changed to <code>@Resolver</code></p>
</li>
<li><p>The <code>@Get</code> decorator by <code>@Query(() =&gt; String)</code></p>
</li>
</ul>
</li>
</ol>
<p>    But everything else remains exactly the same.</p>
<p>    Let’s now get back to our <code>app.module.ts</code> file, and fix the imports</p>
<ol>
<li><p>Change the import of the controller, we no longer have one, we have a resolver instead</p>
</li>
<li><p>Remove the <code>AppController</code> controller from the <code>controllers</code> array,</p>
</li>
<li><p>Add the <code>AppResolver</code> in the <code>providers</code> array along with <code>AppService</code></p>
</li>
</ol>
<p>    Our file now looks like the following:</p>
<pre><code class="lang-typescript">    <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
    <span class="hljs-keyword">import</span> { AppResolver } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.resolver'</span>;
    <span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;
    <span class="hljs-keyword">import</span> { GraphQLModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/graphql'</span>;
    <span class="hljs-keyword">import</span> { ApolloDriver, ApolloDriverConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/apollo'</span>;
    <span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;
    <span class="hljs-keyword">import</span> { ApolloServerPluginLandingPageLocalDefault } <span class="hljs-keyword">from</span> <span class="hljs-string">'apollo-server-core'</span>;

    <span class="hljs-meta">@Module</span>({
      imports: [
        GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({
          driver: ApolloDriver,
          autoSchemaFile: join(process.cwd(), <span class="hljs-string">'src/schema.gql'</span>),
          playground: <span class="hljs-literal">false</span>,
          plugins: [ApolloServerPluginLandingPageLocalDefault()],
        }),
      ],
      controllers: [],
      providers: [AppService, AppResolver],
    })
    <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<p>    That way, we have transformed our initial Rest API into a Graphql one, in a few steps, easy to follow.</p>
<p>Let’s run the app once again and confirm that our API is now Graphql API</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Let's run the app in dev mode</span>
$ yarn start:dev
</code></pre>
<p>Let’s go at <a target="_blank" href="http://localhost:3000/graphql">http://localhost:3000/graphql</a></p>
<p>This is what we normally get:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400021050/e7876d84-9eeb-45c2-824b-114458871218.png" alt class="image--center mx-auto" /></p>
<p><em>image4A</em></p>
<p>Let’s query our server, we currently have only one Query, the <code>getHello</code>, if you were following along, everything should be running like on the image below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400063274/baceaa4c-4920-42aa-806f-7c519888896a.png" alt class="image--center mx-auto" /></p>
<p><em>image4B - Our graphql API running 🚀</em></p>
<p>Kudos, our API is running, let’s now configure our database.</p>
<h2 id="heading-setup-database-and-environment-variables"><strong>Setup database and environment variables</strong></h2>
<blockquote>
<p>You can get the codebase for the previous part by checking out the commit <code>#4db24a</code></p>
</blockquote>
<p>As announced, we will use MongoDB for our database, make sure you have configured a mongo cluster <a target="_blank" href="https://www.mongodb.com/basics/clusters/mongodb-cluster-setup">here</a> and you have a <em>DATABASE_URL</em> ready to process.</p>
<p>To add MongoDB configuration to our project, we will use the <code>MongooseModule</code> module imported from <code>@nestjs/graphql</code> then we will configure environment variables to retrieve the <em>DATABASE_URL</em> variable.</p>
<p>Create a <code>.env</code> file and add there the key <code>DATABASE_URL</code> with the value you got from your cluster before we continue.</p>
<p>When working with NodeJS applications, it's common practice to use .env files to store key-value pairs for different environments. This makes it easy to switch between environments by simply swapping in the appropriate .env file.</p>
<p>A great way to implement this technique in a Nest application is to create a ConfigModule that provides access to a ConfigService. This service loads the appropriate .env file for the current environment. Although you could choose to build this module yourself, Nest offers the convenient <code>@nestjs/config</code> package out-of-the-box. We'll dive into this package in this section.</p>
<p>Let’s get started by installing the required packages:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># install required packages</span>
$ yarn add @nestjs/mongoose @nestjs/config mongoose
</code></pre>
<p>Then, we will inject the <code>MongooseModule</code> module into our root module, as we are getting used to Nest syntaxes, the way we will inject it will look similar to how we did with the <code>GraphQLModule</code> previously.</p>
<p>In the app.module.ts file, let’s add this line, in the <code>imports</code> property of our root module:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app/app.module.ts</span>
...
MongooseModule.forRoot(<span class="hljs-string">'YOUR_DATABASE_URL'</span>),
...
</code></pre>
<p>The <code>forRoot</code> method takes the same parameters as the <code>mongoose.connect()</code> method, in this case, we are passing in the URL for our database.</p>
<p>Instead of hard-coding the URL, we can use the <code>DATABASE_URL</code> from our **<code>.**env</code> file.</p>
<p>We have installed the <code>@nestjs/config</code> package, which is a built-in package that exposes the <code>ConfigModule**,</code> w**e will use this in our root module, to configure the preload of our .env file with its variables.</p>
<p>By adding <code>ConfigModule.forRoot()</code> in the imports property of our root module, we are loading and parsing a **<code>.**env</code> file from the default location (the project root directory). This merges key/value pairs from the **<code>.**env</code> file with environment variables assigned to <code>process.env</code>. The result is stored in a private structure that can be accessed through a <code>ConfigService</code> instance. We don't need to create this service ourselves, as <code>@nestjs/config</code> takes care of it for us.</p>
<p>As we are loading environment variables, the connection to the MongoDB database will no longer be synchronous. To achieve an asynchronous connection, we will use the <code>forRootAsync</code> method instead of <code>forRoot()</code>.</p>
<p>We will then use a factory provider to inject dynamic configuration, such as a dynamic database URL, into our <code>mongoose.connect()</code> function. I recommend looking at <a target="_blank" href="https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory">this resource</a> to understand how to customize providers using the <code>useFactory</code> syntax.</p>
<p>Combining the information above, let’s update the <code>imports</code> property of our root module, here is how it should look now:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// app/app.module.ts</span>
...
imports: [
    GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), <span class="hljs-string">'src/schema.gql'</span>),
      playground: <span class="hljs-literal">false</span>,
      plugins: [ApolloServerPluginLandingPageLocalDefault()],
    }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: <span class="hljs-function">(<span class="hljs-params">configService: ConfigService</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> options: MongooseModuleOptions = {
          uri: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'DATABASE_URL'</span>),
        };

        <span class="hljs-keyword">return</span> options;
      },
    }),
    ConfigModule.forRoot({
      cache: <span class="hljs-literal">true</span>,
    }),
  ],
...
</code></pre>
<p>You can see that we've injected the <code>ConfigService</code> from the <code>@nestjs/config</code> package into the MongooseModule. This service contains a private structure that stores the key/value pairs from the <code>.env</code> file. Restart the server and ensure that the app is running.</p>
<p>In the same way we've injected environment variables into the root module, we can do the same for other modules throughout the app. We're slowly diving into the most important aspects of the Nest framework, great job!</p>
<p>Currently, this is how our root module looks like:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { AppResolver } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.resolver'</span>;
<span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;
<span class="hljs-keyword">import</span> { GraphQLModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/graphql'</span>;
<span class="hljs-keyword">import</span> { ApolloDriver, ApolloDriverConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/apollo'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;
<span class="hljs-keyword">import</span> { ApolloServerPluginLandingPageLocalDefault } <span class="hljs-keyword">from</span> <span class="hljs-string">'apollo-server-core'</span>;
<span class="hljs-keyword">import</span> { ConfigModule, ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
<span class="hljs-keyword">import</span> { MongooseModule, MongooseModuleOptions } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;

<span class="hljs-meta">@Module</span>({
  imports: [
    GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), <span class="hljs-string">'src/schema.gql'</span>),
      playground: <span class="hljs-literal">false</span>,
      plugins: [ApolloServerPluginLandingPageLocalDefault()],
    }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: <span class="hljs-function">(<span class="hljs-params">configService: ConfigService</span>) =&gt;</span> {
        <span class="hljs-comment">// CHECK IF YOU GET WHAT IS EXPECTED</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ENV VAR'</span>, configService.get(<span class="hljs-string">'DATABASE_URL'</span>));

        <span class="hljs-keyword">const</span> options: MongooseModuleOptions = {
          uri: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'DATABASE_URL'</span>),
        };

        <span class="hljs-keyword">return</span> options;
      },
    }),
    ConfigModule.forRoot({
      cache: <span class="hljs-literal">true</span>,
    }),
  ],
  controllers: [],
  providers: [AppService, AppResolver],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<p>Now, let's start building the other modules of the app.</p>
<blockquote>
<p>You can get the codebase for the previous part by checking out the commit <code>#812bc3</code></p>
</blockquote>
<h2 id="heading-create-modules"><strong>Create modules</strong></h2>
<p>At this part, we have done most of the setup, now we will mostly code.</p>
<p>From our ER diagram, we have 3 modules, let’s create those modules in the most scalable way.</p>
<ol>
<li><p>The User Module</p>
<p> We will use the Nest CLI to generate our modules, let’s start with the user module, by running the code below at the root of our project</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># generate the user module</span>
 <span class="hljs-comment"># to the question 'What transport layer do you use?' choose GraphQL (code first)</span>
 <span class="hljs-comment"># to the question 'Would you like to generate CRUD entry points?' reply with y</span>
 $ <span class="hljs-built_in">cd</span> src/app &amp;&amp; nest g resource user
</code></pre>
<p> Wow 🤩 , Nest has done all the heavy lifting for us by providing a solid foundation for our user resource! This is incredibly powerful and allows us to focus on the implementation rather than worrying about architecture or any other complex issues. How amazing is that! Is our app still working? Of cause, Nest is our biggest friend, he can’t break it.</p>
<p> Take a few moments to have a look at the generated files, as we start customizing those files.</p>
<p> As we have generated the CRUD entry point, after running the app, we can see that our <code>schema.gql</code> file is updated to something like the following(code-first):</p>
<pre><code class="lang-graphql"> <span class="hljs-comment"># ------------------------------------------------------</span>
 <span class="hljs-comment"># THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)</span>
 <span class="hljs-comment"># ------------------------------------------------------</span>

 <span class="hljs-keyword">type</span> User {
   <span class="hljs-string">""</span><span class="hljs-string">"Example field (placeholder)"</span><span class="hljs-string">""</span>
   <span class="hljs-symbol">exampleField:</span> Int!
 }

 <span class="hljs-keyword">type</span> Query {
   <span class="hljs-symbol">getHello:</span> String!
   <span class="hljs-symbol">users:</span> [User!]!
   user(<span class="hljs-symbol">id:</span> Int!): User!
 }

 <span class="hljs-keyword">type</span> Mutation {
   createUser(<span class="hljs-symbol">createUserInput:</span> CreateUserInput!): User!
   updateUser(<span class="hljs-symbol">updateUserInput:</span> UpdateUserInput!): User!
   removeUser(<span class="hljs-symbol">id:</span> Int!): User!
 }

 <span class="hljs-keyword">input</span> CreateUserInput {
   <span class="hljs-string">""</span><span class="hljs-string">"Example field (placeholder)"</span><span class="hljs-string">""</span>
   <span class="hljs-symbol">exampleField:</span> Int!
 }

 <span class="hljs-keyword">input</span> UpdateUserInput {
   <span class="hljs-string">""</span><span class="hljs-string">"Example field (placeholder)"</span><span class="hljs-string">""</span>
   <span class="hljs-symbol">exampleField:</span> Int
   <span class="hljs-symbol">id:</span> Int!
 }
</code></pre>
<p> We have a folder called <code>dto/</code> under our generated <code>user</code> resources directory which holds our DTO (Data Transfer Object) files. A DTO defines how data is sent over the network. We can define the DTO schema using TypeScript interfaces or classes. Nest documentation suggests using classes over interfaces as they are part of the JavaScript ES6 standard and will be preserved as real entities in the compiled JavaScript. TypeScript interfaces, however, are removed during transpilation, making them inaccessible to Nest at runtime.</p>
<p> You'll notice that Nest has automatically generated these queries and mutations for us. Now, let's customize the user resource files to suit our needs.</p>
<p> We'll begin by modifying the <code>app/user/entities/user.entity.ts</code> **** file to define our user model. Replace the existing code with the code provided below:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">import</span> { ObjectType, Field } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/graphql'</span>;
 <span class="hljs-keyword">import</span> { Document, Schema <span class="hljs-keyword">as</span> MongooSchema } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongoose'</span>;
 <span class="hljs-keyword">import</span> { Prop, Schema, SchemaFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;

 <span class="hljs-meta">@ObjectType</span>()
 <span class="hljs-meta">@Schema</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> User {
   <span class="hljs-comment">// We are using the @Field() decorator in addition to the @Prop() one to specify that the class propery is a GraphQL field</span>
   <span class="hljs-comment">// In other words, that decorator isn't necessary for Rest APIs</span>

   <span class="hljs-meta">@Field</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">String</span>)
   _id: MongooSchema.Types.ObjectId;

   <span class="hljs-comment">// Add user properties</span>
   <span class="hljs-meta">@Field</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">String</span>)
   <span class="hljs-meta">@Prop</span>()
   name: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Field</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">String</span>)
   <span class="hljs-meta">@Prop</span>({ unique: <span class="hljs-literal">true</span> })
   email: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Field</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">String</span>)
   <span class="hljs-meta">@Prop</span>()
   password: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Field</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">String</span>)
   <span class="hljs-meta">@Prop</span>()
   address: <span class="hljs-built_in">string</span>;

   <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> ADD RELATIONSHIP TO THE BOOK MODEL</span>
 }

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> UserDocument = User &amp; Document;
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> UserSchema = SchemaFactory.createForClass(User);
</code></pre>
<p> According to the <code>@nest/mongoose</code> documentation, we use the <code>@Prop()</code> decorator to define fields in a data module. This decorator can take several properties, such as whether a field is required or unique. For example, we set the email field as unique to prevent duplicate accounts. We will explore other properties later on. You can learn more about them by visiting the <a target="_blank" href="https://www.notion.so/Graphql-APIs-with-NestJs-and-Mongodb-the-modern-way-DRAFT-ceb41610b9294a1d866c45dde4e71304">documentation</a>.</p>
<p> In addition to the necessary <code>@Prop</code> decorator, we also have the <code>@Field()</code> decorator from <code>@nest/graphql</code>. This will help generate our schema file and indicate to our API that the specific field is a GraphQL one.</p>
<p> Now, let's update our DTO files. They are similar to the <code>entity</code> files, but since they're not MongoDB fields, we don't use <code>@Props</code> decorators. 🛠️ Let's update the DTO files to look like the following:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400608052/daf18a81-be8b-4f73-bfb6-8b8f594b7ea0.png" alt class="image--center mx-auto" /></p>
<p> <em>image4 - create-user dto</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400660149/e172fa88-0084-4373-ac31-56641febd073.png" alt class="image--center mx-auto" /></p>
<p> <em>image5 - update-user dto</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400691240/fc9750b0-3ee3-45f0-9e00-b3ce7a6d6eb4.png" alt class="image--center mx-auto" /></p>
<p> <em>image6 - update-password dto</em></p>
<p> As we are on DTOs, I have added the last one, which will take care of updatePassword inputs. We are using <code>PartialType</code> from <code>@nestjs/graphql</code> into the <code>UpdateUserInput</code> class to make sure all the fields that the CreateUserInput contains will be available here, but optional, you can read more about Partial utility types, a typescript feature <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype">here</a>.</p>
<p> Are you ready for some serious code-slinging action? We're about to dive into the nitty-gritty of business logic and, let's be real, it's not rocket science. Most of this stuff is inspired by the <code>@nestjs/mongoose</code> documentation, so if you're ever feeling lost, just give it a quick peek. But don't worry, with everything we've covered so far, you've got this in the bag.</p>
<p> 🛠️ Now, let’s together update the <code>user.service.ts</code> and <code>user.resolver.ts</code> files like following:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400768020/42ecc4b1-a2e4-4126-b50d-8f91c0961599.png" alt class="image--center mx-auto" /></p>
<p> <em>image7 - user.service updated</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400870657/2b3ef8f2-48ee-49fe-a8e6-c6eeb6ab2458.png" alt class="image--center mx-auto" /></p>
<p> <em>image8 - user-resolver.ts updated</em></p>
<p> Alright, it's getting spicy now that we have more than one mutation and query. But don't worry, the code may look like gibberish but it's quite simple. Just pay attention to a couple of details, like making sure your custom <code>name</code> properties are unique, otherwise, GraphQL will ignore the first one and you'll end up with a bunch of confused developers.</p>
<p> And if things still seem a little murky, don't hesitate to add some helpful descriptions to your resolvers. Trust me, it'll make things much clearer for everyone.</p>
<p> 🛠️  Update our <code>user.module</code> file to reflect these changes and make sure we're injecting the user model and exporting it to the root module. Give it a shot, you got this! 🤘 You can check out <code>#c4acf4</code> to verify.</p>
<p> After running the app once again, make sure everything is working just perfectly, the generated <code>schema.gql</code> should look like the following:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675400964610/3f3c42db-4566-4375-b9e5-126a325250a6.png" alt class="image--center mx-auto" /></p>
<p> <em>image9 - schema.gql file</em></p>
<p> Let’s try it out and create a first user</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401023574/2a668f5e-a8a6-4981-9d84-138bcad7b4b6.png" alt class="image--center mx-auto" /></p>
<p> <em>image10 - Create user mutation</em></p>
<p> You should be able to make all the CRUD operations, I know a password should never be stored the way we are doing, be patient, and the section after will all be about security.</p>
<p> Before we move forward to the security section, let’s do the same for book and author modules.</p>
<p> First, let’s generate the resources using nest CLI</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># From the root of the project, let's run</span>
 $ <span class="hljs-built_in">cd</span> src/app &amp;&amp; nest g resource book &amp;&amp; nest g resource author
</code></pre>
<p> This also does the exact same thing we saw before.</p>
<p> Alright, it's time to spruce up our DTOs, entities, services, and modules. Take a gander at <code>#20d186</code> to see the shiny new structure we've got going on. And don't worry if it all seems a bit confusing at first, just take a break and try replicating it yourself. Because as they say, practice makes perfect... or at least passable 😎.</p>
<p> However, it’s important to talk about few aspect we customized:</p>
<ol>
<li><p>I have added a <code>common</code> module at <code>app/common/</code> with only dto files, that module aims to have shared logic under <code>common/service</code> and export them through its root module. For those dto, let’s briefly talk about the <code>get-paginated.args.ts</code> file As we may have a lot of books, authors, or user, their <code>findAll</code> methods under their respective services need to send paginated data, we have defined arguments responsible for calling those resources as following.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401214948/ea85827e-9c5c-4fa0-8988-f9f87915db2b.png" alt class="image--center mx-auto" /></p>
<p> <em>image11 - get-paginated.args.ts file</em></p>
<p> As you can see here, instead of calling limit and skip everywhere we have paginated queries, we decided to put it in a single place, then call the <code>GetPaginatedArgs</code> as query’s argument, you can see a sample of place it’s used in the <code>book.resolver.ts</code> file:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401235712/633539f1-6b79-4aa0-b615-e8132c942287.png" alt class="image--center mx-auto" /></p>
<p> <em>image12 - GetPaginatedArgs</em></p>
</li>
<li><p>The query we have above sends a response of type <code>GetBooksPaginatedResponse</code> for this specific query, we need to return a list of <code>args.limit</code> (by default the limit is 10) books but also we need to know how many books we have in the book collection, this is so helpful for the frontend team to build their pagination component, let’s now see what we have for in our books.service.ts file:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401302236/192435bf-2224-4ea4-a6b6-0ce88ea552c2.png" alt class="image--center mx-auto" /></p>
<p> <em>image13 - findAllBooks method</em></p>
<p> You can notice that we are sending a response of type <code>GetBooksPaginatedResponse</code> defined in the <code>book/entity/book.entity.ts</code> file.</p>
</li>
<li><p>Get ready to dive into the exciting world of relationships! We're going to take a closer look at how we've defined the many-to-many relationship between our user and book models. When a user purchases a book, they become a reader for that book and that book becomes part of the user's collection. It's like magic! See the code below and get ready to amaze yourself. If you want to learn more about relationships in <code>@nest/mongoose</code>, check out the documentation <a target="_blank" href="https://docs.nestjs.com/techniques/mongodb#model-injection">here</a>, it's worth the read!</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401369216/f1eeb1e6-d415-4ee7-be4a-4bf62fcac7ac.png" alt class="image--center mx-auto" /></p>
<p> <em>book.entity.ts</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401399011/296eaf97-6601-43ba-8a56-bdf36661df89.png" alt class="image--center mx-auto" /></p>
<p> <em>user.entity.ts image14 - Book - User many-to-many relationship</em></p>
</li>
</ol>
</li>
</ol>
<p>    Amazing, we have done a lot so far, using a replication of the code we have at <code>#20d18</code>, restart the server once again and make sure it runs correctly.</p>
<p>    Congrats, our API is growing and we can be proud of ourselves 🤩</p>
<h2 id="heading-security-in-nest"><strong>Security in Nest</strong></h2>
<blockquote>
<p>You can get the codebase for the previous part by checking out the commit <code>#20d18</code></p>
</blockquote>
<p>Now let’s talk about one of the most crucial parts of API development: SECURITY.</p>
<p>Everything we have done so far is great, we have been able to achieve a lot, but our app is dangerous for clients, let’s protect them.</p>
<p>According to the nest documentation, there are several ways to secure NestJS GraphQL APIs:</p>
<ol>
<li><p><strong>Authentication</strong>: Use JSON Web Tokens (JWT) or OAuth2 to authenticate users and secure their data. NestJS has built-in support for JWT authentication, we should be able to keep the user’s secret credentials(like the user’s password) encrypted and inaccessible.</p>
</li>
<li><p><strong>Authorization</strong>: Use GraphQL directives to limit access to specific fields and operations based on user roles and permissions, for example, in our case not every user should be able to add books in the store, or only authenticated users should retrieve books, etc. NestJS has built-in support for GraphQL directives.</p>
</li>
<li><p><strong>Input validation</strong>: Use the built-in validation decorators to validate user input and prevent malicious attacks.</p>
</li>
<li><p><strong>CORS</strong>: Enable <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS(Cross-Origin Resource Sharing)</a> to prevent cross-site scripting (XSS) attacks. NestJS has built-in support for CORS.</p>
</li>
<li><p><a target="_blank" href="https://docs.nestjs.com/security/rate-limiting#rate-limiting"><strong>Rate Limiting</strong></a>: Limit the number of requests a user can make to prevent <a target="_blank" href="https://www.cloudflare.com/learning/ddos/what-is-a-ddos-attack/"><strong>DDoS(distributed denial-of-service)</strong></a> attacks and abuse. NestJS has built-in support for rate limiting.</p>
</li>
<li><p><strong>HTTPS</strong>: Use HTTPS to encrypt communication between the client and server and prevent man-in-the-middle attacks.</p>
</li>
<li><p><strong>Error handling</strong>: Use proper error handling to prevent sensitive data from leaking to the client and to log errors.</p>
</li>
<li><p><strong>Security headers</strong>: Add security headers to protect against common web vulnerabilities.</p>
</li>
</ol>
<blockquote>
<p><strong>🚧</strong>  <strong>It's vital to keep in mind that ensuring the security of your NestJS GraphQL APIs is a continuous effort and the methods used may evolve over time. Therefore, it's critical to stay informed of any new advancements and adapt your security strategies accordingly.</strong></p>
</blockquote>
<p>We will go step by step:</p>
<ol>
<li><p>Enable CORS Inside the <code>GraphQLModule</code> we will simply enable cors by using the <code>cors</code> property of its <code>forRoot()</code> method like the following:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// app.module.ts</span>

 ...
 GraphQLModule.forRoot({
   cors: <span class="hljs-literal">true</span>
     <span class="hljs-comment">// or alternatively parse cors options like:</span>
     <span class="hljs-comment">/**
     cors: {
     origin: '*',
     credentials: true,
         ...
   },
     */</span>
 }),
 ...
</code></pre>
</li>
<li><p>Encrypt password To keep it simple for now, we will use <code>bcrypt</code> to encrypt and decrypt our passwords.</p>
<p> Let’s start by installing the bcrypt utilities:</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># install bcrypt</span>
 $ yarn add bcrypt &amp;&amp; yarn add -D @types/bcrypt
</code></pre>
<p> Now, let’s inject the <code>ConfigModule</code> into the <code>UserModule</code> the same way we did for the root directory 🛠️ Update the <code>imports</code> and <code>providers</code> arrays of the <code>userModule</code> with the following code:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// user.module.ts</span>

 ...
 providers: [UserResolver, UserService, ConfigService],
   imports: [
     MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
     ConfigModule.forRoot({
       cache: <span class="hljs-literal">true</span>,
     }),
   ],
 ...
</code></pre>
<p> Let’s now add the loginUser and improve the createUser method into the <a target="_blank" href="http://user.services"><code>user.services</code></a><code>.ts</code></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// user.service.ts</span>

 ...
 <span class="hljs-keyword">async</span> createUser(createUserInput: CreateUserInput) {
     <span class="hljs-comment">// GENERATE HASH PASSWORD TO SAVE</span>
     <span class="hljs-keyword">const</span> hash = <span class="hljs-keyword">await</span> bcrypt.hash(
       createUserInput.password,
       <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'SALT_ROUND'</span>)),
     );

     <span class="hljs-keyword">const</span> createdUser = <span class="hljs-keyword">new</span> <span class="hljs-built_in">this</span>.userModel({
       ...createUserInput,
       password: hash,
     });

     <span class="hljs-keyword">return</span> createdUser.save();
   }

   <span class="hljs-keyword">async</span> loginUser(loginInput: LoginUserInput) {
     <span class="hljs-keyword">const</span> { email, password } = loginInput;
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.userModel.findOne({ email });

     <span class="hljs-keyword">if</span> (!user) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid credentials'</span>);
     }

     <span class="hljs-keyword">const</span> isMatch = <span class="hljs-keyword">await</span> bcrypt.compare(password, user.password);

     <span class="hljs-keyword">if</span> (!isMatch) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Password or email address incorrect'</span>);
     }

     <span class="hljs-keyword">return</span> user;
   }
 ...
</code></pre>
<p> Get ready for some exciting news! We're taking our user creation to the next level by implementing password encryption using bcrypt. As we start adding features such as JWT tokens, authorization, and a complete registration flow, we don't want our user.service file to become overwhelming. In a NestJS architecture, service files serve the purpose of interacting with the database, so we'll keep our user.service file as the go-to source for retrieving, verifying, and modifying data in the user collection. Instead of including login logic in the user.service file, we'll create a brand new module dedicated to handling authentication (and possibly authorization) in our application.</p>
<p> That auth module will be responsible for:</p>
<ul>
<li><p>Creating a new user, making sure their passwords are encrypted correctly(as above)</p>
</li>
<li><p>Logging in an existing user making sure it sends a valid jwt token</p>
</li>
<li><p>Implementing Guards(sort of middleware) so that we protect some mutations and queries</p>
</li>
</ul>
</li>
</ol>
<p>    This topic is a bit confusing and less documented in the nest official doc so, I will walk through the most important aspects of it:</p>
<ol>
<li><p>Let’s generate new auth.module.ts, auth.service.ts and auth.resolver.ts files using nest cli</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># generate auth module files</span>
 $ <span class="hljs-built_in">cd</span> src/app &amp;&amp; nest g module auth &amp;&amp; nest g service auth &amp;&amp; nest g resolver auth
</code></pre>
</li>
<li><p>Install required dependencies to achieve authentication, nest supports passport, and jwt, so we will use that pair to achieve magic.</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># install dependancies</span>
 $ yarn add @types/passport-local @types/passport-jwt -D
 $ yarn add @nestjs/passport passport passport-local @nestjs/jwt passport-jwt
</code></pre>
<p> Those are required dependencies that will help us achieve our end goal.</p>
</li>
<li><p>How do we want our queries and mutations to be proceeded? How do we want to receive auth responses? Well, in real-world scenarios, we expect to receive a token when we log in, using our email address and password(local strategy in good terms), with that said, lets create dto files that prepare us to implement that:</p>
<p> 🛠️ You can follow along and add the <code>app/auth/dto/login-response.ts</code> and the <code>app/auth/dto/login-user.input.ts</code> files that look like:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401686229/43d3fa95-ef43-4295-8cd6-88428b9ae9ab.png" alt class="image--center mx-auto" /></p>
<p> <em>login-response.ts file</em></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675401716028/7fcdb7cf-5009-4995-a4c1-60b9f4eda0ff.png" alt class="image--center mx-auto" /></p>
<p> <em>login-user.input.ts image15 - auth/dto files</em></p>
<p> Nothing strange right? Let’s go ahead with the service and resolvers</p>
</li>
<li><p>In the auth.service.ts file, we need to add a couple of methods that will be the authentication login:</p>
<ul>
<li><p>a <strong>validateUser</strong> method: this method will retrieve data from the database using the findOneByEmail method, will check either the password matches, then will return a user object or null in case the user isn’t valid, here is how it looks like:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth.service.ts file</span>

  ...
  <span class="hljs-keyword">async</span> validateUser(loginUserInput: LoginUserInput) {
      <span class="hljs-keyword">const</span> { email, password } = loginUserInput;
      <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.userService.findOneByEmail(email);

      <span class="hljs-keyword">const</span> isMatch = <span class="hljs-keyword">await</span> bcrypt.compare(password, user?.password);

      <span class="hljs-keyword">if</span> (user &amp;&amp; isMatch) {
        <span class="hljs-keyword">return</span> user;
      }

      <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    }
  ...
</code></pre>
<p>  This looks a bit similar to what we’ve done before, nothing really new, however, you may notice that we are using a <code>UserService</code> instance, to be able to do that, don’t forget to import the user module in the auth module, then user the property <code>exports</code> from user module file, to be able to access its service in the outside, by default, they are private in nest.</p>
</li>
<li><p>a <strong>login</strong> method: this method will only take a validated user(by the previous method) and return an instance of <code>LoginResponse</code> object, means contains an authToken in it, here is how it shoud look:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth.service.ts</span>

  ...
  login(user: User) {
      <span class="hljs-keyword">return</span> {
        user,
        authToken: <span class="hljs-built_in">this</span>.jwtService.sign(
          {
            email: user.email,
            name: user.name,
            sub: user._id,
          },
          {
            secret: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'JWT_SECRET'</span>),
          },
        ),
      };
    }
  ...
</code></pre>
<p>  Few things to mention here that may be interesting. First, we are using another environment variable, that holds the jwt secret word(JWT_SECRET). We installed the <code>@nestjs/jwt</code> module early, that package has a built-in module that we’ll use to be able to use the <code>jwtService</code> instance, just as we did for the config service, as we are getting used to inject modules in our modules, let’s configure the <code>JwtModule</code> into our <code>AuthModule</code></p>
<p>  In the <code>auth.module.ts</code> file, let’s replace the content by the followings:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth.module.ts</span>
  <span class="hljs-comment">// all imports</span>

  ...
  <span class="hljs-meta">@Module</span>({
    providers: [
      AuthService,
      AuthResolver,
      JwtService,
    ],
    <span class="hljs-comment">// We nedd to make sure we've imported the userModule, because we're using it's service</span>
    imports: [
      UserModule,
      PassportModule,
      ConfigModule,
      JwtModule.registerAsync({
        inject: [ConfigService],
        imports: [ConfigModule],
        useFactory: <span class="hljs-function">(<span class="hljs-params">configService: ConfigService</span>) =&gt;</span> {
          <span class="hljs-keyword">const</span> properties: JwtModuleOptions = {
            secret: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'JWT_SECRET'</span>),
            signOptions: {
              expiresIn: <span class="hljs-string">'24h'</span>,
            },
          };
          <span class="hljs-keyword">return</span> properties;
        },
      }),
    ],
  })
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthModule {}
</code></pre>
<p>  As you can see here, we have used the <code>registerAsync()</code> method from JwtModule to be able to inject the secret key asynchronously, then returned the config options using the <code>useFactory</code> property, just like we did for the MongooseModule in the root module. As we are in this file, we also added the PassportModule, as we will need it soon for our strategies. Well done, we can now use the jwt service instance worry freely.</p>
</li>
<li><p>a <strong>signup</strong> method: as you can imagine, this will contain the logic for our signup feature, here is how it looks like:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth.service.ts</span>

  ...
  <span class="hljs-keyword">async</span> signup(payload: CreateUserInput) {
      <span class="hljs-comment">// CHECK IF THE USER ALREADY EXISTS</span>
      <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.userService.findOneByEmail(payload.email);

      <span class="hljs-keyword">if</span> (user) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'User already exists, login instead'</span>);
      }

      <span class="hljs-comment">// GENERATE HASH PASSWORD TO SAVE</span>
      <span class="hljs-keyword">const</span> hash = <span class="hljs-keyword">await</span> bcrypt.hash(
        payload.password,
        <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'SALT_ROUND'</span>)),
      );

      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.userService.createUser({ ...payload, password: hash });
    }
  ...
</code></pre>
<p>  Same logic here, first we make sure the user doesn’t exist, then we proceed with the creation of the account(interaction with the database), we decide to let this responsability to the user.service logic file.</p>
</li>
</ul>
</li>
</ol>
<p>        As you can see here, each method above has a single responsability, we have simple methods easy to understand and that can be scaled at any moment, just like we did, creating a new module. Well done, let’s move in to the guards, and understand why we need them:</p>
<ul>
<li><p>Into the <code>auth.resolver.ts</code> file, let’s see how we consume those logic</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth.resolver.ts </span>

  ...
  <span class="hljs-meta">@Mutation</span>(<span class="hljs-function">() =&gt;</span> LoginUserResponse)
    <span class="hljs-meta">@UseGuards</span>(GqlAuthGuard)
    login(
      <span class="hljs-meta">@Args</span>(<span class="hljs-string">'loginUserInput'</span>) loginUserInput: LoginUserInput,
      <span class="hljs-meta">@Context</span>() context: <span class="hljs-built_in">any</span>,
    ) {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.authService.login(context.user);
    }
  ...
</code></pre>
<p>  This might be a bit confusing but, let’s break it down in a second.</p>
<p>  We are using one of the most important feature of nest in this part, <code>Guards</code> . Guards are a way to add middleware logic to specific mutations or queries(routes or controllers for Rest APIs) in NestJS, they can be used to perform tasks such as authentication, authorization, or request validation before a request is handled by the corresponding controller.</p>
<p>  This also means, before running the <code>auth.service.login()</code> method, our guards will first be executed. We have used <code>@UseGuards</code> from <code>@nest/common</code> and we have passed in a custom guard called <code>GqlAuthGuard</code> that we haven’t implemented yet. How will it work?</p>
<p>  The guard will receive input that we pass through <code>loginUserInput</code>, then verify if the user is valid, and at the end, if the user isn’t valid, it will return an exception, if the user is valid, it will put that user in what we call <code>context</code> of the request, that context will contain information about the user who is querying the server, and in this particular use case, that user will also be the one who needs to login.</p>
<p>  Let’s now implement 2 additional files:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// gql-auth.guards.ts</span>

  <span class="hljs-keyword">import</span> { ExecutionContext, Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
  <span class="hljs-keyword">import</span> { GqlExecutionContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/graphql'</span>;
  <span class="hljs-keyword">import</span> { AuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;

  <span class="hljs-meta">@Injectable</span>()
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> GqlAuthGuard <span class="hljs-keyword">extends</span> AuthGuard(<span class="hljs-string">'local'</span>) {
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
      <span class="hljs-built_in">super</span>();
    }

    getRequest(context: ExecutionContext) {
      <span class="hljs-keyword">const</span> ctx = GqlExecutionContext.create(context);
      <span class="hljs-keyword">const</span> req = ctx.getContext();
      req.body = ctx.getArgs().loginUserInput;

      <span class="hljs-keyword">return</span> req;
    }
  }
</code></pre>
<p>  As this us not a rest api, Nest recommend to build you own guard, that extends the <code>AuthGuard</code> We are also returning a request, that has a body property coming from the arguments we have passed <code>@Args('loginUserInput') loginUserInput: LoginUserInput</code> that’s pretty much great, we next have to implement a localStategy that will treat that context.</p>
<p>  Here is how our <code>LocalStategy</code> class will look like:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// auth/local.strategy.ts</span>

  <span class="hljs-keyword">import</span> { Strategy } <span class="hljs-keyword">from</span> <span class="hljs-string">'passport-local'</span>;
  <span class="hljs-keyword">import</span> { PassportStrategy } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;
  <span class="hljs-keyword">import</span> { Injectable, UnauthorizedException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
  <span class="hljs-keyword">import</span> { AuthService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.service'</span>;

  <span class="hljs-meta">@Injectable</span>()
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LocalStrategy <span class="hljs-keyword">extends</span> PassportStrategy(Strategy) {
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> authService: AuthService</span>) {
      <span class="hljs-built_in">super</span>({
        usernameField: <span class="hljs-string">'email'</span>,
      });
    }

    <span class="hljs-keyword">async</span> validate(email: <span class="hljs-built_in">string</span>, password: <span class="hljs-built_in">string</span>) {
      <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.authService.validateUser({ email, password });

      <span class="hljs-keyword">if</span> (!user) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UnauthorizedException();
      }

      <span class="hljs-keyword">return</span> user;
    }
  }
</code></pre>
<p>  First, when extending the <code>PassportStrategy</code> class, we have added the <code>usernameField: 'email',</code> property, by default, PassportStrategy only accepts username and password as parameters, but in our use case, we don’t have a username, we have an email instead, to make our LocalStrategy accept that, we need to specify that, our <code>usernameField</code> is email instead of the username. Then, every strategy we will implement has to contain a <code>validate()</code> method, this is what the auth-guard will execute first, missing it in our class will make it fail, make sure we have it. Next, we are just calling the <code>validateUser</code> method from the authService, as we saw before, it will return a valid user if the credentials were correct, or a null if not, in the second case, we throw a native nest error <code>UnauthorizedException();</code> telling the user that he’s not authorized to proceed with the request, other wise, we just return the user(or not 🤪) The fact is that, as you can see in our login Mutation, the data we are using for the auth.service is already part of the context <code>return this.authService.login(context.user);</code> so we can or not return a user, since it won’t be used in our use case.</p>
<p>  Well done, the login is completed.</p>
<p>  We have an additional guard implemented in the <code>jwt-auth.guards.ts</code> file which I let you guys discover by yourself, checking our <code>#54640</code></p>
<p>  Now we can protect some resolvers from being queried by an unauthenticated user, let’s say for example the <code>createBook</code> mutation, if we add a guard, here is how it looks like:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// book.resolver.ts</span>

  ...
  <span class="hljs-comment">// Only connected users with valid jwt tokens must create a book(Authentication)</span>
    <span class="hljs-meta">@Mutation</span>(<span class="hljs-function">() =&gt;</span> Book)
    <span class="hljs-meta">@UseGuards</span>(JwtAuthGuard)
    createBook(<span class="hljs-meta">@Args</span>(<span class="hljs-string">'createBookInput'</span>) createBookInput: CreateBookInput) {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.bookService.createBook(createBookInput);
    }
  ...
</code></pre>
<p>  This way, if you are not providing a valid token in the headers, you can’t proceed. I have protected the create, update and delete mutations, as you can see in the GitHub repository.</p>
</li>
</ul>
<p>🤩 Great job getting through that! It may have been a bit dense, but it was definitely worth it. Now that you've learned about it, don't be afraid to re-read the section or practice what you've learned on your own. Remember, even though it may be confusing at first, this is an important part of building a NestJS application.</p>
<h2 id="heading-deploy-the-codebase">Deploy the codebase</h2>
<p>We have covered the most core features of Nest, and we have made a long way to get here, let’s celebrate … Oups, before we celebrate, we need to ship our app to clients, in this last part, we will deploy the app we just built on</p>
<p>To deploy the app, you can use any platform of your choice, you can use <a target="_blank" href="https://render.com/">Render</a> for this first part, the setup is straightforward, however, make sure in the start command you put <code>yarn start:prod</code> and make sure you have imported all our environment variables, to be injected to our app on build time</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In the first part of this series provided an introduction to Nest, a powerful NodeJS framework that allows you to build efficient and scalable applications. By diving into the fundamentals of Nest, we have set up the foundation for our final project, while exploring a couple of key concepts of the framework, a powerful GraphQL API using Nest and MongoDB. With this knowledge, we were able to understand the nest architecture and built on top of built-in packages, hope you enjoyed building along. In the next parts of this series, we will continue to build upon this foundation and learn how to implement best practices and scale our app in a real-world scenario, such as TDD, CI/CD, and microservice architecture.</p>
<p>Have you enjoyed this reading? Let’s connect on <a target="_blank" href="https://twitter.com/PacifiqueLinja1?t=e7uqnNZVMv8HEAjRP2lL0w&amp;s=09">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/pacifique-linjanja">LinkedIn</a> and <a target="_blank" href="https://github.com/pacyL2K19">Github</a> for more content like this.</p>
<p>Thank you for reading, and sharing this with your network, meet you in the second part.</p>
<h2 id="heading-additional-resources">Additional resources</h2>
<ul>
<li><p><a target="_blank" href="https://nestjs.com/">Nest.js official documentation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/nestjs/graphql">@nestjs/graphql documentation</a></p>
</li>
<li><p><a target="_blank" href="https://www.google.com/amp/s/www.freecodecamp.org/news/how-to-deploy-nodejs-application-with-render/amp/">Deploying on render</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>