<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>nestjs - Hard Wired</title>
	<atom:link href="https://www.hardwired.dev/tag/nestjs/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.hardwired.dev</link>
	<description></description>
	<lastBuildDate>Sun, 09 Jun 2024 19:19:18 +0000</lastBuildDate>
	<language>cs</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://www.hardwired.dev/wp-content/uploads/2022/10/android-chrome-256x256-1-150x150.png</url>
	<title>nestjs - Hard Wired</title>
	<link>https://www.hardwired.dev</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>NestJS Chapter 01 &#8211; New Project</title>
		<link>https://www.hardwired.dev/2024/06/09/nestjs-chapter-01-new-project/</link>
		
		<dc:creator><![CDATA[John Doe]]></dc:creator>
		<pubDate>Sun, 09 Jun 2024 19:09:38 +0000</pubDate>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[crud]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[endpoint]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[nestjs]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[RESTfull]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://www.hardwired.dev/?p=2235</guid>

					<description><![CDATA[<p>When you use an app, whether it's a web app or a desktop app, that communicates with a remote server &#62;&#62;&#62;</p>
<p>The post <a href="https://www.hardwired.dev/2024/06/09/nestjs-chapter-01-new-project/">NestJS Chapter 01 – New Project</a> first appeared on <a href="https://www.hardwired.dev">Hard Wired</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="bsf_rt_marker"></div><p>When you use an app, whether it's a web app or a desktop app, that communicates with a remote server over the internet, you can be 99% sure there is an API server involved. API servers are the hidden part of the application where almost all the magic happens. One option for creating APIs is <a href="https://docs.nestjs.com/">NestJS</a>, and we will explore it a little bit.</p>
<p><strong>Key Benefits of NestJS:</strong></p>
<ul>
<li><strong>Scalability</strong>: NestJS is built with scalability in mind, making it easy to manage large-scale applications. Its modular architecture allows developers to split their applications into small, reusable modules.</li>
<li><strong>TypeScript Support</strong>: As a framework built on top of TypeScript, NestJS offers all the benefits of TypeScript, including type safety, improved code readability, and maintainability.</li>
<li><strong>Extensive Ecosystem</strong>: NestJS has a rich ecosystem of libraries and tools, which simplifies the development process. It integrates seamlessly with other popular libraries and frameworks like <a href="https://expressjs.com/en/guide/routing.html">Express</a>, <a href="https://fastify.dev/docs/latest/">Fastify</a>, and more.</li>
<li><strong>Ease of Use</strong>: The framework is designed to be developer-friendly, with a well-documented API and a robust CLI that helps in generating boilerplate code, thereby reducing development time.</li>
<li><strong>Dependency Injection</strong>: NestJS uses a powerful dependency injection system, which makes it easier to manage dependencies and promotes better code organization and testability.</li>
</ul>
<blockquote>
<p><strong>Disclaimer:</strong> This article is not primarily intended for people who are new to programming. It is written with the expectation of some experience in programming. To be honest, my motivation for writing this article is to compile my NestJS developer notes, and I've chosen to present them in article form. It will not explain NestJS in detail, nor its architecture. Instead, it will focus on solving specific problems I have encountered. I hope you find it useful. </p>
</blockquote>
<p>In Chapter 1, we will install NestJS and bring the API server to life.</p>
<p>Make sure you are using the latest LTS version of <a href="https://nodejs.org/en">NodeJS</a>.</p>
<p>For project creation and management, we will use <a href="https://docs.nestjs.com/cli/overview">@nestjs/cli</a>. The easiest way is to install it globally.</p>
<pre><code class="language-shell">npm i -g @nestjs/cli</code></pre>
<p>Then, in your projects folder, simply use the <code>nest</code> command to create a new project.</p>
<pre><code class="language-shell">nest new hardwired-nestjs-api-chapter-01</code></pre>
<p>You will be asked which package manager you want to use. I use <code>npm</code>.</p>
<p>When it is done, just delete the <code>.spec.ts</code> files from the <code>src</code> folder. We don't care about tests right now. A bunch of things are already set up, like <code>prettier</code>, <code>eslint</code>, and <code>TypeScript</code> configuration. Useful scripts are prepared in <code>package.json</code>.</p>
<pre><code class="language-json">&quot;scripts&quot;: {
    &quot;build&quot;: &quot;nest build&quot;,
    &quot;format&quot;: &quot;prettier --write \&quot;src/**/*.ts\&quot; \&quot;test/**/*.ts\&quot;&quot;,
    &quot;start&quot;: &quot;nest start&quot;,
    &quot;start:dev&quot;: &quot;nest start --watch&quot;,
    &quot;start:debug&quot;: &quot;nest start --debug --watch&quot;,
    &quot;start:prod&quot;: &quot;node dist/main&quot;,
    &quot;lint&quot;: &quot;eslint \&quot;{src,apps,libs,test}/**/*.ts\&quot; --fix&quot;,
    &quot;test&quot;: &quot;jest&quot;,
    &quot;test:watch&quot;: &quot;jest --watch&quot;,
    &quot;test:cov&quot;: &quot;jest --coverage&quot;,
    &quot;test:debug&quot;: &quot;node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand&quot;,
    &quot;test:e2e&quot;: &quot;jest --config ./test/jest-e2e.json&quot;
  },</code></pre>
<p>For now, we only need <code>start:dev</code> to run the development version. In the <code>src</code> folder, you can find <code>main.ts</code>, which is the entry point to our API, along with <code>app.controller.ts</code>, <code>app.module.ts</code>, and <code>app.service.ts</code>. You can find a perfect explanation of the NestJS architecture in the chapters <a href="https://docs.nestjs.com/controllers">Controllers</a>, <a href="https://docs.nestjs.com/providers">Providers</a>, and <a href="https://docs.nestjs.com/modules">Modules</a> in the NestJS documentation.</p>
<p><code>main.ts</code> is pretty simple. Just includes <code>@netjs/core</code>, <code>app.module</code> and bootstrap our application.</p>
<pre><code class="language-typescript">import { NestFactory } from &#039;@nestjs/core&#039;;
import { AppModule } from &#039;./app.module&#039;;

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

bootstrap();</code></pre>
<p>When you run <code>npm run start:dev</code>, the API will run on port 3000, and you will be able to access it at <code>http://localhost:3000</code>.</p>
<p>Controllers are where you define your routes. In <code>app.controller.ts</code>, there is one <code>GET</code> route.</p>
<pre><code class="language-typescript">import { Controller, Get } from &#039;@nestjs/common&#039;;
import { AppService } from &#039;./app.service&#039;;

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}</code></pre>
<p>The <code>@Get</code> decorator without parameters in <code>app.controller.ts</code> indicates that you will access this route with <code>/</code>. It's the root route, and you can access it at <code>http://localhost:3000</code>. This route calls the service method <code>getHello()</code>, which returns the string <code>Hello World!</code>. Services are where your business logic resides.</p>
<pre><code class="language-typescript">import { Injectable } from &#039;@nestjs/common&#039;;

@Injectable()
export class AppService {
  getHello(): string {
    return &#039;Hello World!&#039;;
  }
}</code></pre>
<p>You can access <code>http://localhost:3000</code> in your browser, and if the development server is running, you will see <code>Hello World!</code>. However, as an API developer, you may want a better way to call your API during development. I recommend using <a href="https://insomnia.rest/">Insomnia</a>.</p>
<p>When you call <code>http://localhost:3000</code> using Insomnia, you will get the same result as in the browser. However, as you add more routes and JSON responses, you will appreciate the usefulness of Insomnia.</p>
<pre><code>Hello World!</code></pre>
<p><code>Hello World</code> is okay, but not very useful. Let's build something more meaningful.</p>
<p>First, we should discuss how to organize our routes to avoid a mess later. A good way is to organize them into <code>resources</code>. A resource can be <code>user</code>, <code>article</code>, <code>comment</code>, etc. For resource bases, we will use plurals, for example, <code>users</code>, <code>articles</code>, and <code>comments</code>. It is a good practice to follow <a href="https://restfulapi.net/">REST</a> principles when creating an API. One of my favorite articles on this topic is <a href="https://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api">Best Practices for Designing a Pragmatic RESTful API</a>.</p>
<p>Sometimes it is easier for programmers to use just <code>GET</code> and <code>POST</code> methods for all routes, but this does not adhere to <code>RESTful</code> principles. <code>RESTful</code> principles provide strategies to handle <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> actions. It is better to use the full potential of <code>HTTP</code> methods. For example, when we take the resource <code>user</code>:</p>
<ul>
<li><code>GET /users</code> - retrieves a list of users</li>
<li><code>GET /users/1</code> - retrieves the user with id 1</li>
<li><code>POST /users</code> - creates a new user</li>
<li><code>PUT /users/1</code> - updates the user with id 1</li>
<li><code>PATCH /users/1</code> - partially updates the user with id 1</li>
<li><code>DELETE /users/1</code> - deletes the user with id 1</li>
</ul>
<p>You can also combine resources. For instance, to get the articles for a user, one route could be <code>GET /users/1/articles</code>.</p>
<p>If you want to like an article, the API endpoint could be <code>PUT /articles/1/like</code>. You can use aliases, filtering, sorting, limiting, and pagination constructs, but this is a complex and highly opinionated field suitable for many articles. I think the best quick dive is provided in the article I mentioned earlier, written by <a href="https://www.vinaysahni.com/">Vinay Sahni</a>.</p>
<p>Earlier in the article, I said &quot;Let's build something more meaningful,&quot; but that was a lie. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> For a quick demonstration of how to create a resource and follow methods, we will use something completely useless.</p>
<p>We will create a route <code>GET /zodiac-signs</code>. This route will return a list of zodiac signs with date ranges. I borrowed the list from <a href="https://github.com/helmasaur/zodiac-signs/blob/main/data/zodiac.json">here</a>.</p>
<p>To create a NestJS resource, we will use the <code>nest cli</code>.</p>
<pre><code class="language-shell">nest g res zodiac-signs --no-spec</code></pre>
<ul>
<li><code>nest</code> - nest command</li>
<li><code>g</code> - generate</li>
<li><code>res</code> - resource</li>
<li><code>zodiac-sign</code> - resource-name</li>
<li><code>--no-spec</code> - do not generate tests</li>
</ul>
<p>After you enter the command, you will be asked what type of transport layer you want to use. Choose REST API. The next question will be whether you would like to create CRUD entry points. I choose no; I will create them on my own.</p>
<p>When it is done, in your <code>src</code> folder, you will see a folder named <code>zodiac-signs</code>, and it will contain <code>zodiac-signs.controller.ts</code>, <code>zodiac-signs.module.ts</code>, and <code>zodiac-signs.service.ts</code>.</p>
<p>Nest CLI automatically connects your new resource/module to the app.</p>
<p>We will start with <code>zodiac-signs.service.ts</code>.</p>
<pre><code class="language-typescript">import { Injectable } from &#039;@nestjs/common&#039;;

@Injectable()
export class ZodiacSignsService {
    signs = {
        aries: {
            symbol: &#039;&#x2648;&#039;,
            dateMin: &#039;2000-03-21&#039;,
            dateMax: &#039;2000-04-20&#039;,
        },
        taurus: {
            symbol: &#039;&#x2649;&#039;,
            dateMin: &#039;2000-04-21&#039;,
            dateMax: &#039;2000-05-21&#039;,
        },
        gemini: {
            symbol: &#039;&#x264a;&#039;,
            dateMin: &#039;2000-05-22&#039;,
            dateMax: &#039;2000-06-21&#039;,
        },
        cancer: {
            symbol: &#039;&#x264b;&#039;,
            dateMin: &#039;2000-06-22&#039;,
            dateMax: &#039;2000-07-22&#039;,
        },
        leo: {
            symbol: &#039;&#x264c;&#039;,
            dateMin: &#039;2000-07-23&#039;,
            dateMax: &#039;2000-08-22&#039;,
        },
        virgo: {
            symbol: &#039;&#x264d;&#039;,
            dateMin: &#039;2000-08-23&#039;,
            dateMax: &#039;2000-09-23&#039;,
        },
        libra: {
            symbol: &#039;&#x264e;&#039;,
            dateMin: &#039;2000-09-24&#039;,
            dateMax: &#039;2000-10-23&#039;,
        },
        scorpio: {
            symbol: &#039;&#x264f;&#039;,
            dateMin: &#039;2000-10-24&#039;,
            dateMax: &#039;2000-11-22&#039;,
        },
        sagittarius: {
            symbol: &#039;&#x2650;&#039;,
            dateMin: &#039;2000-11-23&#039;,
            dateMax: &#039;2000-12-21&#039;,
        },
        capricorn: {
            symbol: &#039;&#x2651;&#039;,
            dateMin: &#039;2000-12-22&#039;,
            dateMax: &#039;2000-01-20&#039;,
        },
        aquarius: {
            symbol: &#039;&#x2652;&#039;,
            dateMin: &#039;2000-01-21&#039;,
            dateMax: &#039;2000-02-19&#039;,
        },
        pisces: {
            symbol: &#039;&#x2653;&#039;,
            dateMin: &#039;2000-02-20&#039;,
            dateMax: &#039;2000-03-20&#039;,
        },
    };

    findAll() {
        return this.signs;
    }
}</code></pre>
<p>In the <code>ZodiacSignsService</code> class, we have our logic. The list of signs is stored as a class property named <code>signs</code>. The method that returns this list is <code>findAll()</code>. It is a good practice for the route <code>GET /zodiac-signs</code> to use the service method <code>findAll</code>, and for <code>GET /zodiac-signs/:name</code> to use the service method <code>findOne</code>. This uniform naming system will help you orient yourself in a large code base.</p>
<p>Next will be <code>zodiac-signs.controller.ts</code>.</p>
<pre><code class="language-typescript">import { Controller, Get } from &#039;@nestjs/common&#039;;
import { ZodiacSignsService } from &#039;./zodiac-signs.service&#039;;

@Controller(&#039;zodiac-signs&#039;)
export class ZodiacSignsController {
  constructor(private readonly zodiacSignsService: ZodiacSignsService) {}

  @Get()
  findAll() {
    return this.zodiacSignsService.findAll();
  }
}</code></pre>
<p>We create a method <code>findAll</code> decorated with <code>@Get</code> decorator, which, without parameters, instructs the app router to point to the <code>findAll</code> method in the <code>ZodiacSignsController</code> in response to a <code>GET /zodiac-signs</code> request.</p>
<p>That's all for now. Make sure the development server is running (<code>npm run start:dev</code>). Then, you can access <code>http://localhost:3000/zodiac-signs</code>. The expected result is the same JSON as we have in <code>ZodiacSignsService</code>.</p>
<p>Okay, it's not much, but it's enough to get started. In the next chapter, we'll take a look at DTOs (Data Transfer Objects).</p>
<p>You can find project on my <a href="https://github.com/eduardtomasek/hardwired-nestjs-chapter-01-new-project">GitHub</a>.</p>
<p>Happy coding!</p>

<div class="twitter-share"><a href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.hardwired.dev%2F2024%2F06%2F09%2Fnestjs-chapter-01-new-project%2F&#038;via=hessevalentino" class="twitter-share-button">Tweet</a></div><p>The post <a href="https://www.hardwired.dev/2024/06/09/nestjs-chapter-01-new-project/">NestJS Chapter 01 – New Project</a> first appeared on <a href="https://www.hardwired.dev">Hard Wired</a>.</p>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
