在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):TreeMan360/nestjs-graphql-dataloader开源软件地址(OpenSource Url):https://github.com/TreeMan360/nestjs-graphql-dataloader开源编程语言(OpenSource Language):TypeScript 100.0%开源软件介绍(OpenSource Introduction):nestjs-graphql-dataloaderBased on https://github.com/krislefeber/nestjs-dataloader this small library assists in adding https://github.com/graphql/dataloader to a NestJS project. This package also ensures that the ids are mapped to the dataloader in the correct sequence automatically and provides a helpful base class to simplify dataloader creation. Requires NestJS 7+ Installationnpm:
yarn:
Usage1. Register DataLoaderInterceptorFirst, register a NestJS interceptor in your applications root module(s) providers configuration. This can actually be placed in any of your modules and it will be available anywhere but I would recommend your root module(s). It only needs to be defined once. Add: {
provide: APP_INTERCEPTOR,
useClass: DataLoaderInterceptor,
} For example: import { DataLoaderInterceptor } from 'nestjs-graphql-dataloader'
...
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: DataLoaderInterceptor,
},
],
...
imports: [
RavenModule,
ConfigModule.load(
path.resolve(__dirname, '../../config', '**/!(*.d).{ts,js}'),
), 2. Build @Loaders for each @ObjectTypeUsing the provided template method, import { Injectable } from '@nestjs/common'
import { OrderedNestDataLoader } from 'nestjs-graphql-dataloader'
import { Location } from '../core/location.entity'
import { LocationService } from '../core/location.service'
@Injectable({ scope: Scope.REQUEST })
export class LocationLoader extends OrderedNestDataLoader<Location['id'], Location> {
constructor(private readonly locationService: LocationService) {
super()
}
protected getOptions = () => ({
query: (keys: Array<Location['id']>) => this.locationService.findByIds(keys),
})
}
Add these to your modules providers as usual. You will most likely want to include it in your modules exports so the loader can be imported by resolvers in other modules.
interface IOrderedNestDataLoaderOptions<ID, Type> {
propertyKey?: string
query: (keys: readonly ID[]) => Promise<Type[]>
typeName?: string
} Since the majority of the time a The The query is the equivalent of a 3. Use the @Loader in @ResolveFieldTo then use the resolver it just needs to be injected into the resolvers field resolver method. Here is an example: import DataLoader from 'dataloader'
...
@ResolveField(returns => [Location])
public async locations(
@Parent() company: Company,
@Loader(LocationLoader)
locationLoader: DataLoader<Location['id'], Location>,
) {
return locationLoader.loadMany(company.locationIds)
} |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论