자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[GraphQL] 4장 커스텀 타입 만들기

728x90

✅ 1. 폴더 구조

먼저 GraphQL 서버를 만들어 커스텀 타입을 만들기 위해 새로운 폴더를 만들어줍니다. GraphQL 스키마를 붙이기전 서버의 틀만 먼저 만든다고 가정해보겠습니다.

graphql-custom-type/
├── package.json
├── index.js        # 서버 메인 코드
└── node_modules/
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const { GraphQLSchema } = require("graphql");

const app = express();

const schema = new GraphQLSchema({});

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

app.listen(4000, () =>
  console.log("Server is running -> http://localhost:4000/graphql")
);

✅ 2. 커스텀 타입 정의하기

바로 밑부분에 GraphQLObjectType 으로 User라는 타입을 정의합니다, id, name, age 필드를 가지는 사용자 객체구조입니다.

const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt } = require("graphql");

const UserType = new GraphQLObjectType({
  name: "User", // 타입 이름
  description: "User Type", // 문서 설명
  fields: () => ({
    id: { type: GraphQLInt }, // 숫자형 id
    name: { type: GraphQLString }, // 문자열 name
    age: { type: GraphQLInt }, // 수자형 age
  }),
});

✅ 3. 샘플데이터 준비하기

이제 실제 DB에 연결하기 전, 배열로 가짜 데이터를 만들어줍니다.

const users = [
  { id: 1, name: "철수", age: 20 },
  { id: 2, name: "영희", age: 25 },
  { id: 3, name: "재훈", age: 29 },
];

✅ 4. RootQuery 정의

실제 쿼리를 작성할 수 있도록 Root Query를 만들어줍니다.

const { GraphQLList } = require("graphql");

const RootQuery = new GraphQLObjectType({
  name: "Query",
  fields: () => ({
    user: {
      type: UserType, // 반환 타입 = User
      args: { id: { type: GraphQLInt } }, // id 인자 필요
      resolve: (parent, args) => users.find((u) => u.id === args.id),
    },
    users: {
      type: new GraphQLList(UserType), // 반환 타입 = [User]
      resolve: () => users,
    },
  }),
});

✅ 5. 스키마 완성 & 서버 연결하기 

이제 Root Query를 스키마에 등록하고 서버에 붙입니다.

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

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

✅ 6. 최종 코드 

const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLInt,
  GraphQLList,
} = require("graphql");

const app = express();

// 커스텀 타입 정의
const UserType = new GraphQLObjectType({
  name: "User", // 타입 이름
  description: "User Type", // 문서 설명
  fields: () => ({
    id: { type: GraphQLInt }, // 숫자형 id
    name: { type: GraphQLString }, // 문자열 name
    age: { type: GraphQLInt }, // 수자형 age
  }),
});

// 샘플 데이터
const users = [
  { id: 1, name: "철수", age: 20 },
  { id: 2, name: "영희", age: 25 },
  { id: 3, name: "재훈", age: 29 },
];

// RootQuery 정의
const RootQuery = new GraphQLObjectType({
  name: "Query",
  fields: () => ({
    user: {
      type: UserType, // 반환 타입 = User
      args: { id: { type: GraphQLInt } }, // id 인자 필요
      resolve: (parent, args) => users.find((u) => u.id === args.id),
    },
    users: {
      type: new GraphQLList(UserType), // 반환 타입 = [User]
      resolve: () => users,
    },
  }),
});

// 스키마 완성 + 서버 연결
const schema = new GraphQLSchema({
  query: RootQuery,
});

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

// 서버 실행
app.listen(4000, () =>
  console.log("Server is running -> http://localhost:4000/graphql")
);

 

이제 node로 서버를 실행후 http://localhost:4000/graphql에 들어가 다음 명령어를 입력하고 재생버튼을 누르면

{
  users {
    id
    name 
    age
  }
}
{
  "data": {
    "users": [
      {
        "id": 1,
        "name": "철수",
        "age": 20
      },
      {
        "id": 2,
        "name": "영희",
        "age": 25
      },
      {
        "id": 3,
        "name": "재훈",
        "age": 29
      }
    ]
  }
}

 

이렇게 데이터가 잘 나오는 것을 볼 수 있습니다.


 

 

GitHub - Koras02/graphql-b

Contribute to Koras02/graphql-b development by creating an account on GitHub.

github.com

 

728x90
LIST