Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NestJS – No response getById request

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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;
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading