title: NestJS GraphQL DataSources
body: <p><strong>WARNING THE CODE BELOW IS INCORRECT DATASOURCES NEED TO BE CREATED PER REQUEST.</strong></p>
  
  <p><strong>DO NOT USE THE CODE BELOW</strong></p>
  
  <p>Im attempting to use a <a href="https://www.apollographql.com/docs/apollo-server/features/data-sources.html" rel="nofollow noreferrer"><code>apollo-rest-datasource</code></a> with NestJS. The downside Im seeing is the DataSources do not participate in NestJS' DI system.</p>
  
  <p>I was able to work around this by having NestJS instantiate the singleton datasources and then using <code>GraphQLModule.forRootAsync</code> inject these instances into the <code>dataSources</code> property of Apollo Server.</p>
  
  <pre><code> GraphQLModule.forRootAsync({
        imports: [
          DataSourcesModule
        ],
        useFactory: (...args: DataSource[]) =&gt; {
          return {
            typePaths: ['./**/*.graphql'],
            context: ({req}: {req: Request}) =&gt; ({ token: req.headers.authorization }),
            playground: true,
            dataSources: () =&gt; {
              let dataInstances = {} as any;
              args.forEach(arg =&gt; {
                const dataSource = arg as any;
                dataInstances[dataSource.constructor.name] = arg;
              });
              return dataInstances;
            },
          };
        },
        inject: [...dataSources]
  </code></pre>
  
  <p>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. </p>
  
  <p>Is there a better approach for NestJS' DI and Apollo GraphQL context?</p>