0

When extending Apollo Server's DataSources we have to create an initialize method, inside the class :

initialize(config){
  this.context=config.context
}

Yet I cannot clearly define a mental model when it comes to the relationship between the class extension of DataSources and context.As seen in the GitHub repo of Apollo , the way to access the methods of your custom data source is by destructuring dataSource , like this:

getRandomData: (parent,args,{dataSource})=>{
  return dataSources.randomMethod()
}

Yet , how do we pass the context to Apollo Server? I thought something like this :

const server= new ApolloServer({
   typeDefs,
   schema,
   context,
   dataSources:()=>({...})
}

But if it were like this , {dataSources} destructuring does not make sense in the resolvers , so what exactly is the relationship between dataSources and context? Thank you !

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Peter Malik
  • 403
  • 4
  • 14

1 Answers1

0

Apollo server will initialize dataSources within processGraphQLRequest function, it will call dataSources.initialize() method with GraphQL request context. That's why you can get the context object inside your custom data source .initialize() method. And assign dataSources to the dataSources attribute of the context, which is why you can get dataSources through destructuring in the GrapQL resolver.

  async function initializeDataSources() {
    if (config.dataSources) {
      const context = requestContext.context;

      const dataSources = config.dataSources();

      const initializers: any[] = [];
      for (const dataSource of Object.values(dataSources)) {
        if (dataSource.initialize) {
          initializers.push(
            dataSource.initialize({
              context,
              cache: requestContext.cache,
            }),
          );
        }
      }

      await Promise.all(initializers);

      if ('dataSources' in context) {
        throw new Error(
          'Please use the dataSources config option instead of putting dataSources on the context yourself.',
        );
      }

      (context as any).dataSources = dataSources;
    }
  }
}

The processGraphQLRequest function called inside executeOperation method of ApolloServerBase.

Lin Du
  • 88,126
  • 95
  • 281
  • 483