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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { setTimeout } from "node:timers/promises";
import { createPubSub, createSchema, createYoga } from "npm:graphql-yoga";
const pubSub = createPubSub();
const typeDefs = /* GraphQL */ `
type Query {
hello: String
now: String
}
type Subscription {
countdown(from: Int!): Int!
}
type Subscription {
randomNumber: Float!
}
type Mutation {
broadcastRandomNumber: Boolean
}
`;
const resolvers = {
Query: {
hello: () => "Hello, Val Town!",
now: () => new Date().toISOString(),
},
Subscription: {
countdown: {
// This will return the value on every 1 sec until it reaches 0
subscribe: async function*(_, { from }) {
for (let i = from; i >= 0; i--) {
await setTimeout(1000);
yield { countdown: i };
}
},
},
randomNumber: {
// subscribe to the randomNumber event
subscribe: () => pubSub.subscribe("randomNumber"),
resolve: payload => payload,
},
},
Mutation: {
broadcastRandomNumber: (_, args) => {
// publish a random number
pubSub.publish("randomNumber", Math.random());
},
},
};
const defaultQuery = `#
# Welcome to Yoga GraphiQL running on Val town
#
# Yoga GraphiQL is an in-browser tool for writing, validating, and
# testing GraphQL queries.
#
# Try a GraphQL query :
#
subscription {
countdown(from: 5)
}
#
# subscription {
# randomNumber
# }
#
# which listens for a number to be broadcast by
#
# mutation {
# broadcastRandomNumber
# }
#`;
// Create a Yoga GraphQL schema
const schema = createSchema({
typeDefs,
resolvers,
});
// Create a Yoga GraphQL server
const yoga = createYoga({
schema,
graphqlEndpoint: "/",
graphiql: {
title: "GraphQL Yoga Val with Subscriptions",
defaultQuery,
},
});
export default yoga.fetch;