nestjs-graphql-dataloader icon indicating copy to clipboard operation
nestjs-graphql-dataloader copied to clipboard

Using data loaders in a service

Open synic opened this issue 3 years ago • 1 comments

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?

synic avatar Nov 30 '21 00:11 synic

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

amzhang avatar Aug 29 '22 12:08 amzhang