typestack / class-transformer

Decorator-based transformation, serialization, and deserialization between objects and classes.
MIT License
6.64k stars 486 forks source link

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

Closed bansiddha-indexnine closed 1 month ago

bansiddha-indexnine commented 3 months ago

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; }


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; }

2astm commented 2 months ago

the same

diffy0712 commented 2 months ago

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 commented 1 month ago

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

github-actions[bot] commented 4 weeks ago

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.