typeorm-graphql-loader icon indicating copy to clipboard operation
typeorm-graphql-loader copied to clipboard

[Question] How does this library handle field resolvers?

Open bombillazo opened this issue 3 years ago • 2 comments

Hey, thanks for your work on this library, very helpful.

I had a question about field resolvers, how would one avoid the N+1 problem and use this library to handle fields that fetch external data or are calculated based on other fields or even model data?

bombillazo avatar Oct 13 '22 15:10 bombillazo

This lib is unopinionated about field resolvers. All it does is return back an object with all the requested relations/columns pre-loaded from the db. If you have a field resolver defined for one of those fields down the chain, your GraphQL server will still call that field resolver. If your GraphQL query includes a field that does not exist in your TypeORM entity, the loader will ignore it. If you never want to load a particular entity field from the db, you can tell the loader to ignore it (see below).

To help with resolving computed fields, it provides a decorator you can use on your entity fields to indicate whether a field is required. This way if you have a computed field on an entity, you can specify the loader include the dependent fields regardless of whether they were included in the query See the documentation for ignore and required here

@Entity()
class User extends BaseEntity {
  @LoaderConfiguration({ required: (context, fields) => fields.includes('fullName') })
  @Column()
  firstname: string;
  @LoaderConfiguration({ required: (context, fields) => fields.includes('fullName') })
  @Column()
  lastname: string;

  // computed method
  fullName() {
    return this.firstname + ' ' + this.lastname
  }
}

This lib does not help with the N+1 problem for fetching data from sources outside of TypeORM. For that, I suggest looking into the dataloader package on npm. It very easy to use this library in conjunction with dataloader if you so wish.

Mando75 avatar Oct 13 '22 21:10 Mando75

Thanks for the quick response and the thorough and informative answer! Appreciate it, this helps a lot! Don't know if you prefer to leave it open for reference.

bombillazo avatar Oct 14 '22 04:10 bombillazo