Integrating Sequelize models with DTOs in NestJS

I've defined 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;
}

When inserting a survey, only the name field is mandatory, while the rest have default values.

Below is my CreateSurveyDto:

import { IsString } from 'class-validator';

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

  @IsString()
  description?: string;
}

The issue arises in my service 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 triggers an error message:

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 could be causing this issue? Should I include all fields in the model and make some optional, even though only the name field is required in the dto for creating a survey?

Answer №1

My approach to resolving this issue involves the following steps:

return await this.surveyModel.create({ ...createSurveyDto, isActive: true });

By utilizing the spread operator to merge the properties of the DTO into a new object, we are effectively constructing a new object literal that TypeScript recognizes as a suitable argument for the create method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to disable click event binding in Angular2 after it has been clicked once

Within my application, there is a button that has a click event attached to it: <button class="btn btn-default" (click)="doSomething()"> I am wondering if there is a way to remove the (click) event from the button within the doSomething method so t ...

Enhancing function behavior with higher order functions for TypeScript method overriding

After examining this piece of code: /** * Transform a single-argument function into a function that can handle and return values wrapped in the type constructor `F` */ export function lift<F extends URIS3>( F: Functor3<F> ): <A, B>(f ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

What is the best way to convert JSON into a complex object in Typescript and Angular?

In my Typescript class for an Angular version 5 project, I have a JavaScript function that generates a style object. Here is the function: private createCircle(parameters: any): any { return new Circle({ radius: parameters.radius, ...

Angular error message: Trying to access the property 'name' of an undefined object leads to a TypeError

I'm having trouble phrasing this question differently, but I am seeking assistance in comprehending how to address this issue. The error message I am encountering is as follows: TypeError: _co.create is not a function TypeError: Cannot read property ...

Web application experiences freezing issues when utilizing specific components in certain situations

Currently, I am in the process of developing a web application using Angular. In this project, there is a parent component and multiple child components that receive data from an rxjs Subject. One of the child components is being used in another section o ...

Getting exported members through Typescript Compiler API can be achieved by following these steps:

I am currently working on a project hosted at https://github.com/GooGee/Code-Builder This particular file is being loaded by the Typescript Compiler API: import * as fs from 'fs' Below is a snippet of my code: function getExportList(node: t ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function. However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function" Below ...

Is there a way to prompt TypeScript to generate a runtime error when a non-null assertion fails?

Is there a way to convert non-null assertions in TypeScript into JavaScript that throws an error? By default, the non-null assertion is ignored (playground): // Typescript: function foo(o: {[k: string]: string}) { return "x is " + o.x! } con ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

Leveraging Generic Types in React with TypeScript for Dynamically Assigning HTML Props based on Element Tags

I am frequently in need of a component that is essentially just a styled HTML tag. A good example is when I want to create beautifully styled div elements: // Definitions const styledDiv = (className: string) => { const StyledDiv = React.FC<HTMLA ...

The error message "Property 'originalUrl' is not found in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'" appeared

In my TypeScript project, I am utilizing a gulpfile to initiate the process. Within the gulpfile, I am using express where I encounter an issue while trying to access req.originalUrl, with req being the request object. An error is thrown stating Property ...

The Nest.js Inject decorator is not compatible with property-based injection

I am facing an issue with injecting a dependency into an exception filter. Here is the dependency in question: @Injectable() export class CustomService { constructor() {} async performAction() { console.log('Custom service action executed ...

Tips for resolving the error message "What to do when reportWebVitals can't be located

Having some trouble with importing reportWebVitals for my React 18 application that is based on WebPack 5. Below is a snippet of my index.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './style ...

Tips for aligning the arrow of a dropdown menu option

When examining the code provided, I have noticed the clr-select-container with specific attributes as depicted. In the screenshot attached, it displays the clr-select-container. The issue that I am encountering is that the inverted arrow is positioned a f ...

Issue with Typescript express application utilizing express-openid-connect wherein cookies are not being retained, resulting in an infinite loop of redirects

For a while now, I've been facing a block with no resolution in sight for this particular issue. Hopefully, someone out there can lend a hand. Background I have a TS express application running on Firebase functions. Additionally, I utilize a custom ...

Client Components can only receive plain objects and select built-in items from Server Components

My NextJs application has an "admin" page using Vercel Postgres. The issue I am facing is that when I fill in the inputs and click on the "Create user" button, a new user should be created. However, upon clicking the button, I encounter this error: Error ...

typescript encountered an issue when trying to import the p-retry library

After searching through numerous posts, I have yet to find a solution for the specific scenario involving p-retry. The library provides its own type definitions and updated sample documentation for the latest version. However, when I try to import it using ...

What are the best strategies for addressing security risks in Axios versions 1.0.0 to 1.5.1 and those greater than or equal to 1.3.2?

After running npm install, I encountered a moderate vulnerability. How can I resolve this issue? 1 moderate severity vulnerability To fix all problems, run: npm audit fix Run `npm audit` for more information. # npm audit report axios 1.0.0 - 1.5.1 S ...