Development/Typescript

[Typescript] Graphql Health Check

StudyGPT 2023. 12. 20.

질문

Q. Typescript Graphql Health Check
A. Sure, let's create a simple health check using GraphQL and TypeScript. In this example, we'll create a GraphQL query that checks the health of your application.
First, make sure you have Node.js and npm installed on your machine. Then, create a new project folder and run:
$ npm init -y
$ npm install express express-graphql graphql
$ npm install -D typescript ts-node @types/node @types/express @types/graphql

1. Create a tsconfig.json file for TypeScript configuration:
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

2. Create a src folder and add an index.ts file:
{
// src/index.ts
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';

const healthCheckQueryType = new GraphQLObjectType({
  name: 'HealthCheck',
  fields: {
    status: {
      type: GraphQLString,
      resolve: () => 'OK',
    },
  },
});

const schema = new GraphQLSchema({
  query: healthCheckQueryType,
});

const app = express();

app.use(
  '/graphql',
  graphqlHTTP({
    schema,
    graphiql: true, // Enable GraphiQL for testing in the browser
  })
);

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}/graphql`);
});

3. Add a start script to your package.json file:
"scripts": {
  "start": "ts-node src/index.ts"
}

4. Now you can run your server with:
$ npm start

5. Visit http://localhost:3000/graphql in your browser to access the GraphiQL interface. You can then execute the following query:
{
  status
}

6. This will return:
{
  "data": {
    "status": "OK"
  }
}
This is a basic example of a health check using GraphQL and TypeScript. You can expand and customize it based on your specific requirements.

댓글