3

New to Apollo, so I decided to take the most simple example I found and try to work it in a slightly different way. My code can be found here.

The problem I am having is that the Subscription doesn't seem to get called when I call the Mutation createTask(). The Mutation and Subscription are defined in schema.graphql as:

type Mutation {
  createTask(
    text: String!
  ): Task
}

type Subscription {
  taskCreated: Task
}

And in resolvers.js as:

Mutation: {
  createTask(_, { text }) {
    const task = { id: nextTaskId(), text, isComplete: false };
    tasks.push(task);
    pubsub.publish('taskCreated', task);
    return task;
  },
},
Subscription: {
  taskCreated(task) {
    console.log(`Subscript called for new task ID ${task.id}`);
    return task;
  },
},

What I am expecting to happen is that I would get a console.log in the server every time I run the following in the client:

mutation Mutation($text: String!) {
  createTask(text:$text) {
    id
    text
    isComplete
  }
}

But nothing happens. What am I missing?

CodeChimp
  • 8,016
  • 5
  • 41
  • 79

1 Answers1

0

The subscription resolver function is called when there is actually a subscription to the GraphQL Subscription.

As you did not add a client which uses subscriptions-transport-ws and the SubscriptionClient for subscribing to your websocket and the subscription it will not work.

What you could do is add the subscription Channel to the setupFunctions of the SubscriptionManager and therein you get the value that the pubsub.publish function delivers.

Could look like this:

...

const WS_PORT = 8080;

const websocketServer = createServer((request, response) => {
  response.writeHead(404);
  response.end();
});

websocketServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console
  `Websocket Server is now running on http://localhost:${WS_PORT}`
));

const subscriptionManager = new SubscriptionManager({
  schema: executableSchema,
  pubsub: pubsub,
  setupFunctions: testRunChanged: (options, args) => {
    return {
      taskCreated: {
        filter: (task) => {
          console.log(task); // sould be log when the pubsub is called
          return true;
        }
      },
    };
  },
  ,
});

subscriptionServer = new SubscriptionServer({
  subscriptionManager: subscriptionManager
}, {
  server: websocketServer,
  path: '/',
});

...
Locco0_0
  • 3,420
  • 5
  • 30
  • 42