{"id":4439,"date":"2020-08-19T18:58:50","date_gmt":"2020-08-19T11:58:50","guid":{"rendered":"https:\/\/briswell-vn.com\/?p=4439"},"modified":"2020-08-19T19:02:31","modified_gmt":"2020-08-19T12:02:31","slug":"what-is-nestjs","status":"publish","type":"post","link":"https:\/\/www.briswell-vn.com\/en\/news\/what-is-nestjs\/","title":{"rendered":"NestJs &#8211; A backend NodeJS framework"},"content":{"rendered":"<p><\/p>\n<h2><strong>Introduction<\/strong><\/h2>\n<p>Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript) and combines elements of<\/p>\n<ol>\n<li>OOP (Object Oriented Programming),<\/li>\n<li>FP (Functional Programming), and<\/li>\n<li>FRP (Functional Reactive Programming).<\/li>\n<\/ol>\n<p>Why choose NestJS among many other powerful NodeJS frameworks out there? As of July 2020, it boasts over 28k GitHub stars. The improvement of JavaScript as a web development programming language has been the reason behind the rise of many JavaScript frameworks. And NestJS is not an exception. With so many cool features, NestJS can help the developers to easily and efficiently create backend applications, RESTful API.<\/p>\n<p>*** A survey on stateofjs.com on most used Javascript frameworks 2019 shows that Nest is also one of the most popular Javascript frameworks besides Express, Next.js, Koa, Meteor, Sails, Feathers, Nuxt, Gatsby.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4489 size-full aligncenter\" src=\"https:\/\/briswell-vn.com\/wp-content\/uploads\/2020\/07\/chart_nestjs.png\" alt=\"\" width=\"700\" height=\"340\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28164620\/chart_nestjs.png 700w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28164620\/chart_nestjs-300x146.png 300w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p style=\"text-align: center;\">Credit: stateofjs.com<\/p>\n<p>&nbsp;<\/p>\n<h2><strong>Installation and create new NestJS application<\/strong><\/h2>\n<p>Please make sure that <a href=\"https:\/\/nodejs.org\/en\/\"><strong>Node.js<\/strong><\/a> (&gt;= 10.13.0) is installed on your operating system<\/p>\n<p>Setting up a new project is quite simple with the\u00a0<a href=\"https:\/\/docs.nestjs.com\/cli\/overview\"><strong>Nest CLI<\/strong><\/a>. With\u00a0<a href=\"https:\/\/www.npmjs.com\/\"><strong>npm<\/strong><\/a>\u00a0installed, you can create a new Nest project with the following commands in your OS terminal:<\/p>\n<pre>$ npm i -g @nestjs\/cli<\/pre>\n<p>Install nestjs-cli<\/p>\n<pre>$ nest new project-name<\/pre>\n<p>Create new project<\/p>\n<p>The\u00a0project\u00a0directory will be created, node modules and a few other boilerplate files will be installed.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4456\" src=\"https:\/\/briswell-vn.com\/wp-content\/uploads\/2020\/07\/source_tree_nestjs-3-1024x276.png\" alt=\"\" width=\"556\" height=\"150\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28095425\/source_tree_nestjs-3-1024x276.png 1024w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28095425\/source_tree_nestjs-3-300x81.png 300w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28095425\/source_tree_nestjs-3-768x207.png 768w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28095425\/source_tree_nestjs-3.png 1400w\" sizes=\"auto, (max-width: 556px) 100vw, 556px\" \/><\/p>\n<p>Next, run the program by typing the following command:<\/p>\n<pre>npm start\r\n<\/pre>\n<p>Then go to the browser at <a href=\"http:\/\/localhost:3000\">http:\/\/localhost:3000<\/a>, we should see the app is running.<\/p>\n<h2><\/h2>\n<h2><strong>Configure and switch between ExpressJS and Fastify<\/strong><\/h2>\n<p>There are two HTTP platforms that NestJS can support: <strong>Express <\/strong>and <strong>Fastify<\/strong>.<\/p>\n<p><strong>Express:<\/strong>\u00a0 is very popular among Nodejs web development community. Express is a well-known minimalist web framework for node.<\/p>\n<p><strong>Fastify<\/strong>: has better performance. It is a high performance and low overhead framework highly focused on providing maximum efficiency and speed.<\/p>\n<p>You can choose the one that best suits your needs.<\/p>\n<p>By default, Nest makes use of the <strong>Express<\/strong> framework.<\/p>\n<div>\n<pre>import '.\/LoadEnv';\r\nimport { NestFactory } from '@nestjs\/core';\r\nimport { AppModule } from '.\/app.module';\r\nimport { ValidationPipe } from '@nestjs\/common';\r\nasync function bootstrap() {\r\n\u00a0\u00a0try {\r\n\u00a0\u00a0\u00a0\u00a0const app = await NestFactory.create(AppModule);\r\n\u00a0\u00a0\u00a0\u00a0app.useGlobalPipes(new ValidationPipe());\r\n\u00a0\u00a0\u00a0\u00a0await app.listen(process.env.PORT || 3000);\r\n\u00a0\u00a0} catch (err) {\r\n\u00a0\u00a0\u00a0\u00a0console.log(err);\r\n\u00a0\u00a0}\r\n}\r\nbootstrap();<\/pre>\n<p>To configure NestJS to use <strong>Fastify<\/strong>, firstly we need to install the required package:<\/p>\n<pre>$ npm i --save @nestjs\/platform-fastify<\/pre>\n<p>Inside bootstrap function in main.ts, import the package and configure to use <strong>Fastify <\/strong>as the following code:<\/p>\n<pre>const app = await NestFactory.create&lt;NestFastifyApplication&gt;(\r\n  AppModule,\r\n  new FastifyAdapter()\r\n);<\/pre>\n<h2><\/h2>\n<h2><strong><span style=\"background: #FDFDFD;\">Routing in <\/span>NestJS<\/strong><\/h2>\n<p>Routing in NestJS is very easy to be defined. We&#8217;ll use the\u00a0<strong>@Controller(\u2018users\u2019)<\/strong>\u00a0decorator to define the base routing for users. The routes for Post, Get, Put, Delete, Param, and Body marked by Nestjs annotation.<\/p>\n<p>GET \/users<\/p>\n<p>GET \/users\/id<\/p>\n<p>POST \/users<\/p>\n<p>Using a path prefix in a <strong>@Controller(&#8216;users&#8217;)<\/strong> decorator allows us to easily group a set of related routes, and minimize repetitive code.<\/p>\n<div>\n<pre>@Controller('users')\r\nexport class UsersController {\r\n \u00a0@Get()\r\n \u00a0find() {\r\n \u00a0\u00a0\u00a0return this.usersService.find();\r\n \u00a0}\r\n \u00a0@Get(':id')\r\n \u00a0findById(@Param('id') id) {\r\n \u00a0\u00a0\u00a0return this.usersService.findById(id);\r\n \u00a0}\r\n \u00a0@Post()\r\n \u00a0add(@Body() createUserDto: CreateUserDto) {\r\n \u00a0\u00a0\u00a0return this.usersService.add(createUserDto);\r\n \u00a0}\r\n \u00a0@Patch(':id')\r\n \u00a0update(@Param('id') id, @Body() updateUserDto: UpdateUserDto) {\r\n \u00a0\u00a0\u00a0return this.usersService.update(id, updateUserDto);\r\n \u00a0}\r\n}<\/pre>\n<p>We can access the request object by instructing Nest to inject it by adding the\u00a0<strong>@Body()<\/strong>\u00a0decorator to the handler&#8217;s signature.<\/p>\n<div>\n<pre>@Post()\r\n add(@Body() createUserDto: CreateUserDto) {\r\n \u00a0\u00a0return this.usersService.add(createUserDto);\r\n}<\/pre>\n<p><strong>@Param()<\/strong> is used to decorate a method parameter. As seen in the code below, we can access the id parameter by referencing <strong>@Param(\u2018id\u2019)<\/strong>.<\/p>\n<div>\n<pre>@Get(':id')\r\n \u00a0findById(@Param('id')\u00a0id)\u00a0{\r\n \u00a0\u00a0\u00a0return\u00a0this.usersService.findById(id);\r\n}<\/pre>\n<h2><strong>Main concepts in Nest<\/strong><\/h2>\n<p><strong>Providers:<\/strong> are a fundamental concept in Nest. Many of the basic Nest classes may be treated as a provider \u2013 <span style=\"text-decoration: underline;\">services, repositories, factories, helpers<\/span>, and so on. The main idea of a provider is that it can inject\u00a0dependencies; this means objects can create various relationships with each other, and the function of &#8220;wiring up&#8221; instances of objects can largely be delegated to the Nest runtime system. A provider is simply a class annotated with an\u00a0@Injectable()\u00a0decorator.<\/p>\n<p>Let&#8217;s start creating simple service. UsersService \u2013 This service is responsible for storing and returning data, and is designed for use by UsersController, so we should create a provider so that these two classes can create relationships with each other.<\/p>\n<div>\n<pre>@Injectable()\r\nexport class UsersService {\r\n \u00a0constructor(\r\n \u00a0\u00a0\u00a0@InjectRepository(User)\r\n \u00a0\u00a0\u00a0private usersRepository: Repository&lt;User&gt;,\r\n \u00a0) {}\r\n \u00a0async findOne(username: string): Promise&lt;User | undefined&gt; {\r\n \u00a0\u00a0\u00a0return this.usersRepository.findOne({ name: username });\r\n \u00a0}\r\n \u00a0async find(option?: FindManyOptions&lt;User&gt;): Promise&lt;User[]&gt; {\r\n \u00a0\u00a0\u00a0return this.usersRepository.find(option);\r\n \u00a0}\r\n \u00a0async findById(id: number): Promise&lt;User&gt; {\r\n \u00a0\u00a0\u00a0return this.usersRepository.findOne(id);\r\n \u00a0}\r\n \u00a0async add(user: CreateUserDto): Promise&lt;User&gt; {\r\n \u00a0\u00a0\u00a0return this.usersRepository.save(user);\r\n \u00a0}\r\n \u00a0async update(user: UpdateUserDto): Promise&lt;User&gt; {\r\n \u00a0\u00a0\u00a0return this.usersRepository.save(user);\r\n \u00a0}\r\n}<\/pre>\n<p><strong>HINT<\/strong>: It is possible to create a service using CLI: <code>nest g service users<\/code> @Injectable () will help Nest know that this is a provider. So Nest will automatically create an instance of this class and pass it to the UsersController:<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Modules:<\/strong> A module is a class annotated with a @Module() decorator. The @Module() decorator provides metadata that Nest\u00a0makes use of to organize the application structure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4464 size-full aligncenter\" src=\"https:\/\/briswell-vn.com\/wp-content\/uploads\/2020\/07\/module.png\" alt=\"\" width=\"657\" height=\"357\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28110509\/module.png 657w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28110509\/module-300x163.png 300w\" sizes=\"auto, (max-width: 657px) 100vw, 657px\" \/><\/p>\n<p>Each application has at least one module, a\u00a0root module. \u00a0Each module can stand for a specific component or feature in your application. Modules are\u00a0strongly\u00a0recommended as an effective way to organize your components. Your source code structure may look like this:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4466 size-full aligncenter\" src=\"https:\/\/briswell-vn.com\/wp-content\/uploads\/2020\/07\/source-structure.jpg\" alt=\"\" width=\"232\" height=\"470\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28121304\/source-structure.jpg 232w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28121304\/source-structure-148x300.jpg 148w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2020\/07\/28121304\/source-structure-123x250.jpg 123w\" sizes=\"auto, (max-width: 232px) 100vw, 232px\" \/><\/p>\n<h2><\/h2>\n<h2><strong>GraphQL in Nest<\/strong><\/h2>\n<p>As many know, <strong><a href=\"https:\/\/graphql.org\/\">GraphQL<\/a>\u00a0<\/strong>is a powerful query language for APIs and a runtime for fulfilling those queries with your existing data. With NestJS, we can also a powerful GraphQL server.<\/p>\n<p>Assuming that you already have a basic understanding of GraphQL, now let\u2019s jump to find out how to use GraphQL with Nest.<\/p>\n<p>Start by installing the required packages:<\/p>\n<pre>npm i --save @nestjs\/graphql apollo-server-express graphql-tools graphql type-graphql<\/pre>\n<p>Depending on what underlying platform you use (Express or Fastify), you must also install either\u00a0apollo-server-express\u00a0or\u00a0apollo-server-fastify.<\/p>\n<p>Here is a list of the key concepts you need to know about:<\/p>\n<ol>\n<li>Schema<\/li>\n<li>Query<\/li>\n<li>Mutation<\/li>\n<li>Type<\/li>\n<li>Resolver<\/li>\n<\/ol>\n<p>Nestjs provides us with two different ways of building GraphQL applications:<\/p>\n<ol>\n<li>Schema first<\/li>\n<li>Code first<\/li>\n<\/ol>\n<h2><\/h2>\n<h2><strong>Summary<\/strong><\/h2>\n<p>With all the features that have been listed above, it verifies that NestJS has so many cool features that can help the developers to easily build a server-side application. Even though it still has some drawbacks but its power and usefulness can not be denied. Below is the summary of pros and cons of Nest:<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Pros:<\/strong><\/p>\n<p>Open source<\/p>\n<p>Powerful but super friendly to work with<\/p>\n<p>Easy to understand documentation<\/p>\n<p>Fast development<\/p>\n<p>Angular style syntax for the backend<\/p>\n<p>NodeJS ecosystem<\/p>\n<p>Graphql support easy<\/p>\n<p>Good architecture<\/p>\n<p>Typescript makes it well integrated in vscode<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Cons:<\/strong><\/p>\n<p>User base is small. Less help on Stackoverflow<\/p>\n<p>Updates with breaking changes<\/p>\n<p>Unstable<\/p>\n<p>Difficult to debug<\/p>\n<h2><strong>References<\/strong><\/h2>\n<p><a href=\"https:\/\/expressjs.com\/\">https:\/\/expressjs.com\/<\/a><\/p>\n<p><a href=\"https:\/\/www.fastify.io\/\">https:\/\/www.fastify.io\/<\/a><\/p>\n<p><a href=\"https:\/\/docs.nestjs.com\/graphql\/quick-start\">https:\/\/docs.nestjs.com\/graphql\/quick-start<\/a><\/p>\n<p><a href=\"https:\/\/docs.nestjs.com\/techniques\/performance\">https:\/\/docs.nestjs.com\/techniques\/performance<\/a><\/p>\n<p><a href=\"https:\/\/docs.nestjs.com\/fundamentals\/execution-context%23reflection-and-metadata\">https:\/\/docs.nestjs.com\/fundamentals\/execution-context#reflection-and-metadata<\/a><\/p>\n<p><a href=\"https:\/\/medium.com\/google-developers\/exploring-es7-decorators-76ecb65fb841\">https:\/\/medium.com\/google-developers\/exploring-es7-decorators-76ecb65fb841<\/a><\/p>\n<p><a href=\"https:\/\/www.apollographql.com\/blog\/graphql-vs-rest-5d425123e34b\/\">https:\/\/www.apollographql.com\/blog\/graphql-vs-rest-5d425123e34b\/<\/a><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<div>\n<div>\n<div>\n<div><\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p><\/p>","protected":false},"excerpt":{"rendered":"<p>Introduction Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming). Why choose NestJS among many other powerful NodeJS frameworks out there? As of July 2020, it [&hellip;]<\/p>\n","protected":false},"author":18,"featured_media":4443,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"footnotes":""},"categories":[4,71],"tags":[],"class_list":["post-4439","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news","category-it-tec"],"_links":{"self":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/4439","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/users\/18"}],"replies":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/comments?post=4439"}],"version-history":[{"count":0,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/4439\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/media\/4443"}],"wp:attachment":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/media?parent=4439"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/categories?post=4439"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/tags?post=4439"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}