WARNING THE CODE BELOW IS INCORRECT DATASOURCES NEED TO BE CREATED PER REQUEST.
DO NOT USE THE CODE BELOW
Im attempting to use a apollo-rest-datasource with NestJS. The downside Im seeing is the DataSources do not participate in NestJS' DI system.
I was able to work around this by having NestJS instantiate the singleton datasources and then using GraphQLModule.forRootAsync 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]
I now get DI working in my DataSource, and can use DI within the resolvers to include my DataSource instances (instead of accessing from the GraphQL context). While this works, it just feels wrong.
Is there a better approach for NestJS' DI and Apollo GraphQL context?