• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

TreeMan360/nestjs-graphql-dataloader: Easily add dataloader to a nestjs/graphql ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

TreeMan360/nestjs-graphql-dataloader

开源软件地址(OpenSource Url):

https://github.com/TreeMan360/nestjs-graphql-dataloader

开源编程语言(OpenSource Language):

TypeScript 100.0%

开源软件介绍(OpenSource Introduction):

nestjs-graphql-dataloader

Node.js CI

Based 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+

Installation

npm:

npm i nestjs-graphql-dataloader --save

yarn:

yarn add nestjs-graphql-dataloader

Usage

1. Register DataLoaderInterceptor

First, 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 @ObjectType

Using the provided template method, OrderedNestDataLoader<KeyType, EntityType>, you can easily implement DataLoaders for your types. Here is an example:

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),
  })
}

Note: In these examples the usage of Location['id'] is referring to the type of the location.id property, which in this case is string. It would be perfectly acceptable to declare the generic type argument as string rather than Location['id'].

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.

getOptions takes a single options argument which has the following interface:

interface IOrderedNestDataLoaderOptions<ID, Type> {
  propertyKey?: string
  query: (keys: readonly ID[]) => Promise<Type[]>
  typeName?: string
}

Since the majority of the time a propertyKey is 'id' this is the default if not specified.

The typeName for the above example is automatically assigned 'Location' which is derived from the class name, this is just used for logging errors.

The query is the equivalent of a repository.findByIds(ids) operation. It should return the same number of elements as requested. The order does not matter as the base loader implementation takes care of this.

3. Use the @Loader in @ResolveField

To 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)
}



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap