How to create services and work with data in NestJs

Learn about creating services and manipulating data in NestJS.

overview

In NestJS, services encapsulate business logic and act as a bridge between controllers and the database. This article details how to create services and manipulate data with NestJS.

nest.js v10.1.7
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

How to create a service

Nest.js has a very useful command line tool called Nest CLI. By using this, you can automatically register service files, service test files, and providers.

The following commands add a service file and a service test file to the users directory.

nest g s users

This will add a service file and a service test file to your users directory.

src/
└── users/
    ├── users.service.spec.ts
    └── users.service.ts

Check your app.module.ts. You can see that provider registration was also done automatically.

/src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users/users.controller';
import { UsersService } from './users/users.service'; // Automatic registration during CLI execution

@Module({
imports: [],
controllers: [AppController, UsersController],
providers: [AppService, UsersService], // automatic registration when running CLI
})
export class AppModule {}

How to create a service function

Next, implement the data manipulation logic in the UsersService. Here we create an array to hold the user data and implement methods to get, add and remove users.

/src/users/users.service.ts

import { Injectable } from '@nestjs/common';

interface User {
  id: number;
  name: string;
}

@Injectable()
export class UsersService {
  private users: User[] = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Doe' },
  ];
  getUsers(): User[] {
    return this. users;
  }
  addUser(name: string): void {
    const newUser: User = {
      id: this.users.length + 1,
      name,
    };
    this.users.push(newUser);
  }
  putUser(id: number, name: string): void {
    const index = this.users.findIndex((user) => user.id === Number(id));
    if (index === -1) {
      console.error(`User with id ${id} not found.`);
      return;
    }
    console.log(`Updating user with id ${id} to have name ${name}`);
    this.users[index] = { ...this.users[index], name };
  }
  deleteUser(id: number): void {
    this.users = this.users.filter((user) => user.id !== Number(id));
  }
}

The UsersService now has logic to manipulate the user’s data.

How to fix the controller

Finally, modify the UsersController to call the UsersService methods.

/src/users/users.controller.ts

import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
} from '@nestjs/common';
import { UsersService } from './users.service';

interface User {
  id: number;
  name: string;
}

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  getUsers(): User[] {
    return this.usersService.getUsers();
  }
  @Post()
  addUser(@Body() name: string): void {
    this.usersService.addUser(name);
  }

  @Put(':id')
  putUser(@Param('id') id: number, @Body('name') name: string): void {
    this.usersService.putUser(id, name);
  }

  @Delete(':id')
  deleteUser(@Param('id') id: number): void {
    this.usersService.deleteUser(id);
  }
}


Now the UsersController calls the UsersService’s methods on request.

test

# get user list
curl http://localhost:3000/users
# add user
curl -X POST -H "Content-Type: application/json" -d '{"name":"Mike"}' http://localhost:3000/users
# update user
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Bob"}' http://localhost:3000/users/1
# remove user
curl -X DELETE http://localhost:3000/users/4

summary

In this article, you learned how to create services and work with data in NestJS. Services encapsulate business logic and act as a bridge between controllers and databases. NestJS services organize your application logic and encourage code reuse.