-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
51 lines (44 loc) · 1.06 KB
/
server.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
/* eslint-disable no-console */
const { GraphQLServer, PubSub } = require("graphql-yoga")
const typeDefs = `
type Query {
hello: String!
}
type Sensor {
time: Int!
temp: Float!
humidity: Float!
}
type Subscription {
sensor: Sensor!
}
`
const resolvers = {
Query: {
hello: () => `Hello`,
},
Subscription: {
sensor: {
subscribe: (parent, args, { pubsub }) => {
const channel = Math.random()
.toString(36)
.substring(7)
setInterval(
() =>
pubsub.publish(channel, {
sensor: {
time: Math.round(Date.now() / 1000),
temp: +(10 + Math.random() * 10).toFixed(1),
humidity: +(80 + Math.random() * 10).toFixed(1),
},
}),
1000
)
return pubsub.asyncIterator(channel)
},
},
},
}
const pubsub = new PubSub()
const server = new GraphQLServer({ typeDefs, resolvers, context: { pubsub } })
server.start(() => console.log("Server is running on localhost:4000"))