import { setTimeout } from "node:timers/promises";
import { createPubSub, createSchema, createYoga } from "npm:graphql-yoga";
const pubSub = createPubSub();
const typeDefs = `
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: {
subscribe: async function*(_, { from }) {
for (let i = from; i >= 0; i--) {
await setTimeout(1000);
yield { countdown: i };
}
},
},
randomNumber: {
subscribe: () => pubSub.subscribe("randomNumber"),
resolve: payload => payload,
},
},
Mutation: {
broadcastRandomNumber: (_, args) => {
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
# }
#`;
const schema = createSchema({
typeDefs,
resolvers,
});
const yoga = createYoga({
schema,
graphqlEndpoint: "/",
graphiql: {
title: "GraphQL Yoga Val with Subscriptions",
defaultQuery,
},
});
export default yoga.fetch;