My coworker and I are currently collaborating on a client project. We are utilizing NestJS for the backend, Angular for the frontend, and MySQL for the database.
We have encountered an issue that we are struggling to resolve:
- Within the Entity of the NestJS Backend, we have set up a column as a number (int) like this:
//imports
@Entity()
export class Movie {
@Column({ nullable: true })
dfffCopies: number;
//more stuff
}
- In the Angular frontend, my colleague is creating a form using the angular formbuilder with the initial value of 0
this.form = this.fb.group({ dfffCopies: new FormControl(0)})
- When he submits this form with the formbuilder, it reaches the backend controller and ends up in the DTO
//imports
export class CreateMovieDto {
@ApiProperty()
@IsOptional()
dfffCopies: number;
//more stuff
}
The challenge we are facing now is that when the user leaves the input blank, my colleague wants to send out a NULL
, undefined
, empty string, or similar, instead of a 0 as a number so that the backend can store this value as empty.
However, when he does so, the backend throws an error
"incorrect integer value: 'null'"
While we know that we could potentially use something like
Number(dfffCopies)
on the backend before saving, the issue is having to do this for every single integer value within the movie-entity. We attempted this approach but came across the inconvenience of having to apply it to around 50+ more integer values to be saved in this entity.
//when saving
const movie = this.create(createMovieDto);
await this.save(movie);
//when editing
await this.update({ id }, createMovieDto);
This would require us to include an if-statement for each value from the DTO to determine its presence.
So, the question arises:
How can either myself or my colleague adjust the code to accept NULL, undefined, NaN, or other types on the integer field and save it as empty in the database? He suggested changing all fields in the backend from number/integer to String, but that solution doesn't seem ideal to us.