<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Oluwatimileyin Ojo</title>
    <description>The latest articles on DEV Community by Oluwatimileyin Ojo (@openwell).</description>
    <link>https://dev.to/openwell</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F209258%2F4dcb0c1b-9025-4835-b3bb-66c8454fc273.jpeg</url>
      <title>DEV Community: Oluwatimileyin Ojo</title>
      <link>https://dev.to/openwell</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/openwell"/>
    <language>en</language>
    <item>
      <title>Building A Todo API With NEST-JS And JS Data Structure To Persist Data - 1</title>
      <dc:creator>Oluwatimileyin Ojo</dc:creator>
      <pubDate>Sat, 17 Aug 2019 16:40:53 +0000</pubDate>
      <link>https://dev.to/openwell/building-a-todo-api-with-nest-js-and-js-data-structure-to-persist-data-1-4kke</link>
      <guid>https://dev.to/openwell/building-a-todo-api-with-nest-js-and-js-data-structure-to-persist-data-1-4kke</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fl9warl6odzll9l88tvm4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fl9warl6odzll9l88tvm4.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A colleague showed me the piece of code below and it was difficult to decipher. Thus I couldn't interpret the code, making it impossible to explain the code to him.&lt;br&gt;
As an Engineer, I had to break down the problem which came down to me asking myself “what superset of javascript is this?” and “how do I learn it?”.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F44ia5zfdhzc2h1jmwg6w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F44ia5zfdhzc2h1jmwg6w.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After a little research, I discovered it was the TYPESCRIPT...😔. A language I have been trying to do without... with its so-called typed language. However, as an Engineer with a growth mindset, I set out to learn the basics of Typescript before I dive into the documentation of the Nest-js framework.&lt;/p&gt;
&lt;h3&gt;
  
  
  BELOW ARE THE PREREQUISITES
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Knowledge of Typescript &lt;/li&gt;
&lt;li&gt;Understanding of Node or have created an API with Express js&lt;/li&gt;
&lt;li&gt;Understanding of Angular is a Plus&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  WHAT WE ARE DEVELOPING
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;A Todo List CRUD API&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  GETTING STARTED
&lt;/h3&gt;

