Utilizing class-transformer to reveal an array of objects

I am facing an issue with exposing an array of objects in my code. Even though I have exposed the Followers array in the UserDto, it is not getting displayed as expected.

This is the output I am currently seeing,

{
    "id": "5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481",
    "userName": "jdbfjl",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="29434d4f4b4843694e44484045074a4644">[email protected]</a>",
    "bio": "Duuude",
    "avatar": "sjldflaeulajsnlnaefb",
    "followerCount": 0,
    "followeeCount": 0,
    "verified": false,
    "followers": [
      {},
      {},
      {}
    ],
    "followees": [
      {}
    ]
  }

The expected output should look like this,

{
    "id": "5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481",
    "createdAt": "2021-08-11T11:07:11.688Z",
    "updatedAt": "2021-08-11T11:07:11.688Z",
    "userName": "ashdviah",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204853445648415360474d41494c0e434f4d">[email protected]</a>",
    "bio": "I am Handsome",
    "avatar": "sjldflaeulajsnlnaefb",
    "followerCount": 0,
    "followeeCount": 0,
    "verified": false,
    "followers": [
      {
        "id": "db1d30c6-5607-4d87-8838-69f906c3c44e",
        "createdAt": "2021-08-11T11:09:33.018Z",
        "updatedAt": "2021-08-11T11:09:33.018Z"
      },
      {
        "id": "31492cd6-7c56-48f6-aff3-792a980b5100",
        "createdAt": "2021-08-11T11:11:01.288Z",
        "updatedAt": "2021-08-11T11:11:01.288Z"
      },
    ],
    "followees": [
      {
        "id": "ab095d0d-b9fa-41a4-be35-13fe9dd6f7a1",
        "createdAt": "2021-08-11T12:55:18.139Z",
        "updatedAt": "2021-08-11T12:55:18.139Z"
      }
    ]
  }

However, when I do not specify an interceptor for that route, I get this output which exposes password information unintentionally.

My current approach involves using the following code in my mock class which is not working as intended. What could be the issue here?

class mock {
  @Expose() id : string;
  @Expose() createdAt : Date;
  @Expose() updatedAt : Date;
}

export class UserDto {
  @Expose()
  id : string;
  
  @Expose()
  userName : string;
  
  @Expose()
  email : string;

  @Expose()
  bio : string;

  @Expose()
  avatar : string;

  @Expose()
  followerCount : number;

  @Expose()
  followeeCount : number;

  @Expose()
  verified : boolean;

  @Expose()
  followers : Array<mock>;

  @Expose()
  followees : Array<mock>;
}

The transformation is handled by an interceptor used at the controller level.

Usage : @Serialize(UserDto) decorator

export function Serialize(dto: ClassConstructor) {
  return UseInterceptors(new Serializeinterceptor(dto));
}

export class Serializeinterceptor implements NestInterceptor {
  constructor(private dto: any) {}

  intercept(context: ExecutionContext, handler: CallHandler) {
    return handler.handle().pipe(
      map((data: any) => {
        return plainToClass(this.dto, data, {
          excludeExtraneousValues: true,
        });
      }),
    );
  }
}

Answer №1

To handle non-primitive types (such as classes), it is important to include the @Type(() => ClassType) decorator in order for class-transformer to properly process them. In this scenario, the decorator needed would be @Type(() => mock).

This step is crucial as stated in their documentation, especially when dealing with arrays.

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

Create a function that takes advantage of a Promise to resolve its actions

In the asynchronous function provided below: export default async function getUserNames(id: string[]): Promise<string[]> { let userNames: string[] = []; // Additional actions such as service calls are performed here... return userNames; ...

Cannot access a Typescript method variable within an inline function

I've encountered an issue with my code involving loading values into the array usageCategory within an inline function. Despite successfully adding values to the array inside the function, I am unable to print them outside it. getAllUsageCategoryElem ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

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, ...

Is there a solution for the error message "Operator '+' cannot be used with types 'string | number' and 'string' | number'"?

Here's the scenario: I'm encountering an issue where I am invoking a function within another function. This inner function has the capability to return either a string or a number, and my goal is to combine that with another value. However, I kee ...

The error message "Unable to access property MyToast.java as it is not

I've been diligently following this tutorial on how to write Java code in NativeScript and use it directly in TypeScript. But, unfortunately, I encountered an error message stating: Cannot read property 'MyToast' of undefined app.component ...

Encountering TypeScript error in the beforeRouteUpdate hook with Vue and vue-property-decorator

I am developing an application using Vue 2 with TypeScript and vue-property-decorator. Within my component, I am utilizing the beforeRouteEnter/beforeRouteUpdate hooks. One of the methods in my component is findProjects, which I want to call within the bef ...

Executing multiple queries in a node.js transaction with Sequelize using an array

I am looking to include the updates on the clothingModel inside a transaction, with the condition that if it successfully commits, then update the reservationModel. This is the snippet of code I am attempting to refactor using sequelize.transaction tr ...

Utilizing Angular 2 for Element Selection and Event Handling

function onLoaded() { var firstColumnBody = document.querySelector(".fix-column > .tbody"), restColumnsBody = document.querySelector(".rest-columns > .tbody"), restColumnsHead = document.querySelector(".rest-columns > .thead"); res ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...

Sveltekit: Troubleshooting problem of refreshing when utilizing store and localStorage

I am currently working on persisting data using localStorage and have successfully achieved persistence. However, I notice that when I refresh the page, it initially displays a value of 0 before fetching the localStorage value. Is there a way for me to ins ...

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

Am I utilizing Angular's signals correctly? And what is the purpose of still requiring ChangeDetectorRef.detectChanges()?

I have been experimenting with signals and I am questioning whether the current use case would be more beneficial without using Signals and instead just having a "normal" class member swiper?: Swiper: @Component({ selector: '[app-test]', stan ...

The speed of the OpenLayers web application is significantly hindered when accessed from a mobile device using Android

Although it may seem like a common question that should be closed, I have reached a roadblock and cannot find a solution. I hope to provide enough details to make this question suitable for SO. I am currently working on an OpenLayers web application that ...

Tips for sorting through the properties of the Record<K, T>:

Let's say we have the following data stored in a record: export const MenuData: Record<Header, HeaderInfo> = { val1: { message: 'xyz', buttonText: 'txt', buttonUrl: '/url-abc', }, val2: { messa ...

Click the link to copy it and then paste the hyperlink

I am facing an issue with copying and pasting file names as hyperlinks. I have checkboxes next to multiple files and a share button. When I check the boxes and click on the share button, I want to copy the download URLs for those files. Although I can succ ...

The module imported by Webpack appears to be nothing more than a blank

I am attempting to integrate the "virtual-select-plugin" library into my Typescript project using webpack. Unfortunately, this library does not have any type definitions. Upon installation via npm, I encountered the following error in the browser: TypeErro ...

Access an array to filter by specific key-value pairs

How can I efficiently filter an array using key and value pairs from within nested arrays? I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean value ...

Injecting styles haphazardly using styled-components

When populating a grid with various controls such as an up-down counter and a text box, I currently inject styles into the cls member. For example, classes like wide-input and narrow-input: render(): ReactNode { const input: CellItem[] = [ { i ...