GraphQL Dataloaders for NestJS
Description
Quick and easy GraphQL dataloaders for NestJS.
Installation
$ npm install @tracworx/nestjs-dataloader
Usage
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!
Development
# build
$ npm run build
# format with prettier
$ npm run format
# lint with eslint
$ npm run lint
Test
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
Stay in touch
License
@tracworx/nestjs-dataloader
is MIT licensed.