ExpressでGraphQLサーバー実装の最小構成

Main File

import express from 'express'
import expressGraphql from 'express-graphql'
import { GraphQLObjectType, GraphQLSchema } from 'graphql'
import bodyParser from 'body-parser'
import cors from 'cors'
import PostQuery from './queries/PostQuery'

const app = express()

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQuery',
    fields: () => ({
      post: PostQuery
    })
  })
})

app.use('/graphql', cors(), bodyParser.json(), expressGraphql({
  schema,
  graphiql: true
}))

Type File

import { GraphQLID, GraphQLString, GraphQLObjectType } from 'graphql'

export default new GraphQLObjectType({
  name: 'Post',
  fields: () => ({
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    body: { type: GraphQLString }
  })
})

Query file

import { GraphQLID } from 'graphql'
import PostType from '../types/PostType'

export default {
  type: PostType,
  args: {
    id: { type: GraphQLID }
  },
  resolve: async (_parent: any, args: any, _context: any) => {
    return // JSONを返す
  }
}

実装時の注意点

fieldsはオブジェクトではなく関数にしておく(下記参照リンク)

ExpressのGraphQLで相互のRelation関係にあるTypeをimportする方法