WARNING: THE CODE BELOW IS INCORRECT, DATASOURCES NEED TO BE CREATED PER REQUEST.
PLEASE AVOID USING THE CODE BELOW
I am currently exploring using an apollo-rest-datasource
within NestJS. One challenge I have encountered is that the DataSources do not integrate with NestJS' Dependency Injection system.
To work around this limitation, I had NestJS instantiate the singleton datasources and then utilized GraphQLModule.forRootAsync
to inject these instances into the dataSources
property of Apollo Server.
GraphQLModule.forRootAsync({
imports: [
DataSourcesModule
],
useFactory: (...args: DataSource[]) => {
return {
typePaths: ['./**/*.graphql'],
context: ({req}: {req: Request}) => ({ token: req.headers.authorization }),
playground: true,
dataSources: () => {
let dataInstances = {} as any;
args.forEach(arg => {
const dataSource = arg as any;
dataInstances[dataSource.constructor.name] = arg;
});
return dataInstances;
},
};
},
inject: [...dataSources]
With this setup, I was able to achieve Dependency Injection functionality in my DataSource and utilize DI within the resolvers by including my DataSource instances (rather than accessing them from the GraphQL context). While this solution works, it does feel somewhat unorthodox.
Are there alternative approaches for integrating NestJS' DI with the Apollo GraphQL context?