&lt;p&gt;For you to follow along its expected you have &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node (at least v6)&lt;/li&gt;
&lt;li&gt;NPM (at least v5.2) installed on your machine&lt;/li&gt;
&lt;li&gt;A preferred code editor/IDE (I make use of Vscode. 
To confirm you have it installed, type the following in your command line/terminal.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Last login: Tue Aug  6 10:07:57 on console
➜  ~ npm -v 
6.10.2
➜  ~ node -v
v12.1.0
➜  ~ 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  STEP-1 PROJECT SETUP
&lt;/h3&gt;

&lt;p&gt;Navigate to your preferred directory for installing the project files&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;$ npm i -g @nestjs/cli&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;$ nest new project-name&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$ npm i shortid&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;➜  Documents npm i -g @nestjs/cli
/usr/local/bin/nest -&amp;gt; /usr/local/lib/node_modules/@nestjs/cli/bin/nest.js
+ @nestjs/cli@6.6.3
added 12 packages from 46 contributors, removed 194 packages and updated 33 packages in 29.183s

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In this instance, project name will be todo-app&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;➜  Documents  nest new todo-app    
⚡  We will scaffold your app in a few seconds..

CREATE /todo-app/.prettierrc (51 bytes)
CREATE /todo-app/README.md (3370 bytes)
CREATE /todo-app/nest-cli.json (84 bytes)
CREATE /todo-app/nodemon-debug.json (163 bytes)
CREATE /todo-app/nodemon.json (67 bytes)
CREATE /todo-app/package.json (1804 bytes)
CREATE /todo-app/tsconfig.build.json (97 bytes)
CREATE /todo-app/tsconfig.json (325 bytes)
CREATE /todo-app/tslint.json (426 bytes)
CREATE /todo-app/src/app.controller.spec.ts (617 bytes)
CREATE /todo-app/src/app.controller.ts (274 bytes)
CREATE /todo-app/src/app.module.ts (249 bytes)
CREATE /todo-app/src/app.service.ts (142 bytes)
CREATE /todo-app/src/main.ts (208 bytes)
CREATE /todo-app/test/app.e2e-spec.ts (561 bytes)
CREATE /todo-app/test/jest-e2e.json (183 bytes)

? Which package manager would you ❤️  to use? npm
✔ Installation in progress... ☕

🚀  Successfully created project todo-app
👉  Get started with the following commands:

$ cd todo-app
$ npm run start                         
                          Thanks for installing Nest 🙏
                 Please consider donating to our open collective
                        to help us maintain this package.

               🍷  Donate: https://opencollective.com/nest

➜  Documents npm i shortid
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we installed 2 packages. &lt;/p&gt;

&lt;p&gt;The first package has two steps. The first step is to setup Nest-js cli (Command Line Interface). It gives users a massive head start when building a Nest-js app, it saves a user from time-consuming setup and configuration.&lt;/p&gt;

&lt;p&gt;The second stage is using the installed Nest-js cli to create a new app called todo-app.&lt;/p&gt;

&lt;p&gt;Finally, the package called shortid helps generate a random id. if all packages have been successfully installed, the folder structure should be similar to the image shown below. PS😉: check the package.json file to see the shortid version installed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F9qxjpqvo0ep63p52xezz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F9qxjpqvo0ep63p52xezz.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will be creating additional folder and files to the ones shown above. Create a folder called Todo in the src folder and create these set of files. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;create-todo.dto.ts &lt;/li&gt;
&lt;li&gt;todos.controllers.ts &lt;/li&gt;
&lt;li&gt;todos.module.ts &lt;/li&gt;
&lt;li&gt;todos.service.ts&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A controller's purpose is to receive incoming requests for the application. The routing mechanism controls which controller receives which requests and helps to return a response.&lt;/p&gt;

&lt;p&gt;A module is a class annotated with a &lt;code&gt;@Module()&lt;/code&gt; decorator. The &lt;code&gt;@Module()&lt;/code&gt; decorator provides metadata that Nest-js makes use of to organize the application structure. It also houses a controller, import and service which is then bundled and parsed along.&lt;/p&gt;

&lt;p&gt;Service is similar to a helper function that can perform specific tasks. An example is reaching out to a database, so as to make the controller code lean.&lt;/p&gt;

&lt;h3&gt;
  
  
  STEP-2 SERVER SETUP
&lt;/h3&gt;

&lt;p&gt;Open the command terminal in the current project directory, then&lt;br&gt;
&lt;br&gt;
 &lt;code&gt;$ run npm run start:dev&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;This script is automatically created by Nest-js and its found in the package.json file. The script is ran because we are working locally which is the development env, production has its own script to run.&lt;/p&gt;

&lt;p&gt;The App should be running on &lt;a href="http://localhost:3000/" rel="noopener noreferrer"&gt;localhost&lt;/a&gt; if all is set up correctly. You should be greeted with a Hello World on your browser.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;➜  Documents npm run start:dev
npm ERR! path /Users/openwell/Documents/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open '/Users/openwell/Documents/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/openwell/.npm/_logs/2019-08-09T17_29_28_506Z-debug.log
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the above message pops up, you are not in the right directory.&lt;/p&gt;

&lt;h3&gt;
  
  
  STEP-3 SETTING UP CONTROLLER IN TODO FOLDER
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {Controller,Get,Body,Post,Param,Delete,Patch} from '@nestjs/common';
import { TodoService } from './todos.service';

@Controller('todos')
export class TodoController {
  constructor(private readonly todoService: TodoService) {}

  @Get()
  getAllTodos(): any {
    return this.todoService.findAll();
  }

  @Post()
  addTodo(
    @Body('title') todoTitle: string,
    @Body('description') todoDescription: string,
  ): any {
    return this.todoService.create(todoTitle, todoDescription);
  }

  @Get(':id')
  getTodoById(@Param('id') todoId: string): any {
    return this.todoService.findOne(todoId);
  }

  @Delete(':id')
  deleteTodoById(@Param('id') todoId: string): any {
    return this.todoService.deleteById(todoId);
  }

  @Patch(':id')
  updateTodoById(
    @Param('id') todoId: string,
    @Body('title') todoTitle: string,
    @Body('description') todoDescription: string,
  ): any {
    return this.todoService.UpdateById(todoId, todoTitle, todoDescription);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nest-js has done the heavy lifting for us, by providing &lt;code&gt;@nestjs/common&lt;/code&gt; that has many decorators within itself. All we need is to import &lt;code&gt;@Get&lt;/code&gt; as done above to create a get route, which applies to all other Http methods. If you observe the &lt;code&gt;@controller&lt;/code&gt; decorator has 'todos' in it. which translate to &lt;code&gt;localhost:3000/todos&lt;/code&gt; like we have in a normal Express-js app. All Http methods in the controller will be inheriting from it. Meaning the post or delete will be translated to&lt;code&gt;POST http://localhost:3000/todos&lt;/code&gt; &lt;code&gt;DELETE http://localhost:3000/todos&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In the TodoController class, we have Constructor that expects a todoService of type TodoService which we imported.&lt;/p&gt;

&lt;p&gt;We made use of some other decorators which gives us access &lt;code&gt;req.body/@Body('')&lt;/code&gt; or &lt;code&gt;req.params/@Param('')&lt;/code&gt;. For the &lt;code&gt;@Param&lt;/code&gt; to work we need to add it to the route by using ':id' inside the desired method.&lt;/p&gt;

&lt;p&gt;The rest of the function just returns the output from calling the respective services.&lt;/p&gt;

&lt;p&gt;By Default a post route return 201 status code while others return 200. &lt;br&gt;
To change the default code all you need to do is make use of the &lt;code&gt;@HttpCode(200)&lt;/code&gt; decorator.&lt;br&gt;
It also detects the kind of data send out and based on that set the header to suit it. To set your preferred header, make use of &lt;code&gt;@Header('Content-Type', 'application/json')&lt;/code&gt; decorator for example.&lt;/p&gt;
&lt;h3&gt;
  
  
  STEP-4 SETTING UP SERVICE IN TODO FOLDER
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable, NotFoundException } from '@nestjs/common';
import { Todo } from './create-todo.dto';
import { generate } from 'shortid';
@Injectable()
export class TodoService {
  private todosDb: Todo[] = [];
  findAll(): any {
    return [...this.todosDb];
  }
  create(todoTitle: string, todoDescription: string): any {
    const id = generate();
    const newTodo = new Todo(id, todoTitle, todoDescription);
    this.todosDb = this.todosDb.concat(newTodo);
    return newTodo;
  }
  findOne(id: string): any {
    const todoIndex = this.todosDb.find(elem =&amp;gt; elem.id === id);
    if (todoIndex === undefined) {
      throw new NotFoundException();
    }
    return todoIndex;
  }
  deleteById(id: string): any {
    const index = this.todosDb.findIndex(elem =&amp;gt; elem.id === id);
    if (index === -1) {
      throw new NotFoundException();
    }
    this.todosDb.splice(index);
    return { message: 'Todo Deleted' };
  }
  UpdateById(id: string, todoTitle: string, todoDescription: string): any {
    const index = this.todosDb.findIndex(elem =&amp;gt; elem.id === id);
    if (index === -1) {
      throw new NotFoundException();
    }
    const singleTodo = this.todosDb[index];
    if (todoTitle) {
      singleTodo.todoTitle = todoTitle;
    } else if (todoDescription) {
      singleTodo.todoDescription = todoDescription;
    }
    this.todosDb[index] = singleTodo
    return { message: 'Todo Updated' };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;We imported the Todo which is DTO (Data Transfer Object) schema for the todosDb Array and generate for the shortid package.&lt;/p&gt;

&lt;p&gt;We created a TodoService class which was exported with several methods handling the data passed to it. Something to point out is the &lt;code&gt;NotFoundException()&lt;/code&gt;, its a method which helps in error handling, it throws 404 automatically and a custom message can be passed into it.&lt;br&gt;
The rest of the methods are self-explanatory. &lt;/p&gt;
&lt;h3&gt;
  
  
  STEP-5 SETTING UP CREATE-TODO-DTO FILE IN TODO FOLDER
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class Todo {
  constructor(
    public id: string,
    public todoTitle: string,
    public todoDescription: string,
  ) {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The file export a class Todo with the expected &lt;code&gt;@body&lt;/code&gt; input types&lt;/p&gt;
&lt;h3&gt;
  
  
  STEP-6 SETTING UP MODULE IN TODO FOLDER
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { TodoController } from './todos.controllers';
import { TodoService } from './todos.service';

@Module({
  controllers: [TodoController],
  providers: [TodoService],
})
export class TodosModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The module exports the compliation of all codes to a format understood by Nest-js. &lt;/p&gt;

&lt;p&gt;Before we wrap up, it is necessary to import the module in the Todo folder into the main module.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TodosModule } from './Todo/todos.module';

@Module({
  imports: [TodosModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  STEP-7 TESTING OF OUR TODO API WITH REST CLIENT(VSCODE EXTENSION) OR POSTMAN.
&lt;/h3&gt;

&lt;p&gt;I will be making use of Rest Client in this tutorial.&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;http.http&lt;/code&gt; file in the main directory and add it to &lt;code&gt;.gitignore&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;### 
GET http://localhost:3000 HTTP/1.1

### 
GET http://localhost:3000/todos HTTP/1.1

### 
POST http://localhost:3000/todos HTTP/1.1
  content-type: application/json 

  {
    "title": "Wednesday Blog",
    "description": "I lost my dinner to rodent"
  }

### 
GET http://localhost:3000/todos/TGj-TyeBk HTTP/1.1

### 
DELETE  http://localhost:3000/todos/Tg3zyAxj_ HTTP/1.1

### 
PATCH   http://localhost:3000/todos/46szeJhw HTTP/1.1
 content-type: application/json 

  {
    "title": "Monday Blog"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are using Vscode, you will see a send request directly above Get request or any of the Http method created kindly click for the desired route. For those that will be making use of Post-Man, this is self-explanatory, select the right method postman and insert the respective URL. For post and patch send the body in raw and JSON(application/json) or any other format suitable. &lt;/p&gt;

&lt;p&gt;Kindly restart the server with &lt;code&gt;npm run start:dev&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F3xgelviyjeallqg08p5p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F3xgelviyjeallqg08p5p.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  CONCLUSION
&lt;/h3&gt;

&lt;p&gt;In this tutorial, we've learned how to setup Nest-js Todo server.&lt;/p&gt;

&lt;p&gt;Many thanks to Azeez Olasoji for helping out in editing this. Thank you. Thank you.&lt;/p&gt;

&lt;p&gt;You can find the complete source code for this project here on &lt;a href="https://github.com/openwell/nest-todo-project/tree/backend-api-with-js-data" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. For more information about &lt;a href="https://docs.nestjs.com" rel="noopener noreferrer"&gt;Nest-js&lt;/a&gt;, you can visit the official documentation.&lt;/p&gt;

&lt;p&gt;Kindly drop your questions and comments. And if you have any observation or notice an error kindly leave a comment.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>node</category>
      <category>javascript</category>
      <category>nestjs</category>
    </item>
  </channel>
</rss>
