Having a custom getter in a Response DTO does not function properly

After attempting to create a custom getter as shown below:

import { Expose } from 'class-transformer';

export class MyDTOResponse {
  @Expose()
  id: string;

  @Expose()
  name: string;

  @Expose()
  get thisIsATest(): string {
    return 'yolo';
  }
}

This is the process I follow for transformation:

plainToClass(MyDTOResponse, MyRawDataObject, {
  excludeExtraneousValues: true,
});

Referencing the documentation at https://github.com/typestack/class-transformer#exposing-getters-and-method-return-values, my resulting response only contains:

{
  "id": "f8c213c7-5853-4d01-b424-cb0349a6c580",
  "name": "Clean the kitchen!"
}

I am unsure of the mistake I made, but the "thisIsATest" property seems to be missing.

Answer №1

plainToClass function will generate a new instance. If you log this instance, the "thisIsATest" property won't be visible. You can test it with the provided code snippet:

const result = plainToClass(MyDTOResponse, MyRawDataObject, {
  excludeExtraneousValues: true,
});

console.log(result.thisIsATest); // yolo

console.log(instanceToPlain(result))
// {
//   id: 'f8c213c7-5853-4d01-b424-cb0349a6c580',
//   name: 'Clean the kitchen!',
//   thisIsATest: 'yolo'
// }

By the way, it is recommended to use the plainToInstance method as plainToClass is now deprecated.

Answer №2

Utilizing the Transform decorator allows you to achieve this objective by eliminating the need for the getter method,

an example implementation can be seen below:


import { Expose } from 'class-transformer';

export class MyDTOResponse {
  @Expose()
  id: string;

  @Expose()
  name: string;

  @Expose()
  @Transform(({ value, key, obj, type }) => 'yolo' )
  thisIsATest: string

  @Expose()
  @Transform(({ value, key, obj, type }) => obj.name )
  thisIsATestB: string
}

For further details, refer to the following link:

Explore advanced usage of transform feature

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

My findOne() function seems to be malfunctioning - could there be an issue with my syntax?

I have created a database called 'rodrigo-contatos' using the following code: var mongojs = require('mongojs'); var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']); In an attempt to search the database, I am ...

Error encountered while utilizing the infinite-react-carousel package in React

After entering "npm i infinite-react-carousel --save" into the terminal, an error message appears: "npm ERR! code ERESOLVE "npm ERR! ERESOLVE unable to resolve dependency tree" What could be causing this issue? How can I troubleshoot and resolve it? I h ...

Tips for dynamically adjusting the style of table rows in a v-for iteration:

I'm trying to dynamically change the background color of a table row within a v-for loop based on a condition - if global.globalGroupLevel is equal to 0, I want the background color to be one color, and if it's not 0, I want it to be another colo ...

The Ajax URL is failing to connect with the controller through IIS

I am facing an issue where the application gets stuck in the Home controller when running it on IIS. It doesn't progress to the next controller (Data controller) as specified in the URL. However, when I run it in debug mode, everything works fine. How ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

Creating a variable name from a string using a function

I am creating a log to keep track of the functions that are called. One specific function I am using is record_activity( function_name ); I find it tedious to manually add this at the beginning of every function I want to monitor. Currently, my functions ...

Simply use `$timeout` inside the `$watch` method in AngularJS to create a chained

My goal is to link two $timeout functions inside a $watch. This $watch monitors user actions, and if any action is detected, both $timeout instances are canceled. Below is the code snippet outlining this scenario. .run(['$rootScope', '$loc ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

Covering a doughnut shape with a twisting spiral

I want to achieve a hula hoop covered in tape effect using three.js. The 3D model should look similar to the image below. https://i.sstatic.net/lj9cR.jpg I have been able to create the hoop in 3D space using TorusGeometry and pan around, but I am strugg ...

Uninstalling the most recent version of node and going back to an older version is a straightforward

Error: Module 'graphql/validation/rules/KnownArgumentNamesRule' not found. Require stack: - C:\Users\Minseo\AppData\Roaming\npm\node_modules\apollo\node_modules@apo llo\federation\dist\compos ...

What is the best way to create rotational movement for an object in a-frame?

Is there a way to have my entity rotate/spin on the Y-axis? I attempted the following: <a-entity position="-1 0.5 3" animation="property: rotation; to: 0 0 0 ; loop: true; elasticity:1000; dur: 10000" rotation="90 0 0"> <a-box position="1 0 ...

Utilizing AngularJS with multiple dynamically generated forms on a webpage: Extracting data from each form

I am facing a challenge with a web page I have created that uses PHP to generate forms for updating information via a REST API on a remote server. The structure of the forms is as follows: Textfield: name textfield: description select: type (ng-model="se ...

What is the best way to incorporate a comment section in my existing comment box in order to display comments beneath it?

Is there a way to include a comment feature in my comment box so that comments are displayed beneath it? The comment box itself is set up, but this specific addition is missing. Here's my HTML code... <!DOCTYPE html> <html lang="en&quo ...

Switch out a section of the web address with the information from the button to

Before we begin: Check out this Fiddle My current goal is to create a functionality where clicking a button will replace the # in a given link with the text entered in a text box, and then redirect the user to that modified link. http://www.twitch.tv/#/ ...

Swapping out the context of JavaScript's this keyword

After researching scope and context through various articles, I still have a question lingering in my mind. If you take a look at my JSFiddle here, you'll see what I'm working with. My goal is to convert my functions to arrow functions and replac ...

Select a Date: Input for Date Selection

Is it possible to restrict the selection of certain days using HTML date input validation? Some booking websites have a feature where an interactive calendar only allows users to select specific dates for events, while others are greyed out and cannot be c ...

Choose a Range of DOM Elements

My challenge is to select a range of DOM elements, starting from element until element. This can be done in jQuery like this: (Source) $('#id').nextUntil('#id2').andSelf().add('#id2') I want to achieve the same using JavaScr ...

Trouble integrating PDF from REST API with Angular 2 application

What specific modifications are necessary in order for an Angular 2 / 4 application to successfully load a PDF file from a RESTful http call into the web browser? It's important to note that the app being referred to extends http to include a JWT in ...

Can Typegoose classes be used as types?

Currently, I am working on integrating my client class with a typegoose model named Member. Although I know how to use it, I am facing difficulties in setting up the types and intellisense correctly. The class is exported as MemberClass, and I need assista ...

TypeScript overloading error: Anticipated 0 parameters, received 2 instead

I am facing an issue with a class containing an overloaded method that has two versions. One version does not take any arguments, while the second one can take two arguments. class DFD { ... getEndDatetime(): string; getEndDatetime(startTime?: ...