wonderkids
wonderkids

Reputation: 285

How to add DTO in NestJS

I'm trying to make a simple app using nestjs.

When I add CreateUserDTO in UserService I get following TS error.

src/user/user.service.ts:11:40 - error TS2345: Argument of type 'CreateUserDTO' is not assignable to parameter of type 'User'. Type 'CreateUserDTO' is missing the following properties from type 'User': $add, $set, $get, $count, and 32 more. 11 return await this.userModel.create(userData);

I checked a lot of codes about DTO, but I don't know the reason.

Here is code.

import { Column, Model, PrimaryKey, Table } from 'sequelize-typescript';

@Table
export class User extends Model<User> {
  @PrimaryKey
  @Column
  userId: string;

  @Column
  name: string;
}
export class CreateUserDTO {
  userId: string;
  name: string;
}
@Injectable()
export class UserService {
  constructor(@InjectModel(User) private userModel: typeof User) {}

  async createUser(userData: CreateUserDTO) {
    const user = await this.userModel.create<User>(userData);
  }
}

Upvotes: 6

Views: 27890

Answers (2)

Hugo Sohm
Hugo Sohm

Reputation: 3300

The problem is coming from extends Model<User> and your constructor, you don't need to extend the User methods or injecting your DTO.

DTOs are very simple and easy to use, you just need to define a class and use it as you value type importing it instead of injecting it

Here is an example to create a user using a DTO create-user.dto.ts

export class CreateUserDto {
  firstName: string;

  lastName: string;

  email: string;

  password: string;
}

And here is the controller where you can use your DTO as a type users.controller.ts

import { CreateUserDto } from './dto/create-user.dto';

export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  public async createUser(@Body() user: CreateUserDto) {
    await this.usersService.register(user);
  }
}

After it you just need to save your object using your repository users.service.ts

import { Injectable } from '@nestjs/common';
import { UsersEntity } from './users.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UsersRepository } from './users.repository';

@Injectable()
export class UsersService {
  constructor(private readonly usersRepository: UsersRepository) {}
  
  public async register(user: CreateUserDto): Promise<UsersEntity> {
    return this.usersRepository.save({ ...user });
  }
}

If you have more questions about it, please read the documentation about the Request Payloads on NestJS

Upvotes: 6

Alysson Malagutte
Alysson Malagutte

Reputation: 31

You should convert your DTO to your model typeORM dont do that, just work with the models.

See my api with nestjs, https://github.com/Malagutte/lottery-domain-api/blob/main/src/game/game.service.ts#L83

Upvotes: 0

Related Questions