<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by timewn1 on Medium]]></title>
        <description><![CDATA[Stories by timewn1 on Medium]]></description>
        <link>https://medium.com/@timewn1?source=rss-95eb80eef94b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8KU4Dv74emoNcsj5c4Nh2w.png</url>
            <title>Stories by timewn1 on Medium</title>
            <link>https://medium.com/@timewn1?source=rss-95eb80eef94b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:54:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@timewn1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating Login with Selenium and Node.js]]></title>
            <link>https://medium.com/@timewn1/automating-login-with-selenium-and-node-js-644ace8239fe?source=rss-95eb80eef94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/644ace8239fe</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[automatic-testing]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[timewn1]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 07:32:06 GMT</pubDate>
            <atom:updated>2023-12-19T07:32:06.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rds9dsAdQdQMTYQV" /></figure><p><strong>Introduction:</strong></p><p>In today’s tech landscape, automation is king. Repetitive tasks, especially those prone to human error, can be streamlined and optimized with powerful tools like Selenium. In this article, we’ll embark on a beginner-friendly journey to build your first web automation script using Selenium in a Node.js project. Buckle up as we dive into code, conquer login forms, and unlock the potential of automated web testing!</p><p><strong>Setting the Stage:</strong></p><ol><li>Prerequisites: Ensure you have Node.js and npm installed. Basic JavaScript knowledge is helpful.</li><li>Project Setup: Clone the provided Git repository <a href="https://github.com/timewn1/automation-login.git">https://github.com/timewn1/automation-login.git</a>.</li><li>Install Module: In your terminal, run npm install.</li></ol><p><strong>Scripting the Login Flow:</strong></p><p>Open the index.js file in your editor. We’ll walk through the code snippet:</p><pre>// Import the library.<br>const { Builder, By } = require(&#39;selenium-webdriver&#39;);<br><br>// Define an asynchronous function that will automate the login process for a website.<br>async function automationLogin() {<br>  // Create a new instance using the Chrome browser.<br>  const driver = await new Builder().forBrowser(&#39;chrome&#39;).build();<br><br>  try {<br>    // Try to open the website that we want to log in to.<br>    await driver.get(&#39;https://example.com&#39;);<br><br>    // Find the email input element and enter your email address.<br>    const emailElement = await driver.findElement(By.id(&#39;email&#39;));<br>    await emailElement.sendKeys(&#39;your email&#39;);<br><br>    // Find the password input element and enter your password.<br>    const passwordElement = await driver.findElement(By.id(&#39;password&#39;));<br>    await passwordElement.sendKeys(&#39;your password&#39;);<br><br>    // Find the submit button and click it to log in.<br>    const submitButton = await driver.findElement(By.id(&#39;submit&#39;));<br>    await submitButton.click();<br>  } catch (err) {<br>    // Log any errors that occur.<br>    console.error(err);<br>  } finally {<br>    // Quit the driver when we&#39;re done.<br>    await driver.quit();<br>  }<br>}<br><br>// Call the `automationLogin()` function to start the login process.<br>automationLogin();</pre><p>Building the Chrome Driver: We create a new Chrome browser instance.</p><pre>const driver = await new Builder().forBrowser(&#39;chrome&#39;).build();</pre><p>Opening the Website: Navigate to the target website.</p><pre>await driver.get(&#39;https://example.com&#39;);</pre><p>Locating Elements: We use <em>driver.findElement()</em> to identify specific elements by their ID:</p><pre>// Email element<br>const emailElement = await driver.findElement(By.id(&#39;email&#39;));<br><br>// Password element<br>const passwordElement = await driver.findElement(By.id(&#39;password&#39;));<br><br>// Submit button element<br>const submitButton = await driver.findElement(By.id(&#39;submit&#39;));</pre><p>User Interaction: Simulate user actions:</p><pre>// Enter email<br>await emailElement.sendKeys(&#39;your email&#39;);<br><br>// Enter password<br>await passwordElement.sendKeys(&#39;your password&#39;);<br><br>// Click submit button<br>await submitButton.click();</pre><p><strong>Running the Script:</strong></p><p>Save the index.js file and run it in your terminal with node index.js. If successful, your script should automatically open the website, fill in the login credentials, and click the submit button.</p><p><strong>Additional Tips:</strong></p><p>Consider using environment variables to store sensitive information like login credentials.<br>Utilize headless mode for faster script execution and reduced visual clutter.<br>Explore advanced features like JavaScript execution and browser extensions for even greater automation power.</p><p>This article is your springboard into the world of web automation with Selenium.</p><p>By embracing the power of automation, you can unlock new efficiencies, enhance your coding capabilities, and become a sought-after tech talent. So, take your first step today and watch your automation journey unfold!</p><p>I hope this helps you write a compelling Medium article that showcases your automation skills and inspires others to embark on their own automation journey. Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=644ace8239fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test Your NestJS Application with Jest in 4 Steps]]></title>
            <link>https://medium.com/@timewn1/how-to-test-your-nestjs-application-with-jest-in-4-steps-4902c32ac5d8?source=rss-95eb80eef94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4902c32ac5d8</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[timewn1]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 04:48:05 GMT</pubDate>
            <atom:updated>2023-03-04T04:48:05.120Z</atom:updated>
            <content:encoded><![CDATA[<p>NestJS is a server-side backend framework that is becoming increasingly popular within the Node community. In this article, we’ll suggest how to <strong>make the most out of Nest testing tools</strong> from <a href="https://www.theodo.fr/expertise/developpement-nodejs-nest">our experience at Theodo</a>.</p><h3>What you’ll learn in this article</h3><ul><li>An intro to NestJS</li><li>A quick overview of good testing practices</li><li>How to write unit and E2E tests for your backend with Jest</li><li>How to mock services and HTTP calls</li></ul><h3>About NestJS</h3><p>Inspired from Angular, Nest uses Typescript and Javascript and compared to other Node.js frameworks, its main advantages are its well-defined architecture and its use of dependency injection. After comparing different Node frameworks, Theodo has recently <a href="https://blog.theodo.com/2019/03/choose-best-nodejs-framework/">added Nest into their technical stack</a>, a choice that we do not regret: it is <strong>secure, scalable and maintainable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*bSLduGnK0lKWPyUC.png" /></figure><p>An overview of Node.js frameworks. Read more about <a href="https://blog.theodo.com/2019/03/choose-best-nodejs-framework/">how we chose ours</a>.</p><p>Besides all this, NestJS has one notable aspect: <strong>it offers its developers advantages to write automated tests</strong>. Why? First, because of the use of dependency injection, a design pattern that allows dependencies to be managed at runtime instead of compile time. This makes mocking and unit testing much easier! Second, because it’s written in Typescript, which makes up for robust code. Third, it already comes with <a href="https://jestjs.io/">Jest</a>, a Javascript testing framework. That’s great!</p><h3>NestJS Architecture</h3><p>Basic NestJS architecture is composed of Modules, Controllers and Services.</p><p><a href="https://blog.theodo.com/2019/05/an-overview-of-nestjs-typeorm-release-your-first-application-in-less-than-30-minutes/">When you start a basic Nest application</a>, in the <em>/src</em> folder you’ll see five files: the main file, one app module, one controller, one service and a test file for the controller.</p><pre>src ├── app.controller.ts ├── app.module.ts ├── app.controller.spec.ts ├── app.service.ts └── main.ts</pre><p>Ideally, as your project becomes bigger you’ll want to create separate modules for your features (and corresponding controllers and services). <strong>Modules are the main pieces of your app</strong>: inside them, you’ll find the declaration of all its components (controllers, services) and its dependencies (imports). <strong>Controllers are where you’ll define your routes and call their corresponding services</strong>. The idea is to keep controllers as clean and as independent from your external services as possible. Finally, <strong>services contain the core of your business logic</strong> and the focus of your tests. A module usually contains more than one service and controller.</p><h3>Our example application</h3><p>To illustrate how to test your NestJS application, we’ve built a simple example. We have a backend with one route and two services that finds a student in a simulated database by his or her name and calculate the GPA (grade average) if he or she exists.</p><p>This route will be used to exemplify two kinds of tests: unit and end-to-end.</p><p>We started our application by following the steps defined <a href="https://docs.nestjs.com/first-steps">here</a>. Everything we’ll need is included in this default installation! For the tests, we’ll create a new subfolder named “Test”. Inside, we’ll put our new testing files: <em>student.service.spec.ts</em> and <em>app.e2e-spec.ts</em>.</p><pre>src ├── api.service.ts ├── app.controller.ts ├── app.module.ts ├── main.ts ├── student.service.ts └── test ├── app.e2e-spec.ts └── student.service.spec.ts</pre><p>Our <em>app.module</em> looks like this:</p><pre>import { Module, HttpModule } from &#39;@nestjs/common&#39;; import { AppController } from &#39;./app.controller&#39;; import { StudentService } from &#39;./student.service&#39;; import { ApiService } from &#39;./api.service&#39;; @Module({ imports: [HttpModule], controllers: [AppController], providers: [ApiService, StudentService], }) export class AppModule {}</pre><p>The <em>app.controller</em> file looks like this:</p><pre>import { Controller, Get, Query, HttpException } from &#39;@nestjs/common&#39;; import { StudentService } from &#39;./student.service&#39;; @Controller(&#39;student&#39;) export class AppController { constructor(private readonly studentService: StudentService) {} @Get(&#39;/gpa&#39;) async getStudentGpa( @Query(&#39;firstName&#39;) firstName: string, @Query(&#39;lastName&#39;) lastName: string, ): Promise&lt;number&gt; { if (!firstName || !lastName) { throw new HttpException(&#39;Incomplete student information&#39;, 400); } return await this.studentService.getGpa(firstName, lastName); } }</pre><p>Here’s the <strong>studentService </strong>:</p><pre>import { Injectable, HttpException } from &#39;@nestjs/common&#39;; import { ApiService } from &#39;./api.service&#39;; interface Student { name: string; grades: number[]; } @Injectable() export class StudentService { constructor(private apiService: ApiService) {} public async getGpa(firstName: string, lastName: string): Promise&lt;number&gt; { const student: Student = await this.apiService.getStudent( firstName, lastName, ); if (!student || !student.grades) { throw new HttpException(&#39;Cannot find student or student grades&#39;, 404); } let gpa: number = 0; for (const grade of student.grades) { gpa += grade / student.grades.length; } return gpa; } }</pre><p>And, finally, our <em>api.service</em> looks like this:</p><pre>import { Injectable, HttpService } from &#39;@nestjs/common&#39;; interface Student { name: string; grades: number[]; } @Injectable() export class ApiService { constructor(private http: HttpService) {} async getStudent(firstName: string, lastName: string): Promise&lt;Student&gt; { const url = `....../get-student?firstName=${firstName}&amp;lastName=${lastName}`; const response = await this.http.get(url).toPromise(); return response.data; } }</pre><p>The API URL is fake but here it will not be a problem, as we’ll be most interested in mocking this call.</p><p>Ok, we’re all set! So, how can we test our code?</p><h3>4 steps to a happy NestJS testing:</h3><h3>1) Know and apply good testing practices</h3><p><strong>Having a well tested backend is an important step for having a successful product</strong>. Most of the business logic is there, and you’ll want to make sure that neither a “future you” or someone else will break the beautiful code you’ve written today.</p><p>Therefore, it is never too late to stop and revise some of the best practices when it comes to software testing:</p><h3>a) Be familiar with the testing pyramid</h3><p>We usually divide automated tests into three categories: unit, integration and end-to-end tests. Unit tests are smaller and simpler: they are meant to test one internal method at a time, without contacting the external world. Integration tests encompass bigger methods and calls to external services (which, however, should be mocked). Finally, end-to-end tests serve as an extensive check into your routes, to see if everything’s ok in real conditions.</p><p>The <a href="https://martinfowler.com/articles/practical-test-pyramid.html">testing pyramid</a> has been described with some different shapes, but the main idea remains universal: we should write <strong>more of the simpler tests and less of the more complicated ones</strong>, without leaving any of them behind.</p><h3>b) KISS</h3><p>The KISS (Keep It Simple, Stupid) principle applies to tests as well. Testing can be very time-consuming, so we should avoid at all costs over-engineering and losing time, right?</p><p>Not all logic needs to be tested! <strong>Focus where the biggest added value is: it will be the best compromise for you and your client. As always, quality matters more than quantity.</strong></p><h3>c) Write code that it’s easy to maintain</h3><p>The best practice is to <strong>test the result of your method</strong>, not the implementation details. When finishing writing a test, ask yourself: if I ever refactor the tested method (without changing the result), will I have to modify this test? If the answer is yes, you can simplify your tests.</p><h3>d) Give a chance to Test Driven Development (TDD)</h3><p>TDD is a development technique that lots of people have heard of (and even tried once), but don’t use that often. When you start each chunk of logic of your code with a test that fails and then you write the minimal amount of code that makes it pass, you’re ensuring that you’re not over-engineering your app and that your tests are useful and reliable.</p><h3>2) Make the most out of Typescript</h3><p><a href="https://www.typescriptlang.org/">Typescript</a> is a programming language that allows static typing and compiles to pure Javascript. Nest does not oblige developers to use Typescript, however, it fully supports it and we encourage you to use it!</p><p>While using Typescript is not exactly <em>testing</em>, it is included on this list because <strong>it makes your code more robust and actively avoids many bugs</strong>. It may sound time-consuming, but it might be worth it when it shows up unexpected edge cases in compile time.</p><p><strong>Good practices:</strong></p><ul><li><strong>Type not only your method parameters, but also your method returns</strong>. This will help you ensure that what you’re sending at your service is what your controller is expecting.</li><li><strong>Avoid using “any”</strong>: even if you don’t know all the data you’re dealing with, you can partially type what you know.</li></ul><h3>3) Write your isolated unit tests with Jest and Nest testing tools</h3><h4>About Jest</h4><p>As we mentioned before, <a href="https://jestjs.io/">Jest</a> is a Javascript testing framework whose mission is to simplify the developer experience writing tests in frontend and backend projects. <strong>It is integrated with the default Nest installation</strong>, which is very cool!</p><p>Of course, you’re not obliged to keep it and use it if you have another preferred testing framework, such as Mocha or Chai. At Theodo, we stick to Jest, because it is a framework that fulfill our needs. Hint: if you’d like to give it a try, it is possible to <a href="https://jestjs.io/docs/en/migration-guide">convert code from other frameworks</a> to Jest. Another hint: this <a href="https://devhints.io/jest">Jest cheatsheet</a> may help you if you’re a beginner!</p><h4>Mocking a service</h4><p>In our example backend, the external service is the student database API. In a real, more complicated project, external services can be everywhere: REST APIs, authentication, content management, databases, payment services, among other possibilities. If we were to call all those services after every code modification, the test suite would be painstakingly long. Luckily, Nest and Jest make mocking a lot easier.</p><h4>Ok, let’s write tests!</h4><p>That’s how our unit test file will look like:</p><p><em>student.service.spec.ts</em></p><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;; import { ApiService } from &#39;../api.service&#39;; import { StudentService } from &#39;../student.service&#39;; class ApiServiceMock { getStudent(firstName: string, lastName: string) { return { name: &#39;Jane Doe&#39;, grades: [3.7, 3.8, 3.9, 4.0, 3.6], }; } }</pre><p>To write isolated unit tests, it’s common to mock all dependencies of a method or a service. In our StudentService unit test, we’ll mock AppService by creating an ApiServiceMock class.</p><p>This is the ideal procedure if you want to mock everything from this service. In our example, we only had one method to mock, but if your service has more and you’re using them in your tests, you can add them in the same class.</p><p>Next, we’re setting up our test configurations inside beforeAll:</p><pre>describe(&#39;StudentService&#39;, () =&gt; { let app: TestingModule; let studentService: StudentService; beforeAll(async () =&gt; { const ApiServiceProvider = { provide: ApiService, useClass: ApiServiceMock, }; app = await Test.createTestingModule({ providers: [StudentService, ApiServiceProvider], }).compile(); studentService = app.get&lt;StudentService&gt;(StudentService); });</pre><p>We’ll use the TestingModule from the Nest testing package, which takes every provider and module you need for testing. Inside it, we define a mock provider that recognizes when ApiService is called and use the ApiServiceMock class instead. That’s all we need for mocking!</p><p>The BeforeAll method sets a one-time setup for the test suite. If you need the setup to run before each test, use BeforeEach.</p><pre>describe(&#39;getGpa&#39;, () =&gt; { it(&#39;should get student GPA&#39;, async () =&gt; { const expectedGpa = 3.8; const gpa = await studentService.getGpa(&#39;Jane&#39;, &#39;Doe&#39;); expect(gpa).toEqual(expectedGpa); }); }); });</pre><p>Use “toBe” if you want the response to be the instance of the expected response. Prefer “toEqual” if it’s not the case, but you want the values to match.</p><h3>4) Put it all together: write an end-to-end test (also with Jest!)</h3><p>Writing E2E tests can be long and challenging, but fortunately, NestJS and Jest already have what it takes to write them! We want to test our entire route, calling the two services.</p><p>Our goal is to check if our whole route corresponds to our requirements:</p><ul><li>Calculate the GPA if the student exists and has grades,</li><li>Throw an error if the query is incomplete, if the student hasn’t been found or if he/she doesn’t have any grades.</li></ul><h4>Mocking an HTTP call</h4><p>In an E2E test, the idea is to also call your external services, but here we’re mocking the HttpService for simplicity reasons. This means we’ll call the APIService and we’ll use the Jest function spyOn to simulate our HTTP response.</p><h4>Writing our test:</h4><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;; import * as request from &#39;supertest&#39;; import { AppModule } from &#39;../app.module&#39;; import { INestApplication, HttpService, HttpModule } from &#39;@nestjs/common&#39;; import { ApiService } from &#39;../api.service&#39;; import { StudentService } from &#39;../student.service&#39;; import { AxiosResponse } from &#39;axios&#39;; import { of } from &#39;rxjs&#39;; describe(&#39;AppController (e2e)&#39;, () =&gt; { let app: INestApplication; let httpService: HttpService;</pre><p>First, we need to set up the dependencies of the test:</p><pre>beforeAll(async () =&gt; { const testAppModule: TestingModule = await Test.createTestingModule({ imports: [AppModule, HttpModule], providers: [ApiService, StudentService], }).compile(); app = testAppModule.createNestApplication(); httpService = testAppModule.get&lt;HttpService&gt;(HttpService); await app.init(); });</pre><p>We called beforeAll as we did for the unit test, but this time we’re importing two modules and calling the <em>createNestApplication</em> method, that simulates our real app.</p><p>Notice that one of the imported modules is the real HttpModule. That’s because the mock action will happen inside of each test! It’s the simplest solution in our situation, because the mocked response will change for each test case.</p><p>We have four tests:</p><p>First, if we insert the name of a valid student and there are grades associated with this student, we expect to receive the correct GPA.</p><pre>it(&#39;GET student GPA if API finds the student&#39;, async () =&gt; { const result: AxiosResponse = { data: { name: &#39;Jane Doe&#39;, grades: [3.7, 3.8, 3.9, 4.0, 3.6], }, status: 200, statusText: &#39;OK&#39;, headers: {}, config: {}, }; jest.spyOn(httpService, &#39;get&#39;).mockImplementationOnce(() =&gt; of(result)); const expectedGpaString = &#39;3.8&#39;; const response = await request(app.getHttpServer()) .get(&#39;/student/gpa?firstName=Jane&amp;lastName=Doe&#39;) .expect(200); expect(response.text).toEqual(expectedGpaString); });</pre><p>In the line <em>await request(app.getHttpServer()).get(‘/student/gpa?firstName=Jane&amp;lastName=Doe’).expect(200)</em>, we’re simulating our app controller when a GET request for a student is made and collecting the response if the final HTTP status is 200.</p><p>Notice that we defined an AxiosResponse object with the student response we want (all properties are obligatory). Then, with <em>jest.spyOn</em>, we can mock the implementation of the <em>get</em> method of httpService. The <em>of()</em> method transforms the <em>result</em> object into an observable.</p><p>In the next test, we should expect an HTTP 400 code if the query isn’t complete.</p><pre>it(&#39;throws error if GET request does not include student name&#39;, async () =&gt; { return await request(app.getHttpServer()) .get(&#39;/student/gpa?firstName=&amp;lastName=&#39;) .expect(400); });</pre><p>Now, we should expect an HTTP 404 code if the query is complete, but the student hasn’t been found.</p><pre>it(&#39;throws error if API cannot find the student&#39;, async () =&gt; { const result: AxiosResponse = { data: {}, status: 404, statusText: &#39;&#39;, headers: {}, config: {}, }; jest.spyOn(httpService, &#39;get&#39;).mockImplementationOnce(() =&gt; of(result)); return await request(app.getHttpServer()) .get(&#39;/student/gpa?firstName=Anna&amp;lastName=Julia&#39;) .expect(404); });</pre><p>Finally, we should also expect an HTTP 404 code if the student exists, but has no grades array associated.</p><pre>it(&#39;throws error if student does not have grades assigned&#39;, async () =&gt; { const result: AxiosResponse = { data: { name: &#39;Davy Jones&#39; }, status: 200, statusText: &#39;&#39;, headers: {}, config: {}, }; jest.spyOn(httpService, &#39;get&#39;).mockImplementationOnce(() =&gt; of(result)); return await request(app.getHttpServer()) .get(&#39;/student/gpa?firstName=Davy&amp;lastName=Jones&#39;) .expect(404); }); });</pre><p>Now that we wrote all our tests, we might want to check our test coverage. With Jest, it’s pretty simple: go to your <em>package.json</em> file, find the Jest configuration and add ‘<em>“collectCoverage”: true’</em> to it. You can also add <em>‘“verbose”: true’</em> if you want more details into your test report.</p><p>Let’s run our test suite (with <em>npm test </em>or <em>yarn test</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*IwLOmowYejAKqySO.png" /></figure><p>Everything passed ! And, as expected, we’re fully covered.</p><p>We’ve arrived at the end of this list. If you followed through, you’ll have the main tools for a nice test suite in your NestJS application!</p><p>If you’d like to check our testing files created for this article, you can clone our <a href="https://github.com/deboraornellas/nestjs-testing">public Github repo</a>.</p><p>Do you use other techniques for testing a NestJS app? Would you recommend other steps to be a better tester? Share in the comments!</p><p><em>Originally published at </em><a href="https://blog.theodo.com/2019/06/test-nestjs-with-jest-typescript/"><em>https://blog.theodo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4902c32ac5d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to connect PostgreSQL with NestJS]]></title>
            <link>https://medium.com/@timewn1/how-to-connect-postgresql-with-nestjs-54e33be32b95?source=rss-95eb80eef94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e33be32b95</guid>
            <dc:creator><![CDATA[timewn1]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 05:07:25 GMT</pubDate>
            <atom:updated>2023-02-18T05:07:25.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Database</h3><p>Nest is database agnostic, allowing you to easily integrate with any SQL or NoSQL database.</p><h3>TypeORM Integration</h3><p>For integrating with SQL and NoSQL databases, Nest provides the <a href="http://twitter.com/nestjs/typeorm">@nestjs/typeorm</a> package. Nest uses TypeORM because it’s the most mature Object Relational Mapper (ORM) available for TypeScript. Since it’s written in TypeScript, it integrates well with the Nest framework.</p><blockquote>npm install --save @nestjs/typeorm typeorm pg pg-connection-string</blockquote><p>Once the installation process is complete, we can import the TypeOrmModule into the root AppModule.</p><p><em>app.module.ts</em></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot({<br>      type: &#39;postgres&#39;,<br>      host: &#39;localhost&#39;,<br>      port: 5432,<br>      username: &#39;root&#39;,<br>      password: &#39;password&#39;,<br>      database: &#39;test-db&#39;,<br>      entities: [],<br>      synchronize: true,<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><h4>Repository pattern</h4><p><a href="https://github.com/typeorm/typeorm">TypeORM</a> supports the repository design pattern, so each entity has its own repository. These repositories can be obtained from the database data source.</p><p><em>user.entity.ts</em></p><pre>import { Entity, Column, PrimaryGeneratedColumn } from &#39;typeorm&#39;;<br><br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  firstName: string;<br><br>  @Column()<br>  lastName: string;<br><br>  @Column({ default: true })<br>  isActive: boolean;</pre><p>To begin using the User entity, we need to let TypeORM know about it by inserting it into the entities array in the module forRoot() method options</p><p><em>app.module.ts</em></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { User } from &#39;./users/user.entity&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot({<br>      type: &#39;postgres&#39;,<br>      host: &#39;localhost&#39;,<br>      port: 5432,<br>      username: &#39;root&#39;,<br>      password: &#39;password&#39;,<br>      database: &#39;test-db&#39;,<br>      entities: [User],<br>      synchronize: true,<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><p><em>users.module.ts</em></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br>import { UsersController } from &#39;./users.controller&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Module({<br>  imports: [TypeOrmModule.forFeature([User])],<br>  providers: [UsersService],<br>  controllers: [UsersController],<br>})<br>export class UsersModule {}</pre><p>This module uses the forFeature() method to define which repositories are registered in the current scope. With that in place, we can inject the UsersRepository into the UsersService using the <a href="http://twitter.com/InjectRepository">@InjectRepository</a>() decorator:</p><p><em>users.service.ts</em></p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Injectable()<br>export class UsersService {<br>  constructor(<br>    @InjectRepository(User)<br>    private usersRepository: Repository&lt;User&gt;,<br>  ) {}<br><br>  findAll(): Promise&lt;User[]&gt; {<br>    return this.usersRepository.find();<br>  }<br><br>  findOne(id: number): Promise&lt;User&gt; {<br>    return this.usersRepository.findOneBy({ id });<br>  }<br><br>  async remove(id: string): Promise&lt;void&gt; {<br>    await this.usersRepository.delete(id);<br>  }<br>}</pre><p>If you want to use the repository outside of the module which imports TypeOrmModule.forFeature, you’ll need to re-export the providers generated by it. You can do this by exporting the whole module, like this:</p><p><em>users.module.ts</em></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Module({<br>  imports: [TypeOrmModule.forFeature([User])],<br>  exports: [TypeOrmModule]<br>})<br>export class UsersModule {}</pre><h4>Example</h4><p>A working example is available <a href="https://github.com/nestjs/nest/tree/master/sample/07-sequelize">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e33be32b95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Swagger OpenAPI document in NestJS]]></title>
            <link>https://medium.com/@timewn1/how-to-use-swagger-openapi-document-in-nestjs-16ff9ebb304a?source=rss-95eb80eef94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ff9ebb304a</guid>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[back-end-development]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[timewn1]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 06:32:35 GMT</pubDate>
            <atom:updated>2023-02-13T06:32:35.896Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://swagger.io/specification/">OpenAPI</a> specification is a language-agnostic definition format used to describe RESTful APIs. Nest provides a dedicated <a href="https://github.com/nestjs/swagger">module</a> which allows generating such a specification by leveraging decorators.</p><h3><strong>Installation</strong></h3><p>To begin using it, we first install the required dependency.</p><blockquote>$ npm install --save @nestjs/swagger</blockquote><h3>Bootstrap</h3><p>Once the installation process in complete, open the <em>main.ts</em> file and initialize Swagger using the <em>SwaggerModule </em>class:</p><p><strong>main.ts</strong></p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { SwaggerModule, DocumentBuilder } from &#39;@nestjs/swagger&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  const config = new DocumentBuilder()<br>    .setTitle(&#39;Nest API&#39;)<br>    .setDescription(&#39;The Nest API description&#39;)<br>    .setVersion(&#39;1.0&#39;)<br>    .addTag(&#39;API&#39;)<br>    .build();<br>  const document = SwaggerModule.createDocument(app, config);<br>  SwaggerModule.setup(&#39;api&#39;, app, document);<br><br>  await app.listen(3000);<br>}<br><br>bootstrap();</pre><p>The <em>DocumentBuilder </em>helps to structure a base document that conforms to the OpenAPI Specification. It provides several methods that allow setting such properties as title, description, version, etc. In order to create a full document (with all HTTP routes defined) we use the <em>createDocument()</em> method of the <em>SwaggerModule </em>class. This method takes two arguments, an application instance and a Swagger options object. Alternatively, we can provide a third argument, which should be of type <em>SwaggerDocumentOptions</em>. More on this in the Document options section.</p><p>Once we create a document, we can call the setup() method. It accepts:</p><ol><li>The path to mount the Swagger UI</li><li>An application instance</li><li>The document object instantiated above</li><li>Optional configuration parameter (read more here)</li></ol><p>Now you can run the following command to start the HTTP server:</p><blockquote>npm run start</blockquote><p>While the application is running, open your browser and navigate to <em>http://localhost:3000/api</em>. You should see the Swagger UI.</p><p>As you can see, the <em>SwaggerModule </em>automatically reflects all of your endpoints.</p><p>A working example is available <a href="https://github.com/nestjs/nest/tree/master/sample/11-swagger">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ff9ebb304a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>