class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

Transform decorator in class-transformer does not wait for asynchronous function and returns a Promise instead of the transformed value

Open bansiddha-indexnine opened this issue 1 year ago • 2 comments

Hi there, we are using class-transformer with groups in nestJs. We are struggling on how to make class-transformer await a property when this property is exposed. Currently it result in a null object.

@Entity() export class User extends Audit { @ManyToOne(() => Organization, (organization) => organization.id, { nullable: true }) organization?: Promise<Organization>; }


export class UserDto { @ApiProperty() @Expose() @Transform(async ({ obj }) => { const resolvedValue = await obj.organization; if (resolvedValue && Object.keys(resolvedValue).length > 0) { return resolvedValue.name; } else { return null; } }) organization: string; }

bansiddha-indexnine avatar Mar 28 '24 15:03 bansiddha-indexnine

the same

2astm avatar Apr 11 '24 12:04 2astm

The Transform decorator signature calls for a function https://github.com/typestack/class-transformer/blob/69cd8ccbc672179ea46492a625653ec448f03a17/src/decorators/transform.decorator.ts#L10 with return type any, which is a bit misleading (as it will work with a promise in your case at least in ts). I do not see anything that is should support for async calls. it will not await for it I. (if it would support async I think the plainToInstance, instanceToInstance and instanceToPlain functions should support async as well.

The plainToInstance function should be called with the concrete data and awaited before it.

I think you would need something like

const resolvedValue = await something.organization;
const organisation = resolvedValue && 'name' in resolvedValue ? resolvedValue.name : null;

const user = plainToInstance(User, {..., organization});

I hope this helps

diffy0712 avatar Apr 24 '24 21:04 diffy0712

Closing as answered. Note that there is an ongoing issue on async support. https://github.com/typestack/class-transformer/issues/549

diffy0712 avatar May 09 '24 19:05 diffy0712

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Jun 09 '24 00:06 github-actions[bot]