So I have two entities, User and Role with Many-To-Many relationship between them.
user.entity.ts
@Entity()
@ObjectType()
export class User {
@PrimaryGeneratedColumn('uuid')
@Field(() => String)
id: string;
@Field(() => String)
@Column()
name!: string;
@Field(() => [Role])
@ManyToMany(() => Role, (role) => role.users, {
cascade: true,
lazy: true,
})
@JoinTable()
roles!: Array<Role>;
}
// Deleting the unnecessary properties for readability
role.entity.ts
@Entity()
@ObjectType()
export class Role {
@PrimaryGeneratedColumn('uuid')
@Field(() => String)
id: string;
@Field(() => String)
@Column()
name!: string;
@Field(() => [User])
@ManyToMany(() => User, (user) => user.roles, {
lazy: true,
})
users: Promise<Array<User>>;
@Field(() => String)
@CreateDateColumn()
createdAt: Date;
}
The problem I am facing is that when I have to create a new User, I have to first extract the role ids from the DTO, fetch for each ID the role object in the database and then wire it to the user object manually before saving.
const {roleIds} = createUserInput;
const roles = roleIds.map(async (id) => await roleService.findById(id))
const user = this.userRepository.create({...createUserInput, roles});
return this.userRepository.save(user);
And this is all working fine, but I just am curious if there is a way to get this to work without making the extra calls and manual wiring. If I can just pass in the roleIds and it magically auto resolves it. Something like this:
const user = this.userRepository.create({...createUserInput, roleIds});