Skip to content

Loaders

Davide Gheri edited this page Feb 19, 2021 · 2 revisions

Mercurius offers a solution to the 1 + N query problem of GraphQL out of the box, Loaders.

Loaders are defined like field resolvers that coalesces each of the request and combines them into a single, bulk query.

import { ResolveLoader, LoaderQuery } from 'nestjs-mercurius'; 

@Resolver( => Cat)
export class CatResolver {
  //...
  @ResolveLoader(() => Owner, { nullable: true, opts: { cache: true /*this is the default*/ } })
  owner(
    @Parent() queries: LoaderQuery<Cat>[],
    @Context() ctx: any,
  ) {
    // queries is an array of objects defined as { obj, params } where obj is the current object and params are the GraphQL params
    // Loader functions should return an array the same length of queries

    return this.userService.findByIds(
      queries.map(({ obj }) => obj.ownerId)
    )
  }
}

ResolveLoader decorator has the same signature of NestJs ResolveField and accepts the same options, plus an opts object with Loader specific options ({ cache: boolean })