{"id":31178,"date":"2023-02-28T11:54:31","date_gmt":"2023-02-28T19:54:31","guid":{"rendered":"https:\/\/coderpad.io\/?p=31178"},"modified":"2023-06-05T13:38:50","modified_gmt":"2023-06-05T20:38:50","slug":"defining-nestjs-and-how-to-get-started","status":"publish","type":"post","link":"https:\/\/coderpad.io\/blog\/development\/defining-nestjs-and-how-to-get-started\/","title":{"rendered":"Defining NestJS and How to Get Started"},"content":{"rendered":"\n<p>Because of the rapid growth of JavaScript and <a href=\"https:\/\/coderpad.io\/languages\/typescript\/\">TypeScript frameworks<\/a> and libraries, a huge selection of packages is available through popular package management systems such as Node Package Manager (NPM).&nbsp;<\/p>\n\n\n\n<p>Some packages are created to specifically address one or two particular issues. However, others may try to recreate existing solutions.&nbsp;In this article, we&#8217;ll provide an overview of NestJS, one of the leading TypeScript frameworks. We&#8217;ll answer questions such as &#8220;What is NestJS?&#8221; and &#8220;How do I get started using it?&#8221; to give you&nbsp;a better understanding of what it is and how to use it.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is NestJS?<\/strong><\/h2>\n\n\n\n<p>NestJS is a TypeScript framework for developing highly scalable, flexible, and production-ready Node.js back-end applications. At the time of writing, NestJS had over <strong>52,000 stars<\/strong> and <strong>6300 forks<\/strong> on GitHub, and it&#8217;s one of the most popular TypeScript frameworks for <a href=\"https:\/\/coderpad.io\/languages\/node\/\">Node.js.<\/a>&nbsp;<\/p>\n\n\n\n<p>In addition, NestJS supports various JavaScript versions such as ES6, ES7, and ES8. As a result, you can create back-end applications using pure JavaScript or by using one of its derivatives, such as TypeScript.&nbsp;&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Features of NestJS<\/strong><\/h2>\n\n\n\n<p>To gain a better understanding of the core features of NestJS, let&#8217;s take a closer look at them.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Uses TypeScript<\/strong><\/h3>\n\n\n\n<p>NestJS uses TypeScript for the composition of back-end applications. TypeScript is a strongly typed programming language that helps to reduce errors related to type checking and inconsistencies when developing large-scale and enterprise applications. This is in contrast to JavaScript, which doesn&#8217;t have the same level of type checking. By using TypeScript, NestJS helps to ensure the stability and reliability of code.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Powerful command line interface<\/strong><\/h3>\n\n\n\n<p>Are you a fan of the terminal or CMD prompt? Don&#8217;t worry, NestJS has you covered! It provides a powerful command line interface (CLI) program that can be used to develop&nbsp;applications with NestJS without relying on graphical user interfaces. With just a few simple commands, you can create and manage any part of the NestJS framework, such as databases, modules, controllers, and service files.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Developer-friendly documentation<\/strong><\/h3>\n\n\n\n<p>The quality of documentation can have a significant impact on the adoption of a framework such as NestJS. If the documentation isn&#8217;t well written, comprehensive, and easy to understand, developers may be less likely to use it. Fortunately, NestJS offers detailed, developer-friendly,&nbsp;and straightforward documentation that covers most development questions and provides clear instructions on how to get started with the framework.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Microservice architecture pattern<\/strong><\/h3>\n\n\n\n<p>NestJS supports microservice architecture development by making it easy to connect to popular microservice tools like Kafka, gPRC, RabbitMQ, etc.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Supports popular libraries<\/strong><\/h3>\n\n\n\n<p>NestJS makes application development quicker and more efficient by supporting popular tools. It&#8217;s configured according to industry standards and best practices, ensuring that developers have access to the best tools available.&nbsp;<\/p>\n\n\n\n<p>Furthermore, NestJS comes preconfigured with TypeORM, Mongoose, GraphQL, logging, validation, caching, web sockets, and many other features.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Why learn NestJS?<\/strong><\/h2>\n\n\n\n<p>Learning a new framework such as NestJS can cause doubts to arise. Questions like&nbsp;&#8220;How long will this framework last?&#8221;, &#8220;Are big companies using it?&#8221;, and &#8220;Can I get a job with it?&#8221;&nbsp;make it difficult to decide whether&nbsp;to invest the time needed to learn&nbsp;it.&nbsp;<\/p>\n\n\n\n<p>Here are a few reasons NestJS is worth learning:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>TypeScript and bulletproof architectural patterns make it easy for developers to build enterprise-ready applications that can be scaled and kept up to date with modern technologies.<\/li>\n\n\n\n<li>NestJS uses the standards and structures of <a href=\"https:\/\/coderpad.io\/languages\/angular\/\">Angular<\/a> and makes them better. So if you&#8217;re switching from Angular to NestJS, you can probably start using it in a day.<\/li>\n\n\n\n<li>It also works with GraphQL, WebSockets, Kafka, and RabbitMQ\u2014all popular enterprise tools\u2014right out of the box. These tools are used to build large microservice applications.<\/li>\n\n\n\n<li>NestJS also supports tools like TypeORM, Mongoose, Logging, Validation, Caching, WebSockets, and much more, without extra configuration.<\/li>\n\n\n\n<li>Many Fortune 500 companies are now using NestJS to implement their back-end applications. Therefore, it can be easy to&nbsp;find a job with companies using NestJS.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>NestJS vs. Express.js<\/strong><\/h2>\n\n\n\n<p>NestJS and Express.js are both used for building web applications and APIs. Both are built on top of the Node.js runtime, which allows you to run JavaScript on the server side.&nbsp;<\/p>\n\n\n\n<p>NestJS is inspired by Angular and offers a modular structure for organizing code into reusable components. Additionally, NestJS also includes a module system for dividing code into separate modules and built-in support for dependency injection to manage dependencies between different parts of the application.&nbsp;<\/p>\n\n\n\n<p>Express.js is a minimalist web framework for Node.js. It provides a simple set of functions for building web applications and APIs. It&#8217;s designed to be flexible and lightweight, and many other web frameworks and libraries are built on top of it.&nbsp;<\/p>\n\n\n\n<p>Which framework is best for your project depends on your specific needs and preferences. If you&#8217;re building a large, scalable application and want to take advantage of NestJS&#8217;s modular structure and dependency injection features, NestJS may be a good choice. If you want a lightweight framework that is easy to get started with and provides a simple set of tools for building web applications and APIs, Express.js may be a better fit.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Getting started with NestJS<\/strong><\/h2>\n\n\n\n<p>After reading these details about NestJS, it should be&nbsp;clear that it&#8217;s&nbsp;a powerful framework worth learning. In this section, we&#8217;ll begin our journey with NestJS, from basic concepts to implementation. So, let&#8217;s&nbsp;get started!&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>NestJS architecture<\/strong><\/h3>\n\n\n\n<p>NestJS uses a three-tier architecture to promote modularity, allowing developers to organize their code into three distinct components. This enables them to create more organized code.&nbsp;<\/p>\n\n\n\n<p>This three-tier architecture includes the following:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Controllers<\/li>\n\n\n\n<li>Services<\/li>\n\n\n\n<li>Data access layer<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s take a deeper look at this architecture.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Controllers&nbsp;<\/strong><\/h4>\n\n\n\n<p>Controllers act as a go-between for client requests and responses. Essentially, they&#8217;re in charge of handling incoming requests and returning responses to the client via HTTP. A controller receives and processes a specific request for the application via a routing mechanism. NestJS creates controllers with classes and decorators, mapping each class method to a route and receiving a specific request.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Services<\/strong><\/h4>\n\n\n\n<p>NestJS <em>providers <\/em>are used to inject services as dependencies, which are then used as the foundation of the application. Services contain business logic and provide methods for performing database CRUD (create, retrieve, update, delete) operations, such as creating, storing, and updating data. Relationships between components, controllers, and other parts of the application are established through the injection of these services.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Data access layer<\/strong><\/h4>\n\n\n\n<p>The data access layer is responsible for accessing data stored in persistent storage of some kind. It&#8217;s located at the lowest level and is responsible for dealing with the database, encapsulating data access details, and providing an access interface for the upper layer.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Setting up NestJS<\/strong><\/h3>\n\n\n\n<p>Now that we have a good understanding of NestJS, including its design architecture and how it works, it&#8217;s time to put this knowledge into practice by creating a simple NestJS project. Specifically, we&#8217;ll be building a to-do list app. Are you ready to get started? Let&#8217;s dive in!&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Prerequisites<\/strong><\/h4>\n\n\n\n<p>These are the basic requirements to move forward with the to-do app project:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A decent computer with internet connectivity<\/li>\n\n\n\n<li>Basic terminal knowledge<\/li>\n\n\n\n<li>Node.js installed<\/li>\n\n\n\n<li>Knowledge of JavaScript and Node.js<\/li>\n\n\n\n<li>Knowledge of Postman<\/li>\n<\/ul>\n\n\n\n<p>If you meet these requirements, you can proceed with this section.&nbsp; If you don\u2019t meet all the requirements, you can still follow along, but basic JavaScript knowledge is necessary.&nbsp;<\/p>\n\n\n\n<p>Follow the steps below to build our to-do list application (API) using NestJS.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>1. Install the CLI<\/strong><\/h4>\n\n\n\n<p>The first step to starting a NestJS application is installing the Nest CLI using the command below.&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\">$ npm i -g @nestjs\/cli\n$ nest <span class=\"hljs-keyword\">new<\/span> nest-todo-app<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The commands above install NestJS CLI globally and use the <code>nest<\/code> command to create a new project with the name <code>nest-todo-app<\/code>.&nbsp;<\/p>\n\n\n\n<p>Next, the command will prompt you to choose your preferred package manager. We&#8217;ll go with NPM and watch the command do its thing. You can also choose other JavaScript and TypeScript package managers like <code>yarn<\/code>.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>2. Run the demo application<\/strong><\/h4>\n\n\n\n<p>By default, creating a project using the NestJS CLI creates a demo app. We can test this app by navigating into our project root directory and running the command below:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npm run start:dev<\/code><\/span><\/pre>\n\n\n<p>To keep things tidy, you can delete all <code>app.**.ts<\/code> TypeScript files except the <code>app.module.ts<\/code> file.&nbsp;<\/p>\n\n\n\n<p>You\u2019ll get a <code>Hello World<\/code> output when you open the project in <code>localhost<\/code>.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>3. Create a controller<\/strong><\/h4>\n\n\n\n<p>As previously stated, controllers in NestJS receive incoming HTTP requests from an application front end and return an appropriate response.&nbsp;<\/p>\n\n\n\n<p>The <code>nest<\/code> command can be used to create, generate, and modify NestJS controllers, as well as to generate boilerplate code.&nbsp;<\/p>\n\n\n\n<p>We can create a controller using following command:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ nest generate controller todo<\/code><\/span><\/pre>\n\n\n<p>The two files, <code>todo.controller.spec.ts<\/code> and <code>todo.controller.ts<\/code>, will be created by the command. The first is for writing unit tests and will be ignored because it&#8217;s outside the scope of this tutorial.&nbsp;<\/p>\n\n\n\n<p>The second is a TypeScript file with the <code>@Controller<\/code> annotation. For our to-do list app, open the <code>todo.controller.ts<\/code> file and replace the code inside it with the following code:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"TypeScript\" data-shcb-language-slug=\"typescript\"><span><code class=\"hljs language-typescript shcb-wrap-lines\"><span class=\"hljs-comment\">\/\/ directory - nest-todo-app\/src\/todo\/todo.controller.ts<\/span>\n\n<span class=\"hljs-comment\">\/\/ we\u2019ll import a couple of packages that we\u2019ll use in our Todo app<\/span>\n\n<span class=\"hljs-keyword\">import<\/span> {\n  Controller,\n  Get,\n  Res,\n  HttpStatus,\n  Param,\n  NotFoundException,\n  Body,\n  Put,\n  Query,\n  Delete,\n  Post,\n\n} <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'@nestjs\/common'<\/span>;\n<span class=\"hljs-keyword\">import<\/span> { TodoService } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/todo.service'<\/span>;\n<span class=\"hljs-keyword\">import<\/span> { CreateTodoDTO } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/dto\/create-todo.dto'<\/span>;\n<span class=\"hljs-meta\">@Controller<\/span>(<span class=\"hljs-string\">'todos'<\/span>)\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">class<\/span> TodoController {\n  <span class=\"hljs-keyword\">constructor<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">private<\/span> todoService: TodoService<\/span>) {}\n\n  <span class=\"hljs-comment\">\/\/ Create a todo<\/span>\n  <span class=\"hljs-meta\">@Post<\/span>(<span class=\"hljs-string\">'\/'<\/span>)\n  <span class=\"hljs-keyword\">async<\/span> create(<span class=\"hljs-meta\">@Res<\/span>() res, <span class=\"hljs-meta\">@Body<\/span>() createTodoDTO: CreateTodoDTO) {\n    <span class=\"hljs-keyword\">const<\/span> newTodo = <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">this<\/span>.todoService.addTodo(createTodoDTO);\n    <span class=\"hljs-keyword\">return<\/span> res.status(HttpStatus.OK).json({\n      message: <span class=\"hljs-string\">'Todo has been submitted successfully!'<\/span>,\n      todo: newTodo,\n    });\n  }\n\n  <span class=\"hljs-comment\">\/\/ Fetch a particular todo using ID<\/span>\n  <span class=\"hljs-meta\">@Get<\/span>(<span class=\"hljs-string\">'\/:todoID'<\/span>)\n  <span class=\"hljs-keyword\">async<\/span> getTodo(<span class=\"hljs-meta\">@Res<\/span>() res, <span class=\"hljs-meta\">@Param<\/span>(<span class=\"hljs-string\">'todoID'<\/span>) todoID) {\n    <span class=\"hljs-keyword\">const<\/span> todo = <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">this<\/span>.todoService.getTodo(todoID);\n    <span class=\"hljs-keyword\">if<\/span> (!todo) {\n      <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> NotFoundException(<span class=\"hljs-string\">'Todo does not exist!'<\/span>);\n    }\n    <span class=\"hljs-keyword\">return<\/span> res.status(HttpStatus.OK).json(todo);\n  }\n\n  <span class=\"hljs-comment\">\/\/ Fetch all todos<\/span>\n  <span class=\"hljs-meta\">@Get<\/span>(<span class=\"hljs-string\">'\/'<\/span>)\n  <span class=\"hljs-keyword\">async<\/span> getTodos(<span class=\"hljs-meta\">@Res<\/span>() res) {\n    <span class=\"hljs-keyword\">const<\/span> todos = <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">this<\/span>.todoService.getTodos();\n    <span class=\"hljs-keyword\">return<\/span> res.status(HttpStatus.OK).json(todos);\n  }\n\n  <span class=\"hljs-comment\">\/\/ Edit a particular todo using ID<\/span>\n  <span class=\"hljs-meta\">@Put<\/span>(<span class=\"hljs-string\">'\/'<\/span>)\n  <span class=\"hljs-keyword\">async<\/span> editTodo(\n    <span class=\"hljs-meta\">@Res<\/span>() res,\n    <span class=\"hljs-meta\">@Query<\/span>(<span class=\"hljs-string\">'todoID'<\/span>) todoID,\n    <span class=\"hljs-meta\">@Body<\/span>() createTodoDTO: CreateTodoDTO,\n  ) {\n    <span class=\"hljs-keyword\">const<\/span> editedTodo = <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">this<\/span>.todoService.editTodo(todoID, createTodoDTO);\n    <span class=\"hljs-keyword\">if<\/span> (!editedTodo) {\n      <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> NotFoundException(<span class=\"hljs-string\">'Todo does not exist!'<\/span>);\n    }\n    <span class=\"hljs-keyword\">return<\/span> res.status(HttpStatus.OK).json({\n      message: <span class=\"hljs-string\">'Todo has been successfully updated'<\/span>,\n      todo: editedTodo,\n    });\n  }\n\n  <span class=\"hljs-comment\">\/\/ Delete a todo using ID<\/span>\n  <span class=\"hljs-meta\">@Delete<\/span>(<span class=\"hljs-string\">'\/delete'<\/span>)\n  <span class=\"hljs-keyword\">async<\/span> deleteTodo(<span class=\"hljs-meta\">@Res<\/span>() res, <span class=\"hljs-meta\">@Query<\/span>(<span class=\"hljs-string\">'todoID'<\/span>) todoID) {\n    <span class=\"hljs-keyword\">const<\/span> deletedTodo = <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">this<\/span>.todoService.deleteTodo(todoID);\n    <span class=\"hljs-keyword\">if<\/span> (!deletedTodo) {\n      <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> NotFoundException(<span class=\"hljs-string\">'Todo does not exist!'<\/span>);\n    }\n    <span class=\"hljs-keyword\">return<\/span> res.status(HttpStatus.OK).json({\n      message: <span class=\"hljs-string\">'Todo has been deleted!'<\/span>,\n      todo: deletedTodo,\n    });\n  }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">TypeScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">typescript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The code above performs a basic CRUD operation using the following logic:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For making a new to-do entry, we have the <code>Create<\/code> method, which uses the <code><strong>POST<\/strong><\/code> method.<\/li>\n\n\n\n<li>We have the <code>getTodo<\/code> and <code>getTodos<\/code> methods, which both use the <code><strong>GET<\/strong><\/code> method to get a single to-do, or to get all of them respectively.<\/li>\n\n\n\n<li>Next, we have the <code>editTodo<\/code> method, which uses the <code><strong>PUT<\/strong><\/code> method to change or update an existing to-do.<\/li>\n\n\n\n<li>The last method is <code>deleteTodo<\/code>, which uses the <strong><code>DELETE<\/code><\/strong> method and lets us get rid of our to-do.<\/li>\n<\/ul>\n\n\n\n<p>The most important thing is that the service class controls every operation. This keeps business logic separate from actual data manipulation.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>4. Create a service<\/strong><\/h4>\n\n\n\n<p>NestJS services handle any complex business logic data manipulations for a specific purpose and give an appropriate response to the controller.&nbsp;<\/p>\n\n\n\n<p>We can create services using the following command:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ nest generate service todo<\/code><\/span><\/pre>\n\n\n<p>Once again, open <code>todo.service.ts<\/code> and modify the code with the following:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"TypeScript\" data-shcb-language-slug=\"typescript\"><span><code class=\"hljs language-typescript shcb-wrap-lines\"><span class=\"hljs-comment\">\/\/ directory - nest-todo-app\/src\/todo\/todo.service.ts<\/span>\n\n<span class=\"hljs-keyword\">import<\/span> { Injectable } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'@nestjs\/common'<\/span>;\n<span class=\"hljs-keyword\">import<\/span> { CreateTodoDTO } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/dto\/create-todo.dto'<\/span>;\n\n<span class=\"hljs-comment\">\/\/ Creates a Todo interface to show exactly the attribute of our Todo<\/span>\n<span class=\"hljs-keyword\">interface<\/span> Todo {\n  readonly id: <span class=\"hljs-built_in\">number<\/span>;\n  readonly title: <span class=\"hljs-built_in\">string<\/span>;\n  readonly description: <span class=\"hljs-built_in\">string<\/span>;\n  readonly isDone: <span class=\"hljs-built_in\">boolean<\/span>;\n}\n\n<span class=\"hljs-meta\">@Injectable<\/span>()\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">class<\/span> TodoService {\n\n<span class=\"hljs-comment\">\/\/ Creates a Todo array with one Todo<\/span>\n  <span class=\"hljs-keyword\">private<\/span> todos: Todo&#91;] = &#91;\n    {\n      id: <span class=\"hljs-number\">1<\/span>,\n      title: <span class=\"hljs-string\">'Test todo'<\/span>,\n      description: <span class=\"hljs-string\">'This is a demo Todo application'<\/span>,\n      isDone: <span class=\"hljs-literal\">true<\/span>,\n    },\n  ];\n\n<span class=\"hljs-comment\">\/\/ Creates a new todo (Add todo to array)<\/span>\n  <span class=\"hljs-keyword\">async<\/span> addTodo(createTodoDTO: CreateTodoDTO): <span class=\"hljs-built_in\">Promise<\/span>&lt;Todo&gt; {\n    <span class=\"hljs-keyword\">this<\/span>.todos.push(createTodoDTO);\n\n<span class=\"hljs-comment\">\/\/ return last added item<\/span>\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>.todos.at(<span class=\"hljs-number\">-1<\/span>);\n  }\n\n<span class=\"hljs-comment\">\/\/ Returns a single todo with ID<\/span>\n  <span class=\"hljs-keyword\">async<\/span> getTodo(todoID: <span class=\"hljs-built_in\">number<\/span>): <span class=\"hljs-built_in\">Promise<\/span>&lt;Todo&gt; {\n    <span class=\"hljs-keyword\">const<\/span> post = <span class=\"hljs-keyword\">this<\/span>.todos.find(<span class=\"hljs-function\">(<span class=\"hljs-params\"><span class=\"hljs-params\">todo<\/span><\/span>) =&gt;<\/span> todo.id === todoID);\n    <span class=\"hljs-keyword\">return<\/span> post;\n  }\n\n<span class=\"hljs-comment\">\/\/ Returns all todos available<\/span>\n  <span class=\"hljs-keyword\">async<\/span> getTodos(): <span class=\"hljs-built_in\">Promise<\/span>&lt;Todo&#91;]&gt; {\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>.todos;\n  }\n\n<span class=\"hljs-comment\">\/\/ Deletes a todo by ID and add a new one (Update process)<\/span>\n  <span class=\"hljs-keyword\">async<\/span> editTodo(postID: <span class=\"hljs-built_in\">number<\/span>, createTodoDTO: CreateTodoDTO): <span class=\"hljs-built_in\">Promise<\/span>&lt;Todo&gt; {\n    <span class=\"hljs-keyword\">await<\/span> <span class=\"hljs-keyword\">this<\/span>.deleteTodo(postID);\n    <span class=\"hljs-keyword\">this<\/span>.todos.push(createTodoDTO);\n\n<span class=\"hljs-comment\">\/\/ return last added item<\/span>\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>.todos.at(<span class=\"hljs-number\">-1<\/span>);\n  }\n\n<span class=\"hljs-comment\">\/\/ Deletes a todo from the array<\/span>\n  <span class=\"hljs-keyword\">async<\/span> deleteTodo(todoID: <span class=\"hljs-built_in\">number<\/span>): <span class=\"hljs-built_in\">Promise<\/span>&lt;<span class=\"hljs-built_in\">any<\/span>&gt; {\n    <span class=\"hljs-keyword\">const<\/span> todoIndex = <span class=\"hljs-keyword\">this<\/span>.todos.findIndex(<span class=\"hljs-function\">(<span class=\"hljs-params\"><span class=\"hljs-params\">todo<\/span><\/span>) =&gt;<\/span> todo.id === todoID);\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>.todos.splice(todoIndex, <span class=\"hljs-number\">1<\/span>);\n  }\n}\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">TypeScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">typescript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Because we&#8217;re not working with a real database, the code above implements a basic CRUD&nbsp;operation using simple JavaScript array manipulations.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>5. Create a module<\/strong><\/h4>\n\n\n\n<p>Modules in NestJS organize your project into features and separate different features for easy structuring. A module is a class that has been annotated with the <code>@Module() decorator<\/code>. It aids in the organization of the application structure.&nbsp;<\/p>\n\n\n\n<p>The command below creates a module named <code>todo<\/code>:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\">$ nest generate <span class=\"hljs-built_in\">module<\/span> todo<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If you look into the <code>app.module.ts<\/code> (root module), you\u2019ll see how NestJS wires and sets up everything by importing your controllers\u2019 providers.&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"TypeScript\" data-shcb-language-slug=\"typescript\"><span><code class=\"hljs language-typescript shcb-wrap-lines\"><span class=\"hljs-keyword\">import<\/span> { Module } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'@nestjs\/common'<\/span>;\n\n<span class=\"hljs-keyword\">import<\/span> { AppController } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/app.controller'<\/span>;\n\n<span class=\"hljs-keyword\">import<\/span> { AppService } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/app.service'<\/span>;\n\n<span class=\"hljs-keyword\">import<\/span> { TodoController } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/todo\/todo.controller'<\/span>;\n\n<span class=\"hljs-keyword\">import<\/span> { TodoService } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/todo\/todo.service'<\/span>;\n\n<span class=\"hljs-keyword\">import<\/span> { TodoModule } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'.\/todo\/todo.module'<\/span>;\n\n<span class=\"hljs-meta\">@Module<\/span>({\n\n\u00a0\u00a0imports: &#91;TodoModule],\n\n\u00a0\u00a0controllers: &#91;AppController, TodoController],\n\n\u00a0\u00a0providers: &#91;AppService, TodoService],\n\n})\n\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">class<\/span> AppModule {}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">TypeScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">typescript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><strong>6. Create a data transfer object<\/strong><\/p>\n\n\n\n<p>Finally, we need to create a <em>data transfer object<\/em> (DTO) to help define how data is sent across the network and how data is posted from the application to the database.&nbsp;<\/p>\n\n\n\n<p>We can do this by creating a directory named \u201cDTO\u201d inside our <code>todo<\/code> folder, and then creating the file. We&#8217;ll call it <code>create-todo.dto.ts<\/code>.&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"TypeScript\" data-shcb-language-slug=\"typescript\"><span><code class=\"hljs language-typescript shcb-wrap-lines\"><span class=\"hljs-comment\">\/\/ directory - nest-todo-app\/src\/todo\/dto\/create-todo.dto.ts<\/span>\n\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">class<\/span> CreateTodoDTO {\n\n\u00a0\u00a0readonly id: <span class=\"hljs-built_in\">number<\/span>;\n\n\u00a0\u00a0readonly title: <span class=\"hljs-built_in\">string<\/span>;\n\n\u00a0\u00a0readonly description: <span class=\"hljs-built_in\">string<\/span>;\n\n\u00a0\u00a0readonly isDone: <span class=\"hljs-built_in\">boolean<\/span>;\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">TypeScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">typescript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><strong>Testing the NestJS framework<\/strong><\/p>\n\n\n\n<p>We\u2019ve finished creating our NestJS application, and now it\u2019s time to test it.&nbsp;<\/p>\n\n\n\n<p>First, check that your development server is still running, or run the following command to restart it.&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npm run start:dev<\/code><\/span><\/pre>\n\n\n<p>Now, open your Postman and test your endpoints by performing a few CRUD operations as defined in <code>todo.service.ts<\/code>. Your to-do list API should work great if there are no errors.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>You can already see the potential of NestJS to revolutionize and transform the way we develop back-end applications. Its versatility, flexibility, and modularity make it an attractive choice. Don&#8217;t miss out\u2014jump on the NestJS bandwagon!&nbsp;For more insights on how NestJS works, please visit the <a href=\"https:\/\/docs.nestjs.com\/\" target=\"_blank\" rel=\"noopener\">official NestJS documentation<\/a>.&nbsp;<\/p>\n\n\n\n<p><br><em>This post was written by Boris Bambo. He is a data &amp; machine learning engineer fascinated by technology, education, and business. Feel free to connect with him on <\/em><a href=\"https:\/\/www.linkedin.com\/in\/bamboriz\/\" target=\"_blank\" rel=\"noopener\"><em>LinkedIn<\/em><\/a><em>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Discover the power of NestJS, a server-side Node.js framework. Learn about its features and how to get started with developing applications in this blog post.<\/p>\n","protected":false},"author":1,"featured_media":31260,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[9],"tags":[],"persona":[29],"blog-programming-language":[33,41],"keyword-cluster":[],"class_list":["post-31178","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/31178","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/comments?post=31178"}],"version-history":[{"count":35,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/31178\/revisions"}],"predecessor-version":[{"id":31412,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/31178\/revisions\/31412"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media\/31260"}],"wp:attachment":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media?parent=31178"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/categories?post=31178"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/tags?post=31178"},{"taxonomy":"persona","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/persona?post=31178"},{"taxonomy":"blog-programming-language","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/blog-programming-language?post=31178"},{"taxonomy":"keyword-cluster","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/keyword-cluster?post=31178"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}