Express API 서버에 GraphQL 끼얹기 2편 - GraphQLSchema 직접 만들어보기

이진선·2019년 12월 2일
0

{ 2. GraphQLSchema 직접 만들어보기 }

첫 스키마를 작성해 볼때 다른 부가적인 라이브러리 사용없이 순수 GraphQL 라이브러리만 이용하여 GraphQLSchema를 직접 구현해 보려고 시도했다.

Node.js 에서 Express를 사용하여 서버를 개발중이고
Sequelize 로 PostgresSQL DB 모델을 정의하여 사용중이다.

순수 GraphQL을 이용할 경우
코드는 아래와 같다

user 정보를 담고있는 DB를 GraphQL로 요청할 수 있도록 작성해보자.

user.js

const Graphql = require('graphql');
const models = require('../src/database/models');
const userType = new Graphql.GraphQLObjectType({
    name: 'user',
    fields: {
        id: {type: Graphql.GraphQLInt},
        user_name: {type: Graphql.GraphQLString},
    },
});
const queryType = new Graphql.GraphQLObjectType({
    name: 'RootQuery',
    fields: {
        user: {
            type: new Graphql.GraphQLList(userType),
            args: {
                id: {type: Graphql.GraphQLInt},
            },
            resolve: async function(_, {id}) {// 실제로 쿼리 될때 호출되는 메소드
                const users = await models.user.findAndCountAll();
                (users.rows).filter((element) => {
                    if (element.id == id) {
                        return element;
                    }
                });
                return users.rows;
            },
        },
        alluser: {
            type: new Graphql.GraphQLList(userType),
            resolve: async function() {
                const users = await models.user.findAndCountAll();
                return users.rows;
            },
        },
    },
});
module.exports = new Graphql.GraphQLSchema({query: queryType});

app.js

~~~
const myGQLschema = require('./mygql/user.js');
app.use(
    '/gql',
    graphqlHTTP({
        schema: myGQLschema,
        graphiql: true,
    }),
);
~~~

복잡한 코드에 비해 원리는 간단하다.
GraphQLObjectType은 name 과 fields 두개의 키를 가지는데
type 객체는 fields에 key:value 형식으로 column:type 을 추가해주면 되고, (ex| id : int)
query 객체는 fields에 func : { type, args, resolve } 에 각각 value 값을 추가해주면 된다.
여기서
type : 이 함수의 return type,
args : 받을 인자,
resolve : 함수의 실제 내용물을 담아주면 된다.

다만 실제 우리는 user 테이블만 존재하는게 아니므로,
이 기본 코드를 모듈화하여 사용하여야한다.

문제는, 기본 코드가 다소 복잡하고 GraphQLInt 같은 type이 직관적이지 않은점이 불편하다.

또한 모듈화를 다소 진행해 보았는데, 꽤나 마음먹은대로 조작이 되지 않아서 다른 방법을 검색해 보았다.

13-graphql-tools-and-libraries-you-should-know

그러던 중 GraphQL-tools
이라는 꽤나 타입스크립트 같은 라이브러리를 찾아서 이용해보려고 한다.

실제 Typescirpt 와 GraphQL 을 접목시킨 라이브러리는 TypeGrpahQL 이라고 따로 존재하지만, 이 문법이 개인적으로 아직은 마음에 들지 않아서 tools 만 이용해서 스키마를 만들어보았다.

1개의 댓글

comment-user-thumbnail
2020년 9월 17일

감사합니다. ^^

답글 달기