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

本文是小编为大家收集整理的关于带有Apollo数据源的NestJS的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我一直在尝试重新创建 apollo tutorial Nestjs.但是,当我尝试使用 apollo-datasource-rest 从外部数据源获取数据时,它会失败.

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

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

// 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的数据源的最佳方法是什么?

推荐答案

我能够通过在我的每种解析器方法上使用@Context装饰器来解决问题,以获取Apollo数据源服务(例如dataSources),而不是将数据源注入解析器类.因此,更新的外观如下:

// 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 {}

本文地址:https://www.itbaoku.cn/post/1938105.html

问题描述

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 {}

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

推荐答案

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 {}