Transform decorator in class-transformer does not wait for asynchronous function and returns a Promise instead of the transformed value
bansiddha-indexnine opened this issue · 4 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;
}
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;
}
the same
The Transform decorator signature calls for a function
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
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.