The classToPlain transformation is not compatible with routing-controllers

When it comes to using class-transformer and routing-controllers, I seem to be encountering some confusion. I tried to utilize the class-transformer library to convert objects received from a third-party server and adapt them to fit my own model with different names. Initially, this seemed to work fine as I was able to see the converted model when logging it or converting it to JSON. However, when attempting to output the model using routing-controllers, it still showed the original object.

User class:

class User {
  @Expose({ name: 'uid' }) // To convert/rename the "uid" property received from the server
  id: string
  firstName: string
  lastName: string
}

users-controller.ts:

@JsonController('/users')
export class UsersController {
  @Get('/')
  async get() {
    const user = plainToClass(User, {
      uid: '123',
      firstName: 'Matthew',
      lastName: 'Michalsky'
    })

    console.log(user)

    return user
  }
}

The console displays the expected value:

User {
  id: '123',
  firstName: 'Matthew',
  lastName: 'Michalsky'
}

However, the response from UsersController (using routing-controllers lib) shows:

{
  uid: '123',
  firstName: 'Matthew',
  lastName: 'Michalsky'
}

I'm wondering if there is something missing or incorrectly done on my end. Any insights would be greatly appreciated. Thanks!

Answer №1

Indeed. The response returns JSON data, making it impossible to transfer class names in the process. This is why when you return a class instance from a controller using routing-controllers, the classToPlain method is applied, resulting in a transformed plain object.

If you wish to bypass this behavior, you can configure @ResponseClassTransformOption.

  @ResponseClassTransformOption({
    ignoreDecorators: true,
  })
  @Get('/')
  async get() {

Additionally, you have the option to specify the direction of transformation, such as setting it to "toClass only". In this case, when a class instance undergoes processing via classToPlain, decorators like these won't take effect.

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

Intellij IDEA does not offer auto-completion for TypeScript .d.ts definitions when a function with a callback parameter is used

I've been working on setting up .d.ts definitions for a JavaScript project in order to enable auto-completion in Intellij IDEA. Here is an example of the JavaScript code I'm currently defining: var testObj = { tests: function (it) { ...

The client's cookie does not appear when Cookie is displayed. This may be due to Javascript

Working with an API provided by a company. Upon logging in, the server sends a cookie to the client. To retrieve this cookie, I use the following command: const loginCookie = response.headers.get('set-cookie') I then output the cookie value to ...

What is the best way to refresh the data in my list when a subitem is updated through a GET request using RTK Query?

Having a good understanding of the RTK query concept, I am facing a specific use case where I require some guidance. In my application, there is a list component and a details component that allows users to navigate and view more information about a parti ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

encountering a hiccup while deploying my MERN website on Railway platform

My latest project is a Discord clone portfolio that can be found on GitHub. I have successfully deployed the frontend to Vercel at this link. While it functions correctly in Firefox, there seems to be an issue with Chrome and Edge where network requests ge ...

What is the method for installing TypeScript declarations for packages with scopes or namespaces using @types?

My current challenge involves the use of TypeScript and my desire to utilize a scoped package such as @foo/bar or @babel/core that does not include its own type declarations. My attempted solution so far has been to execute the following command: npm ins ...

Having trouble with fetch API and NodeJS/Express causing a 404 error on XHR POST requests?

Recently, I've been diving into learning how to implement the fetch API for my front-end development work. However, I seem to be facing a persistent XHR 404 POST error. //Backend file const express = require("express"); const app = expre ...

What is preventing Backbone from triggering a basic route [and executing its related function]?

Presenting My Router: var MyRouter = Backbone.Router.extend({ initialize: function(){ Backbone.history.start({ pushState:true }); }, routes: { 'hello' : 'sayHello' }, sayHello: function(){ al ...

What causes the "This page isn't responding" error to pop up in Edge and Chrome browsers while attempting to perform consecutive tasks in a web application built with Angular 8?

Trouble with Page Loading Whenever this error occurs, I find myself unable to perform any activities on that page. The only solution is to close the tab and open a new one. My current code allows me to navigate through an array list (Next and Previous) us ...

The NextJS image URL remains constant across various endpoints

Currently experiencing an issue with my Channel Tab where the icon and name of the channel are displayed. The problem is that every time I switch channels, the icon remains the same as the first channel I clicked on. PREVIEW This is the code I am current ...

What is the method to declare data types within the map function?

When retrieving data from a server, I receive an object that includes four arrays with different types of objects. I am attempting to map this data before subscribing to the observable so that I can properly utilize the classes in my frontend: getData(){ ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

Utilizing a Single Variable Across Multiple Middlewares in nodeJS

I encountered an issue where I am attempting to utilize one variable across two middlewares, but it displays an error stating that the variable is not defined. Here is an example of my situation: //1st middleware app.use((req, res, next) =>{ cont ...

Implementing a node.js application deployment with pm2 to ensure zero downtime

While there are countless tutorials on developing chat applications using socket.io and node.js, the event-driven advantage of Node is undeniable for building chat apps. However, a recent thought crossed my mind - how can I ensure the sustainability of my ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Angular2 is throwing an error: "NavigationService provider not found! (MenuComponent -> NavigationService)"

I am in the process of developing an angular (beta7) application. I aim to have a MenuComponent at the top that utilizes the NavigationService to navigate throughout different sections of my app. To ensure that the NavigationService remains a singleton, I ...

Unable to utilize AgmMarkerSpiderModule

I followed the instructions to add the AgmMarkerSpiderModule from the official package documentation. However, when I compile, I encountered the following error message: /directives/marker-spider.ts:14:24 - error TS2307: Cannot find module '@agm/core/ ...

Tips for implementing type safety in a generic class to verify that the response type aligns with the anticipated type in TypeScript

In TypeScript, I have created a QueryFactory class with two generic type parameters: TQuery and TResponse. My goal is to ensure type safety so that if the TResponse type does not match the expected response type of the TQuery type, the compiler will throw ...

What steps should I take to resolve the eslint issue indicating that a TypeScript props interface is not being utilized, even though it is being used?

One of my components utilizes AvatarProps for its props: https://i.sstatic.net/cZBl1.png Below is the interface declaration for AvatarProps: export interface AvatarProps { userName: string; userLastName: string; userImg?: string; onPress?: Functi ...

In search of a resolution for the asynchronous problem using Javascript

Currently in the process of developing an application with Angular, socket.io, and express. Though, I am facing a challenge regarding asynchronous operations that I am struggling to resolve. Below is the snippet of code causing the issue: export class W ...