본문 바로가기

공부일지/React

비전공자의 공부일지 - GraphQL 두번째 이야기

728x90
반응형

GraphQL 두번째이야기

 

저번 일지에 이어서 이번에도 GraphQL을 공부할 것이다.

 

저번에 작성했던 server.js에서 이번에는 Query에 다른 코드들을 작성해 볼 예정이다.

 

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const {buildSchema} = require('graphql')
const app = express();
const port = 4000;

const schema = buildSchema(`
    type Query{
        posts:[Post],
        comments: [Comment],
    }
    type Post{
        id: ID!,
        title: String!,
        description: String!,
        comments: [Comment]
    }

    type Comment{
        id: ID!,
        text:String!,
        likes:Int
    }
`);

const root = {
    posts:[
        {
            id: 'post1',
            title:'It is a first post',
            description:'It is a first post description',
            comments:[{
                id:'comment1',
                text:'It is a first comment',
                likes: 1
            }]
        },
        {
            id: 'post2',
            title:'It is a second post',
            description:'It is a second post description',
            comments:[]
        }
    ],
    comments: [
        {
            id:'comment1',
            text:'It is a first comment',
            likes:1
        }
    ]
}

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

app.listen(port,() => {
    console.log(`Running a GraphQL API server at http://localhost:${port}/graphql`);
});

저번 일지와 다르게 이번엔 Query에 posts와 comments를 작성하고 바로 밑에 Post와 Comment를 참조 할 수 있게 작성 해 주었다.

이번에 id:ID! 가 있는데 일단 먼저 GraphQL은 id값을 사용해 캐싱을 해준다고 한다.

그리고 !는 무조건 해당 키에 무조건 값이 들어가 있어야 한다고 한다. 쉽게 생각해서 필수 값이라고 생각하면 될거 같다.

comment도 지금은 그냥 하드코딩으로 다 적었지만 저런식으로 데이터를 받아와서 출력시켜준다 보여주기 위해 다 적어서 출력 시켰다.

 

GraphQL Tools


api를 불러올때 server.js에서 처럼 한곳에서 다 불러오게 되면 해당 페이지에서 소스를 찾기가 힘들고 유지보수 하기도 힘들기 때문에 그때 사용하는게 graphtools이다.

 

graphtools을 사용한 코드는 어떤지 한번 확인해보자

const { loadFilesSync } = require('@graphql-tools/load-files');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const {buildSchema} = require('graphql')
const app = express();
const port = 4000;

const loadedFiles = loadFilesSync("**/*",{
    extensions:['graphql']
})

const schema = makeExecutableSchema({
    typeDefs: loadedFiles
})

const root = {
    posts : require('./posts/posts.model'),
    comments: require('./comments/comments.model')
}

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

app.listen(port,() => {
    console.log(`Running a GraphQL API server at http://localhost:${port}/graphql`);
});

 

소스를 조금 보자면

const loadedFiles = loadFilesSync("**/*",{
    extensions:['graphql']
})

const schema = makeExecutableSchema({
    typeDefs: loadedFiles
})

 

loadFileSync : 현재폴더(__dirname)에 있는 폴더들 이다.

** : 위의 폴더들을 모두 포함한다는 명령어이다.

* : extenstions 의 값에 적힌 값을 모두 찾는다.

extenstions : 찾으려는 확장자를 뜻한다. 여기서 graphqls라고 하고 확장자들도 전부 graphqls라고 해도 잘 동작한다.

 

 

comments, posts폴더를 만든후 posts.graphql, posts.model.js 와 comments.graphql, comments.model.js 를 만들어 graphql에는 schema에 작성했던 코드를 model에는 root에 작성했던 코드를 작성하면 된다.

model에는 module.exports를 해서 작성해 주어야 한다.

 

server.js의 root에 posts, comments를 각각 require를 해서 가져온다.

 

그러면 위에 작성했던 코드들처럼 잘 동작한다.

프로젝트의 규모가 커지면 저렇게 파트별로 나누어서 작성하고 관리하면 될거 같다.

 

728x90
반응형