Home > OS >  NestJS - No response getById request
NestJS - No response getById request

Time:01-29

I need your help. I recently started learning the nestjs framework. I am currently trying to do CRUD operations without a database. I have 2 methods: getAllUsers and getDifferentUser. I manage to get all users, but I can't get a user by id. I don't get any error, 200 response, but my response is empty. What is my mistake? Thank you very much

userService.ts

public getAllUsers(): IUserModel[] {
   return this.users;
}

public findDifferentUser(id: number): IUserModel {
   return this.users.find(user => user.id === id);
}

user.controller.ts

@Controller('users')
export class UserController {

   constructor(private userService: UserService) {}

   @Get()
   public getAllUsers(): IUserModel[] {
      return this.userService.getAllUsers();
   }

   @Get(':id')
   public getDifferentUser(@Param('id') id: number): IUserModel {
      return this.userService.findDifferentUser(id);
   }
}

user.model.ts

export interface IUserModel {
   id: number;
   name: string;
   age: number;
   description: string;
   quality: string;
}

CodePudding user response:

Use this in your controller:

 @Get(':id')
   public getDifferentUser(@Param('id', ParseIntPipe) id: number): IUserModel {
      return this.userService.findDifferentUser(id);
   }

Because you need to convert id to a number. When you recieve it in param, it's a string.

  • Related