nestjs-graphql-dataloader
nestjs-graphql-dataloader copied to clipboard
Using data loaders in a service
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?
3 ways I can see:
- 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.
-
You could just pass in the loader into the service from the caller, which is presumably from the controller
-
Use async local storage. I'm unfamiliar with this but I know that Mikro-ORM in Nestjs uses this approach.