question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Datasources missing in the context when using subscriptions

See original GitHub issue

Intended outcome: Context in the resolver functions will contain dataSources field when using subscriptions just like when calling with queries.

Actual outcome: Field dataSources is missing while using subscriptions in the context (in subscribe and resolve functions). The context contains everything except this one field.

How to reproduce the issue:

  1. set dataSources to the server
const server = new ApolloServer({
    schema: Schema,
    dataSources: () => createDataSources(),
	// ...
})
  1. dump content of the context:
subscribe: (parent, args, context) => {
    console.warn(context); // dataSources missing, every other field is there correctly
})

I think this is quite serious because otherwise, I cannot query my data sources at all while using subscriptions.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:23 (4 by maintainers)

github_iconTop GitHub Comments

20reactions
martijnwalravencommented, Aug 14, 2018

Unfortunately, this is a known issue. Although we run SubscriptionServer as part of ApolloServer, the request pipeline is completely separate. That means features like persisted queries, data sources, and tracing don’t currently work with subscriptions (or queries and mutations over the WebSocket transport).

There is work underway on a refactoring of the apollo-server-core request pipeline that will make it transport independent, and that will allow us to build the WebSocket transport on top of it. Until then, I’m afraid there isn’t much we can do.

12reactions
josedachecommented, May 16, 2020

I solved this by using @PatrickStrz method with some little tweak to have each Datasource instance to have the full context, Same way apollo server initializes its Datasources


const pubSub = new PubSub();

/**
 * Generate dataSources for both transport protocol
 */
function dataSources() {
  return {
    userService: new UserService(),
    ministryService: new MinistryService(),
    mailService: new MailService(),
  };
}

/**
 * Authenticate  subscribers on initial connect
 * @param {*} connectionParams 
 */
async function onWebsocketConnect(connectionParams) {
  const authUser = await authProvider.getAuthenticatedUser({
    connectionParams,
  });
  if (authUser) {
    return { authUser, pubSub, dataSources: dataSources() };
  }
  throw new Error("Invalid Credentials");
}

/**
 * Initialize subscribtion datasources
 * @param {Context} context 
 */
function initializeSubscriptionDataSources(context) {
  const dataSources = context.dataSources;
  if (dataSources) {
    for (const instance in dataSources) {
      dataSources[instance].initialize({ context, cache: undefined });
    }
  }
}

/**
 * Constructs the context for transport (http and ws-subscription) protocols
 */
async function context({ req, connection }) {
  if (connection) {
    const subscriptionContext = connection.context;
    initializeSubscriptionDataSources(subscriptionContext);
    return subscriptionContext;
  }

  const authUser = await authProvider.getAuthenticatedUser({ req });
  return { authUser, pubSub };
}

/**
 * Merges other files schema and resolvers to a whole
 */
const schema = makeExecutableSchema({
  typeDefs: [rootTypeDefs, userTypeDefs, ministryTypeDefs, mailTypeDefs],
  resolvers: [rootResolvers, userResolvers, ministryResolvers, mailResolvers],
});

/**
 * GraphQL server config
 */
const graphQLServer = new ApolloServer({
  schema,
  context,
  dataSources,
  subscriptions: {
    onConnect: onWebsocketConnect,
  },
});


Hope this helps 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Subscriptions in Apollo Server - Apollo GraphQL Docs
Each subscription operation can subscribe to only one field of the Subscription type. Enabling subscriptions. Subscriptions are not supported by Apollo Server ...
Read more >
node.js - Can't access this.context inside a defined class and ...
Show activity on this post. So my issue is trying to access the context inside this class. It always returns undefined. Now I...
Read more >
Why ERROR "DefaultDataSource is missing [jboss.naming ...
Issue. If the default datasource ExampleDS is removed from JBoss EAP, applications are not getting deployed successfully, even though those ...
Read more >
Handling data source errors (Power Query) - Microsoft Support
Advice on how to identify, deal with, and resolve errors from externals data sources and Power Query when you refresh data.
Read more >
Troubleshoot Subscriptions - Tableau Help
However, if the background process is handling an extraordinarily large and complex dashboard, that may not be enough time. You can check the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found