node.jstypescriptgraphql-yoga

How to check if graphql yoga server is running locally?


I have a pubsub service running with Redis and I need to check if GraphQL Yoga server is up and running locally before I start it.

What's the best way to do it in Node.js with TypeScript?

healthCheckEndpoint is set to 'live', port 4000


Solution

  • In order to ensure Redis doesn't connect until GraphQL is running, you can import the redis library asynchronously inside the server's success callback.

    index.js

    import { createServer } from "node:http";
    import { createYoga } from "graphql-yoga";
    import { schema } from "./schema.js";
    import redis from "./redis.js";
    
    // Create a Yoga instance with a GraphQL schema.
    const yoga = createYoga({ schema });
    
    // Pass it into a server to hook into request handlers.
    const server = createServer(yoga);
    
    // Start the server and you're done!
    server.listen(4000, async () => {
      console.info("GraphQL server is running on http://localhost:4000/graphql");
    
      await redis();
    
      return Promise.resolve();
    });
    

    redis.js

    import Redis from "ioredis";
    
    export default async () => {
      const redis = new Redis();
      return redis.set("mykey", "value");
    };