분류 Nodejs

Node.js와 Express로 GraphQL 서버를 만드는 법

컨텐츠 정보

  • 조회 299 (작성일 )

본문

Node.js 및 Express Powered GraphQL 서버를 생성하는 방법에 대한 간단한 자습서


새 Node.js 프로젝트를 아직 만들지 않은 경우 먼저 만듭니다.


npm init --y


이 명령은 npm으로 작업해야 하는 package.json 파일을 만듭니다.


npm 패키지 express, graphql 및 express-graphql을 설치하십시오.


npm install express graphql express-graphql


app.js 파일을 작성하고 Express 서버를 초기화하는 것으로 시작합시다.


const express = require('express')

const app = express()

app.listen(3000, () => {
  console.log('App listening on port 3000')
})


이제 express-graphql을 추가합니다. 이것은 미들웨어이며, /graphql 라우트에만 적용합니다.


const express = require('express')
const graphqlHTTP = require('express-graphql')

const app = express()

app.use('/graphql', graphqlHTTP())

app.listen(3000, () => {
  console.log('App listening on port 3000')
})


스키마 정의를 포함해야 하는 schema 속성을 포함하는 객체를 전달해야 합니다.


먼저 스키마를 정의해야 합니다!


schema.js 파일을 만들고 거기에 먼저 graphql이 필요하다. 그리고 나서 객체 파괴 구문을 사용하여 곧 사용할 GraphQLSchema, GraphQLObjectType 및 GraphQLString 객체를 얻는다.


const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = graphql


그런 다음 새 GraphQLSchema 인스턴스를 초기화하고 쿼리 속성이 포함 된 개체를 전달하여 스키마 값을 정의합니다. 이 속성은 GraphQLObjectType 객체의 인스턴스입니다.


const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
		//...
  })
})

module.exports = schema


이 새 객체 안에는 이름과 필드 매개 변수를 지정해야 합니다. 이 마지막 속성은 스키마 집합의 각 필드에 대해 하나씩 속성 집합을 포함하는 개체입니다. 이 예제에서는 hello 필드를 설정합니다.


const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'world'
        }
      }
    }
  })
})


resolve() 메서드는 world라는 문자열을 반환합니다. 즉, hello 필드를 요청할 때 해당 문자열을 반환합니다.


다음은 전체 schema.js 파일 내용입니다.


const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = graphql

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'world'
        }
      }
    }
  })
})

module.exports = schema


이제 app.js 파일로 돌아가 보겠습니다.


이것이 우리가 가진 것입니다 :


const express = require('express')
const graphqlHTTP = require('express-graphql')

const app = express()

app.use('/graphql', graphqlHTTP())

app.listen(3000, () => {
  console.log('App listening on port 3000')
})


이제 schema.js 파일이 필요합니다.


const schema = require('./schema.js')


이를 graphqlHTTP() 생성자에 전달하는 객체에 추가합니다.


app.use('/graphql', graphqlHTTP({
  schema: schema
}))


이제 이것을 테스트하여 작동하는지 확인할 수 있습니다. Google의 GraphQL API를 테스트하는 훌륭한 도구 인 GraphiQL을 사용할 수 있습니다.


이미 설치되어 있고 이를 가능하게 하려면 graphqlHTTP 생성자에 다른 속성을 전달해야 합니다.


app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


이제 노드 app.js를 실행 한 후 브라우저에서 http : // localhost : 3000 / graphql URL에 액세스하면 GraphiQL이 실제로 작동합니다.


a95d85232d0d3ae25e8b8d0c2ea0740e_1563408941_8395.png
그리고 다음 쿼리를 전달하여 첫 번째 API 호출을 테스트 할 수 있습니다.


{
	hello
}


결과는 다음과 같습니다.


a95d85232d0d3ae25e8b8d0c2ea0740e_1563408998_622.png
이제 더 복잡한 스키마를 작성해 보겠습니다.


하나는 중첩 된 유형이 있습니다.


내가 생각한 예는 블로그 게시물입니다.


블로그 게시물에는 제목과 설명이 있으며 저자도 있습니다. 저자의 이름이 있습니다.


이것을 알아 봅시다.


먼저 게시물과 작성자를 추가합니다.


const posts = [
  {
    title: 'First post',
    description: 'Content of the first post',
    author: 'Flavio'
  },
  {
    title: 'Second post',
    description: 'Content of the second post',
    author: 'Roger'
  }
]

const authors = {
  'Flavio': {
    name: 'Flavio',
    age: 36
  },
  'Roger': {
    name: 'Roger',
    age: 7
  }
}


이것이 우리가 데이터를 얻을 수 있는 곳입니다.


다음으로, 3 개의 GraphQLObjectType 인스턴스를 정의합니다.


  • authorType : 작성자 데이터를 정의합니다.
  • postType : 게시물 데이터를 정의합니다.
  • queryType, 주요한 것

저자와 함께 시작하겠습니다. 저자는 이름과 나이를 가지고 있습니다.


우리는 GraphQLInt 타입을 사용하는데, 우리는 이것을 require에 추가해야 합니다 :


const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt } = graphql

//...

const authorType =  new GraphQLObjectType({
  name: 'Author',
  fields: {
    name: {
      type: GraphQLString
    },
    age: {
      type: GraphQLInt
    }
  }
})


다음은 postType입니다. 게시물에는 제목, 설명 (문자열 모두) 및 작성자가 있습니다. 작성자는 우리가 방금 정의한 authorType 유형이며 해결자를 가지고 있습니다.


게시물 매개 변수 인 source 매개 변수에서 게시자 이름을 가져오고 이를 기반으로 작성자 데이터를 조회합니다. 우리는 그것을 돌려 보냅니다.


const postType =  new GraphQLObjectType({
  name: 'Post',
  fields: {
    title: {
      type: GraphQLString
    },
    description: {
      type: GraphQLString
    },
    author: {
      type: authorType,
      resolve: (source, params) => {
        return authors[source.author]
      }
    }
  }
})


resolver 함수는 비동기적일 수 있으므로 async/await를 사용하여 데이터베이스 또는 네트워크의 자원을 조회 할 수 있습니다. 


다음은 스키마에 추가 할 루트 유형 인 queryType입니다. 거기에 2 개의 필드를 정의합니다.


  • ID로 식별되는 단일 블로그 게시물 게시
  • 게시물 목록을 게시합니다.

둘 다 posts 배열에서 데이터를 조회하는 resolver 함수를 가지고 있습니다.


const queryType =  new GraphQLObjectType({
  name: 'Query',
  fields: {
    post: {
      type: postType,
      args: {
        id: { type: GraphQLInt }
      },
      resolve: (source, {id}) => {
        return posts[id]
      }
    },
    posts: {
      type: new GraphQLList(postType),
      resolve: () => {
        return posts
      }
    }
  }
})


새로운 GraphQLList 유형을 주목하십시오.이 유형은 postType을 포장하여 postType 객체의 목록임을 의미합니다. 그것을 꼭 필요로 합니다.


const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLInt } = graphql


스키마에 추가해야 하며 다음과 같이 설정됩니다.


const schema = new GraphQLSchema({
  query: queryType
})


전체 코드는 다음과 같습니다.


const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLInt } = graphql

const posts = [
  {
    title: 'First post',
    description: 'Content of the first post',
    author: 'Flavio'
  },
  {
    title: 'Second post',
    description: 'Content of the second post',
    author: 'Roger'
  }
]

const authors = {
  'Flavio': {
    name: 'Flavio',
    age: 36
  },
  'Roger': {
    name: 'Roger',
    age: 7
  }
}


const authorType =  new GraphQLObjectType({
  name: