NestJS's "Exclude" decorator in class-transformer does not exclude the property as expected

I attempted to exclude a specific property within an entity in NestJS, but it appears that the exclusion is not working as expected. When I make a request, the property is still being included.

Code:

// src/tasks/task.entity.ts
import { Exclude } from 'class-transformer';
import { User } from 'src/auth/user.entity';
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { TaskStatus } from './task-status.enum';

@Entity()
export class Task {
  @PrimaryGeneratedColumn('uuid') id?: string;

  @Column() title: string;

  @Column() description: string;

  @Column() status: TaskStatus;

  @Exclude({ toPlainOnly: true }) // -> not working
  @ManyToOne((_) => User, (user) => user.tasks, { eager: false })
  user: User;
}

src/transform.interceptor.ts

import {
  NestInterceptor,
  Injectable,
  CallHandler,
} from '@nestjs/common';
import { classToPlain } from 'class-transformer';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(_: any, next: CallHandler<any>) {
    return next.handle().pipe(map((data) => classToPlain(data)));
  }
}

src/task.service.ts (relevant methods)

@Injectable()
export class TasksService {
  constructor(@InjectRepository(TaskRepo) private tasksRepo: TaskRepo) {}

// ...
  createTask(createTaskDto: CreateTaskDto, user: User) {
    return this.tasksRepo.createTask(createTaskDto, user);
  }

// ...
}

src/tasks.controller.ts

@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
  constructor(private tasksService: TasksService) {}

  @Post()
  createTask(@Body() createTaskDto: CreateTaskDto, @GetUser() user: User) {
    return this.tasksService.createTask(createTaskDto, user);
  }
// ...
}

// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './transform.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalInterceptors(new TransformInterceptor());
  await app.listen(3030).catch(console.error);
}
bootstrap().catch(console.error);

After incorporating @omidh's suggestion into main.ts file, unfortunately, the issue remains unresolved.

import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './transform.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalInterceptors(new TransformInterceptor());
  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
  await app.listen(3030).catch(console.error);
}
bootstrap().catch(console.error);

What could be causing this issue?

Answer №1

To enhance serialization, consider implementing a class serializer interceptor in your main file:

    app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));

Answer №2

When your main objective is simply to get a basic object representation of an entity, you have the option to eliminate all transformer-related code and opt for declaring a method within the entity itself:

toJSON() {
   return classToPlain(this)
}

By doing this, your entity classes will be seamlessly transformed into plain objects.

Answer №3

Double check that the relationship between your Task and User entities is established correctly.

In my experience with Sequelize, I encountered a similar problem where I overlooked specifying the primary key as user_id, resulting in an additional id attribute being included in all query results. I'm not sure how this issue is resolved in TypeORM though.

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

Using TypeScript to define generic types for classes, method parameters, and method return types

I am facing an issue with this particular function function getCollection<T>(collectionType: T): Collection<T> { return new Collection<T>() } In the Collection class, I have the following code snippet export class Collection<T> { ...

Obtaining a return value from a function in Angular

After just starting to work with Angular, I am attempting to extract a value from a button displayed in the HTML using a function. `<button class="btn" id="btn-gold" (click)="value(9)" name="mybutton" value="9">` 9 I have also inclu ...

Can you explain the purpose and functionality of the following code in Typescript: `export type Replace<T, R> = Omit<T, keyof R> & R;`

Despite my efforts, I am still struggling to grasp the concept of the Replace type. I have thoroughly reviewed the typescript documentation and gained some insight into what is happening in that line, but it remains elusive to me. ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Facing an issue with the ng2-carousel component where the left and right arrow icons are

Currently employing ng2-carouselamos Visit the ng2-carouselamos npm page here After duplicating the provided HTML template, I have encountered issues with clickable events not functioning properly. The absence of a TypeScript file in the documentation ma ...

Having trouble resolving the '@angular/material/typings/' error?

I am currently working on tests for an angular project and encountering errors in these two test files: https://pastebin.com/bttxWtQT https://pastebin.com/7VkirsF3 Whenever I run npm test, I receive the following error message https://pastebin.com/ncTg4 ...

Having trouble sending a x-www-form-urlencoded POST request in Angular?

Despite having a functional POST and GET service with no CORS issues, I am struggling to replicate the call made in Postman (where it works). The only thing I can think of is that I may have incorrectly set the format as x-www-form-urlencoded. When searchi ...

Unable to perform real-time transpilation of ES module, a loader plugin must be set up through the SystemJS.config configuration

I encountered an issue while trying to develop a plugable application. Everything was functioning correctly until I introduced "ngx-bootstrap" and "FullCalendarModule"/primeng in the plugin app. Importing any of these modules resulted in the following erro ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...

Tips for utilizing RouterLink within an HTML template

Angular 2.3.0 I created a module in Angular 2 as shown below: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; impo ...

Angular Error: Attempting to access property 'then' of undefined object causes TypeError

I am struggling with implementing JHipster Auth-guard. I am facing an issue where canActivate is not triggered for a user without permission for a specific route. I have carefully examined my code, but the console shows that .then() is undefined at the sp ...

Async pipe in Angular does not work with my custom observables

I've been trying to implement the async pipe in my template, but I'm encountering difficulties retrieving data from my API. To store and retrieve the data, I have utilized a behavior subject to create an observable. However, when I attempt to dis ...

The functionality of Layout.tsx is inconsistent across various pages

I'm having trouble with the console.log() code to display the page path only showing up in the "pages.tsx" file (src/app/pages.tsx) and not appearing in the console for other files located in (src/page/Login). Here is the code from layout.tsx: ' ...

What exactly are the implications of having dual type declarations in TypeScript?

I recently came across the Angular tutorial here In the code snippet below, there are double type declarations that I am having trouble understanding. handleError<T>(operation = 'operation', result?: T) { return (error: any): Observabl ...

The proper method for referencing TypeScript compiled files with the outDir option

I am currently working on a simple app that consists of two .ts files. These files are compiled using the following tsconfig.js file: { "compilerOptions": { "target": "ES5", "module": "commonjs", "sourceMap": true, "emitDecoratorMetadata ...

Dramatist - shutting down an angular pop-up dialog

I am currently utilizing the Playwright tool to carry out testing on an angular application. One particular scenario involves a modal that is displayed by default when a page is loaded. Despite my best efforts, I have been unable to successfully close this ...

TS7030: In Angular13, ensure that all code paths within the guard and canActivate methods return a value

Having trouble using guards for an unlogged user and constantly facing errors. Error: TS7030 - Not all code paths return a value. Below is my auth.guard.ts file: import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from &a ...

Using the className prop in React with TypeScript

How can the className prop be properly typed and utilized in a custom component? In the past, it was possible to do the following: class MyComponent extends React.Component<MyProps, {}> { ... } and then include the component using: <MyCompone ...

What causes the discrepancy in results between these two NodeJS/Typescript imports?

Within my NodeJS project, I have integrated typescript version 3.2 alongside express version 4.16 and @types/express version 4.16. My development is focused on using Typescript with the intention of transpiling it later on. The guidelines for @types/expre ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...