2

Nest JS REST API Tutorial

 2 years ago
source link: https://dev.to/cryptus_neoxys/nest-js-rest-api-tutorial-2gdi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Getting started

The first things you'll need are:

  • Node installed
  • Your favourite Code Editor/IDE

Once you have those setup, let us get started with nest.
Install the nest js CLI:

npm i -g @nestjs/cli
Enter fullscreen modeExit fullscreen mode

Now you we can use this to bootstrap our nest project, using the following command:

nest new <project-name>
Enter fullscreen modeExit fullscreen mode

The command should start scaffolding your app, select your preferred package manager and let the CLI setup and install dependencies.

Then navigate into your project directory and start the development server.

cd nest-beginner
npm run start:dev
Enter fullscreen modeExit fullscreen mode

Open a browser and go to http://localhost:3000/, and you should see a familiar message

Developing our API

To keep this tutorial simple, we are going to use nest CLI's resource generator recipe for generating our resources. Go ahead and run the following command to generate the User resource for our API.

For this tutorial, we will be developing a REST API, so go ahead and select that option and also let nest generate the CURD entry points to give us some boilerplate code to get started with.

After running the command successfully, you should have the following files in src/ directory:

We start by defining the user entity and the DTOs:

// user.entity.ts
export class User {
  id: number;
  username: string;
  email: string;
  password: string;
}
Enter fullscreen modeExit fullscreen mode
// create-user.dto.ts
export class CreateUserDto {
  username: string;
  email: string;
  password: string;
}
Enter fullscreen modeExit fullscreen mode

Since we are using nest generated resource's boilerplate, it makes it simpler as we need to modify just the business logic in the service layer which the controller is already utilising in the API layer. (for this tutorial, we will be storing everything in-memory, do note that in a real-world application we would use a database like MySQL or MongoDB)

// user.service.ts
@Injectable()
export class UsersService {
  private users: User[] = [];
  private idSeq = 0;

  create(createUserDto: CreateUserDto) {
  }

  findAll(): User[] {
    return this.users;
  }

  findOne(id: number): User {
  }

  update(id: number, updateUserDto: UpdateUserDto): User {
  }

  remove(id: number): User {
  }
}
Enter fullscreen modeExit fullscreen mode

Let us begin with the Get methods first.

// user.service.ts
  findAll(): User[] {
    return this.users;
  }

  findOne(id: number): User {
    return this.users.find((user) => user.id === id);
  }
Enter fullscreen modeExit fullscreen mode

To create the user, we push the create user DTO and use the idSeq variable to generate a sequential id for it:

// user.service.ts
  create(createUserDto: CreateUserDto) {
    this.users.push({
      ...createUserDto,
      id: this.idSeq++,
    });
    return this.users.at(-1);
  }
Enter fullscreen modeExit fullscreen mode

To update the user, we first find the index by the id, if the user exists then we overwrite the values with the update user DTO.

// user.service.ts
  update(id: number, updateUserDto: UpdateUserDto): User {
    const i = this.users.findIndex((user) => user.id == id);
    if (i === -1) return null;
    this.users[i] = {
      ...this.users[i],
      ...updateUserDto,
    };
    return this.users[i];
  }
Enter fullscreen modeExit fullscreen mode

For deleting, we similarly find if the user exists by id, and use the Array slice method to delete it from memory:

// user.service.ts
  remove(id: number): User {
    const i = this.users.findIndex((user) => user.id == id);
    if (i === -1) return null;
    const user = this.users[i];
    this.users.splice(i, 1);
    return user;
  }
Enter fullscreen modeExit fullscreen mode

Now all of our CRUD functionalities are in place and we can test our API, yes you heard that right, we don't need to wire up the controller, set up the module and wire it up with our app, the nest CLI did all of that for us when we generated users resource. So fire up Postman or Insomnia or whatever is your favourite HTTP client.

Feel free to reach out to me on Twitter @cryptus_neoxys and connect with me on LinkedIn.


Refs & Resources

Nest JS Docs


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK