NestJS connecting Sequelize models and DTOs

13 views Asked by At

I have a Survey model:

@Table
export class Survey extends Model {
  @PrimaryKey
  @Default(DataType.UUIDV4)
  @Column(DataType.UUID)
  id: string;

  @Column({ type: DataType.STRING, allowNull: false })
  name: string;

  @Column({ type: DataType.STRING, defaultValue: '', allowNull: false })
  description: string;

  @Column({ type: DataType.BOOLEAN, defaultValue: false, allowNull: false })
  isActive: boolean;
}

Only the name field is required when a survey is inserted. The rest has default values.

Here is my CreateSurveyDto:

import { IsString } from 'class-validator';

export class CreateSurveyDto {
  @IsString()
  name: string;

  @IsString()
  description?: string;
}

The problem is, in my service, I am getting a TypeScript error when passing the dto as an argument to the create function:

  public async createSurvey(createSurveyDto: CreateSurveyDto): Promise<Survey> {
    return await this.surveyModel.create(createSurveyDto);
  }

This results in an error:

Argument of type 'CreateSurveyDto' is not assignable to parameter of type 'Optional<any, string>'.
  Type 'CreateSurveyDto' is not assignable to type 'Omit<any, string>'.
    Index signature for type 'number' is missing in type 'CreateSurveyDto'

What am I doing wrong here? In the dto, only the name is required when creating a survey but the user can optionally pass a description if they want. Should I include ALL the fields in the model and make some optional?

0

There are 0 answers