-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
59 lines (54 loc) · 1.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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',
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',
});
});