Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Final Improvements and Cleanup | Section
Building Backend Applications with Nest.js

bookFinal Improvements and Cleanup

Pyyhkäise näyttääksesi valikon

At this point, your API already supports all four CRUD operations. You can create users, return user data, update existing records, and delete them.

Now it is a good time to make the code cleaner and more consistent.

One improvement is to replace inline object types with a DTO:

export class CreateUserDto {
  name: string;
  age: number;
}

You can then use it in your controller methods:

@Post()
createUser(@Body() body: CreateUserDto) {
  return this.usersService.createUser(body);
}

@Put(':id')
updateUser(
  @Param('id') id: string,
  @Body() body: CreateUserDto
) {
  return this.usersService.updateUser(Number(id), body);
}

This makes the code easier to read and avoids repeating the same structure.

Another improvement is to keep controllers focused on request handling and keep logic inside services. The controller should stay small and clear:

  • Receive the request;
  • Extract needed data;
  • Call the service;
  • Return the result.

You should also make naming consistent across the project. File names, class names, and method names should clearly describe their purpose.

At this stage, your project is still simple, but it already follows the core Nest.js ideas:

  • Controllers handle requests;
  • Services contain logic;
  • Modules organize features;
  • DTOs define data structure.

This is the main value of Nest.js. It helps you build backend applications in a way that stays organized as the project grows.

question mark

What is the main benefit of replacing inline object types with a DTO?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 23

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 1. Luku 23
some-alt