Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle one-to-many with type-graphql typeorm and dataloader

I'm trying to figure out the best way to handle a one-to-many relationship using type-graphql and typeorm with a postgresql db (using apollo server with express). I have a user table which has a one-to-many relation with a courses table. The way I am currently handling this is to use the @RelationId field to create a column of userCourseIds and then using @FieldResolver with dataloader to batch fetch the courses that belong to that user(s). My issue is that with the @RelationId field, a separate query is made to get the relationids whether or not I actually query for userCourses. Is there a way to handle this where it won't make that extra query or is there a better way to go about handling one-to-many relationships?

User side of relation:

@OneToMany(() => Course, (course) => course.creator, { cascade: true })
userCourses: Course[];
@RelationId((user: User) => user.userCourses)
userCourseIds: string;

Course side of relation:

@Field()
@Column()
creatorId: string;

@ManyToOne(() => User, (user) => user.userCourses)
creator: User;

userCourses FieldResolver:

@FieldResolver(() => [Course], { nullable: true })
async userCourses(@Root() user: User, @Ctx() { courseLoader }: MyContext) {
  const userCourses = await courseLoader.loadMany(user.userCourseIds);
  return userCourses;
}
like image 222
Joel Jacobsen Avatar asked Aug 30 '20 23:08

Joel Jacobsen


1 Answers

userCourses field can be written like below using @TypeormLoader decorator provided by type-graphql-datalaoader.

@ObjectType()
@Entity()
class User {
  ...

  @Field((type) => [Course])
  @OneToMany(() => Course, (course) => course.creator, { cascade: true })
  @TypeormLoader((course: Course) => course.creatorId, { selfKey: true })
  userCourses: Course[];
}

@ObjectType()
@Entity()
class Course {
  ...

  @ManyToOne(() => User, (user) => user.userCourses)
  creator: User;

  @RelationId((course: Course) => course.creator)
  creatorId: string;
}

Additional queries will not be issued anymore since userCourseIds is omitted. Although creatorId with @RelationId exists, it will not issue extra queries since the entity has the value by its own.

Update: June 2021

@TypeormLoader no longer needs arguments. Therefore @RelationId can be completely omitted, if preferred.

like image 143
Kazuaki Tanida Avatar answered Oct 19 '22 16:10

Kazuaki Tanida