TreeMan360 / nestjs-graphql-dataloader

Easily add dataloader to a nestjs/graphql 7+ application with automatic sequencing and a template method
86 stars 24 forks source link

Using data loaders in a service #35

Open synic opened 2 years ago

synic commented 2 years ago

The current @Loader decorator works fine as a parameter to a @ResolveField function, etc. Is there a way to inject the data loader into a service constructor?

amzhang commented 2 years ago

3 ways I can see:

  1. If you use @Inject(REQUEST) request:
@Injectable()
export class UserService {
  constructor(
    // @InjectRepository(User) private readonly userRepository: Repository<User>,
    private userRepository: UserRepository,
    @Inject(REQUEST) request,
  ) {}
}

Then you can get at the loader factory directly:

const loader = request["NEST_LOADER_CONTEXT_KEY"].getLoader(UserLoader);
loader.load(id)

BUT the @Inject(REQUEST) request provider is Scope.REQUEST, which means it will bubble up and make any provider that uses UserService also scope with Scope.REQUEST. This might impact your performance.

  1. You could just pass in the loader into the service from the caller, which is presumably from the controller

  2. Use async local storage. I'm unfamiliar with this but I know that Mikro-ORM in Nestjs uses this approach.

https://github.com/medibloc/nestjs-request-context