Quick and easy GraphQL dataloaders for NestJS.
$ npm install @tracworx/nestjs-dataloader
Import the DataloaderModule
in your root module.
import { Module } from '@nestjs/common';
import { DataloaderModule } from '@tracworx/nestjs-dataloader';
import { ItemResolver } from './item.resolver';
import { ItemLoader } from './item.loader';
@Module({
imports: [DataloaderModule],
providers: [ItemResolver, ItemLoader],
})
export class AppModule {}
Decorate dataloader factory classes with @DataloaderProvider()
to automatically provide them to the GraphQL context object for each request.
import DataLoader from 'dataloader';
import { DataloaderProvider } from '@tracworx/nestjs-dataloader';
@DataloaderProvider()
class ItemLoader {
createDataloader(ctx: GqlExecutionContext) {
// Fetch request-scoped context data if needed
const user = ctx.getContext().req.user;
// Replace this with your actual dataloader implementation
return new DataLoader<string, Item>(async (ids) => getItemsWithIds(user, ids));
}
}
Use @Loader(...)
to inject a dataloader instance into your resolver methods.
import DataLoader from 'dataloader';
import { Loader } from '@tracworx/nestjs-dataloader';
import { ItemLoader } from './item.loader';
@Resolver()
class ItemResolver {
@Query(() => Item, { name: 'item' })
getItem(@Args('id') id: string, @Loader(ItemLoader) itemLoader) {
return itemLoader.load(id);
}
}
And that's it. Happy coding!
# build
$ npm run build
# format with prettier
$ npm run format
# lint with eslint
$ npm run lint
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
- Author - Eoin O'Brien
- Website - https://tracworx.ai
- Twitter - @realEoinOBrien
@tracworx/nestjs-dataloader
is MIT licensed.