带有 Apollo 数据源的 NestJS [英] NestJS with Apollo DataSource

查看:20
本文介绍了带有 Apollo 数据源的 NestJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试重新创建 Apollo 教程NestJS.但是当我尝试使用 apollo-datasource-rest 使用 NestJS,从外部数据源获取数据时失败,错误如下:

I have been trying to re-create the Apollo tutorial with NestJS. But when I try using apollo-datasource-rest with NestJS, it fails when fetching data from the external data source with the following error:

[Nest] 29974   - 07/14/2020, 9:33:20 PM   [ExceptionsHandler] Cannot read property 'fetch' of undefined +125971ms
TypeError: Cannot read property 'fetch' of undefined

好像数据源类没有正确注入解析器中,但我不知道为什么?

It seems as if the data source class in not being injected properly in the resolver, but I can't figure out why?

// The data source class
@Injectable()
class LaunchAPI extends RESTDataSource {
  constructor() {
    super();
    this.baseURL = 'https://api.spacexdata.com/v2/';
  }
  async getLaunchById({ launchId }) {
    return await this.get('launches', { flight_number: launchId });
  }
}

// The Nest resolver
@Resolver('launch')
@Injectable()
export class LaunchResolver {
  constructor(private readonly  launchAPI: LaunchAPI) {}

  @Query('getLaunch')
  async getLaunch(
    @Args('id') id: string
  ) {
    return await this.launchAPI.getLaunchById({ launchId: id })
  }
}

// The app module
@Module({
  imports: [
    GraphQLModule.forRoot({
      dataSources,
      context: ({ req }) => {
        if (req) {
          return { headers: req.headers };
        }
      },
      typePaths: ['./**/*.graphql'],
      definitions: {
        path: join(process.cwd(), 'src/graphql.schema.ts'),
        outputAs: 'class',
      },
      debug: true,
    })
  ],
  controllers: [AppController],
  providers: [AppService, LaunchAPI, LaunchResolver],
})
export class AppModule {}

将 Apollo 的数据源与 Nest 解析器结合使用的最佳方式是什么?

What's the best way to use Apollo's data source with Nest resolvers?

推荐答案

我能够通过在我的每个解析器方法上使用 @Context 装饰器来获取阿波罗数据来解决这个问题源服务(例如dataSources),而不是在解析器类中注入数据源.所以更新后的样子如下:

I was able to solve the issue by using the @Context decorator on each of my resolver methods in order to grab the apollo data source services (e.g. dataSources), instead of injecting the data source in the resolver class. So the updated looks as following:

// The Nest resolver
@Resolver('launch')
@Injectable()
export class LaunchResolver {
  @Query('getLaunch')
  async getLaunch(
    @Context('dataSources') { launchAPI }: DataSources,
    @Args('id') id: string
  ) {
    return await launchAPI.getLaunchById({ launchId: id })
  }
}

// app.module.ts

// set up any dataSources our resolvers need
const dataSources = () => ({
  launchAPI: new LaunchAPI(),
});

@Module({
  imports: [
    GraphQLModule.forRoot({
      dataSources,
      context: ({ req }) => {
        if (req) {
          return { headers: req.headers };
        }
      },
      typePaths: ['./**/*.graphql'],
      definitions: {
        path: join(process.cwd(), 'src/graphql.schema.ts'),
        outputAs: 'class',
      },
      debug: true,
    })
  ],
  controllers: [AppController],
  providers: [AppService, LaunchAPI, LaunchResolver],
})
export class AppModule {}

这篇关于带有 Apollo 数据源的 NestJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