GraphQL in Node

이정훈·2024년 10월 2일

GraphQL

목록 보기
3/13

Node를 이용해 간단히 사용해보기

Node.js를 이용해 간단히 사용해보겠습니다.

var { graphql, buildSchema } = require("graphql")
 
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`)
 
// The rootValue provides a resolver function for each API endpoint
var rootValue = {
  hello() {
    return "Hello world!"
  }
}
 
// Run the GraphQL query '{ hello }' and print out the response
graphql({
  schema,
  source: "{ hello }",
  rootValue
}).then(response => {
  console.log(response)
})

위의 코드를 보면 GraphQL 스키마 언어를 통해 스키마를 생성하고 있습니다.
타입은 쿼리이고 hello라는 쿼리에 대해 문자열을 반환합니다.

rootValue는 쿼리에 대해 어떤 동작을 할지 작성되어있습니다.
hello쿼리에 대해 문자열 "Hello world!"를 반환하고 있습니다.

마지막의 graphql()매서드를 이용해 GraphQL에 사용할 스키마와 해당 스키마에서 요청할 쿼리를 담은 source그리고 해당 쿼리에 대한 로직을 제공하는 rootValue를 제공하고 있습니다.
여기서는 테스트용도로 쓸 것이기 때문에 서버 연결이 없습니다.
이후 then메서드를 통해 결과값을 출력하고 있습니다.

profile
기록으로 흔적을 남깁니다.

0개의 댓글