-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (61 loc) · 1.69 KB
/
Copy pathindex.js
File metadata and controls
72 lines (61 loc) · 1.69 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
const express = require('express');
const {graphqlHTTP} = require('express-graphql');
const {buildSchema, subscribe} = require('graphql');
const {PubSub} = require('graphql-subscriptions');
const { createServer } = require('http');
const { useServer } = require('graphql-ws/use/ws');
const { WebSocketServer } = require('ws');
// Schema
const schema = buildSchema(`
type Query {
user: [User]
userById(id:Int!): User
}
type Mutation {
userChangeName(id:Int!, name:String!): User
}
type Subscription {
updatedList: [User]
}
type User {
id: Int
name: String
}`);
const users = [
{ id: 23, name: "Jason" },
{ id: 25, name: "Delfie" },
{ id: 1, name: "Caleb" }
];
const pubSub = new PubSub();
const root = {
user: () => users,
userById: (args) => users.find(u => u.id === args.id),
userChangeName: async (args) => {
for (let i = 0; i < users.length; i++) {
if (users[i].id == args.id) {
users[i].name = args.name
setTimeout(() => {
pubSub.publish('OPERATION_FINISHED', { updatedList: [...users] });
}, 1000);
return users[i]
}
}
return null
},
updatedList: {
subscribe: () => pubSub.asyncIterableIterator(['OPERATION_FINISHED'])
}
};
const app = express();
app.use('/helloGraph', graphqlHTTP({
schema,
rootValue: root,
graphiql: { subscriptionEndpoint: 'ws://localhost:4000/helloGraph' }
}));
const server = createServer(app);
const wsServer = new WebSocketServer({
server,
path: '/helloGraph',
});
useServer({ schema, roots: { subscription: root } }, wsServer);
server.listen(4000, () => console.log("Listening on port 4000 for GraphQL"))