nestjs + graphql + typeorm, how to transform a lazy relation (promise) into solid array for the model

316 Views Asked by At

I am using nestjs with graphql (apollo) and typeorm. My entity has a lazy relation roles and the model represents it as an array. The issue is that it cannot seem to "magically" transform the Promise<[]> into []. Here's in more detail,

I have the UserModel which looks like this

@ObjectType({ description: 'User' })
export class UserModel {
  @Field()
  id: string;

  @Field(() => [UserRolesModel], { nullable: true })
  roles?: UserRolesModel[]
}

and the UserEntity which looks like that

@Entity({ name: 'user' })
export class UserEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @OneToMany(() => UserRolesEntity, (userRoles) => userRoles.userId)
  roles: Promise<UserRolesEntity[]>;
}

typescript complains that the Promise<UserRolesEntity[]> is not compatible with UserRolesModel[].

TS2322: Type 'UserEntity[]' is not assignable to type 'UserModel[]'.
Type 'UserEntity' is not assignable to type 'UserModel'.
Types of property 'roles' are incompatible.
Type 'Promise<UserRolesEntity[]>' is missing the following properties from type 'UserRolesModel[]': length, pop, push, concat, and 29 more.

I suspect there is some trivial way of doing that with nestjs and the class-transformer? What is the recommended way of solving this?

0

There are 0 best solutions below