带有Apollo数据源的NestJS [英] NestJS with Apollo DataSource
问题描述
我一直在尝试使用以下方法重新创建 Apollo教程 NestJS.但是,当我尝试在NestJS中使用 apollo-datasource-rest
时,从外部数据源中获取数据时失败,并显示以下错误:
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
装饰器来解决该问题,以获取阿波罗数据源服务(例如,
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屋!