When using Angular, NestJS, and TypeORM, an issue may arise where null values are

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.

Answer №1

After some investigation, I came up with a solution to the problem by developing my own decorator inspired by a similar implementation found in this toBoolean Decorator. Now, when my colleague sends me an empty string, ``, or null, it automatically converts it to NULL in the database. This transformation takes place before passing the data to the DTO.

import { Transform } from 'class-transformer';

const ToInteger = () => {
    const toPlain = Transform(
        ({ value }) => {
            return value;
        },
        {
            toPlainOnly: true,
        },
    );
    const toClass = (target: any, key: string) => {
        return Transform(
            ({ obj }) => {
                return valueToInteger(obj[key]);
            },
            {
                toClassOnly: true,
            },
        )(target, key);
    };
    return function (target: any, key: string) {
        toPlain(target, key);
        toClass(target, key);
    };
};

const valueToInteger = (value: any) => {
    if (value === undefined) {
        return undefined;
    }
    if (isNaN(value)) {
        return null;
    }
    if (value === '') {
        return null;
    }
    if (value === 'null') {
        return null;
    }
    const x = parseInt(value);

    return x;
};

export { ToInteger };

With the decorator in place, all that was left to do was to import it into my DTO and apply it to the specific variable.

    //imports
    
    export class CreateMovieDto {
    
    @ApiProperty()
    @IsOptional()
    @ToInteger()
    dfffCopies: number;
    
    //more stuff
    
    }

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

What could be causing my TypeScript object to appear as "undefined" when I try to log it?

I created a StackBlitz demo featuring a button that, when clicked, should pass a value to the controller. In the controller, there is a function designed to assign this value to an object. However, TypeScript seems to be indicating that the object is undef ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

Refreshing the browser causes Angular route to display raw JSON data

I have been working on a MEAN stack application and I have set up a proxy configuration for development purposes. Everything seems to be in order as I am able to successfully call an API from Angular/Node. However, the issue arises when I refresh the brows ...

AOT compile error due to Angular interpolation syntax

I am facing an issue while compiling my application. The AOT compiler is showing an error related to Angular interpolation in an Angular 2 form: Property 'address' does not exist on type 'FirebaseObjectObservable'. Here's a sn ...

Typescript enables bidirectional control of Swiper

I attempted to use the two-way control slider example from Swiper documentation, but I encountered TypeScript errors that prevented it from working correctly. Is there a way to make it compatible with TypeScript? The specific errors I received were: TS23 ...

Transform Angular 4 by enforcing fatal errors on ng lint

When working with Angular CLI, I appreciate the convenience of its built-in linter. By simply running ng lint, I can effortlessly identify and rectify any errors within my codebase. In fact, it even has the capability to automatically fix some issues. I&a ...

Array containing HTML code for Ionic framework

Just starting out with Ionic/Angular and I have a question. How can I display an array containing HTML content? { "code" : "06", "descr" : "Some text:</br>Other text.<br/>Other text</br>Other text." } When I try to print it, the HTML ta ...

Monitor changes in Angular Reactive forms to retrieve the field name, as well as the previous value and the current value of the field

this.formData = this.fb.group({ field1: '', field2: '' }); this.formData.valueChanges.pipe(startWith(null), pairwise()) .subscribe(([previous, current]: [any, any]) => { console.log('PREVIOUS', previous); co ...

Angular demo showcasing a Multi-Column ListView component in NativeScript

I have a question that may seem simple to you, but I haven't been able to find a straightforward example anywhere. I came across this resource already, but it's not in Angular. As a beginner in Nativescript (I've been working with it for a ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Avoiding redundant requests with the same parameters in Angular/NGRX

Imagine having a component designed to showcase a list of actors from a movie. When this component loads, it triggers an action to retrieve the actors' data. actors.component.ts @Input() filter; // for example, only displaying male actors ngOnInit( ...

Using Angular 2+, learn how to effectively utilize and monitor the output emitter when utilizing the createComponent factory method

When I dynamically create a component in ParentComp, the code looks like this: const factory = this.resolver.resolveComponentFactory<ChildComp>(component); this.componentRef = this.container.createComponent(factory); this.componentRef.instance.dataC ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

How to handle an empty data response in Angular 2's HTTP service

My ASP.NET web API has a simple method with the following test results: $ curl localhost:5000/Api/GetAllQuestions [{"questionId":0,"value":"qqq","answers":[{"answerId":25,"value":"qwerty"}]}] However, I am encountering an issue in my Angular 2 HTTP serv ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...

Angular: The CORS issue continues despite configuring proxy.conf.json

I have tried several tutorials in an attempt to resolve my CORS issues, but unfortunately, I have been unsuccessful so far. My server setup is very basic - it responds to get 127.0.0.1:8080/hello by returning the string hello there for testing purposes. ...

Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and Ty ...

Strategies for implementing searchbar filtering in Ionic3 and Angular5 data manipulation

I'm having trouble displaying product names on my search.html page based on the search bar input. I've tried using the Ionic searchbar component but it's not working. Can anyone help me with this issue? If there's an alternative solutio ...