Skip to content

Commit

Permalink
Add new notification subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
loic-carbonne committed Feb 19, 2018
1 parent 79e6a1a commit 2cb852c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
33 changes: 31 additions & 2 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,58 @@ const express = require('express');
const bodyParser = require('body-parser');
const { graphqlExpress, graphiqlExpress } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');
const { PubSub } = require('graphql-subscriptions');
const cors = require('cors');
const { execute, subscribe } = require('graphql');
const { createServer } = require('http');
const { SubscriptionServer } = require('subscriptions-transport-ws');

const pubsub = new PubSub();
const NOTIFICATION_SUBSCRIPTION_TOPIC = 'newNotifications';

const notifications = [];
const typeDefs = `
type Query { notifications: [Notification] }
type Notification { label: String }
type Mutation { pushNotification(label: String!): Notification }
type Subscription { newNotification: Notification }
`;
const resolvers = {
Query: { notifications: () => notifications },
Mutation: {
pushNotification: (root, args) => {
const newNotification = { label: args.label };
notifications.push(newNotification);
pubsub.publish(NOTIFICATION_SUBSCRIPTION_TOPIC, { newNotification: newNotification });

return newNotification;
},
},
Subscription: {
newNotification: {
subscribe: () => pubsub.asyncIterator(NOTIFICATION_SUBSCRIPTION_TOPIC)
}
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });

const app = express();
app.use('*', cors({ origin: `http://localhost:3000` }));
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
app.listen(4000, () => {
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://localhost:4000/subscriptions`
}));
const ws = createServer(app);
ws.listen(4000, () => {
console.log('Go to http://localhost:4000/graphiql to run queries!');

new SubscriptionServer({
execute,
subscribe,
schema
}, {
server: ws,
path: '/subscriptions',
});
});
6 changes: 5 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@
"dependencies": {
"apollo-server-express": "^1.3.2",
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"graphql-tools": "^2.21.0"
"graphql-subscriptions": "^0.5.7",
"graphql-tools": "^2.21.0",
"http": "0.0.0",
"subscriptions-transport-ws": "^0.9.5"
}
}

0 comments on commit 2cb852c

Please sign in to comment.