ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • GraphQL (1) - schema, query, response
    인턴 2024. 1. 19. 13:35

    schema

    type User{
    	id: ID! //필수값
        name: String! //필수값
    }
    
    type Query{
    	user(id: ID!): User!
    }

     

    query

    query{
    	user(id: "10"){ // id 값이 10인 user 목록 조회
        	id
            name
            // id와 name이 반환됨
         }
    }

     

     

    response

    {
    	"data": {
        	"user": {
            	"id": "10",
                "name": "Simon"
            }
        }
    }

     

     

     

    GraphQL.js로 GraphQL의 스키마 정의하기

    import { GraphQLObjectType, GraphQLSchema, GraphQLString, printSchema } from 'graphql';
    
    const schema = new GraphQLSchema({
      query: new GraphQLObjectType({
        name: 'RootQueryType',
        fields: {
          hello: {
            type: GraphQLString,
          },
        },
      }),
    });
    
    console.log(printSchema(schema));
    
    -------------------------------------------------------------------------
    출력하면 다음과 같은 스키마가 정의됨
    
    schema {
      query: RootQueryType
    }
    
    type RootQueryType {
      hello: String
    }

     

    커스텀 추가 가능

    import { GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema, GraphQLString, printSchema } from 'graphql';
    
    const User = new GraphQLObjectType({
      name: 'User',
      fields: {
        name: {
          type: new GraphQLNonNull(GraphQLString),
        },
      },
    });
    
    const schema = new GraphQLSchema({
      query: new GraphQLObjectType({
        name: 'Query',
        fields: {
          users: {
            type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(User))),
            resolve: () => [{ name : 'Johnny' }],
          },
        },
      }),
    });
    
    (async () => {
      const result = await graphql({ schema, source: 'query { users { name } }' });
      console.log(JSON.stringify(result, null, 2));
    })();
    
    ------------------------------------------------------------------------------
    # 출력하면 다음과 같은 스키마 정의됨
    
    type Query {
      users: [User!]!
    }
    
    type User {
      name: String!
    }
    
    ------------------------------------------------------------------------------
    # Query
    
    query{
    	user{
        	name
        }
    }
    
    ------------------------------------------------------------------------------
    # Response
    
    {
      "data": {
        "users": [
          {
            "name": "Johnny"
          }
        ]
      }
    }

     

     

     

    클라이언트에 API 전송하기

    GraphQL.js는 한 프로세스 안에서 질의만 처리하고, 서버-클라이언트 구조에 대해서 해주는 것은 아무 것도 없다.

    API를 클라이언트에 전송하려면 별도의 라이브러리가 필요하다.

    express-graphql 이나 Apollo Server를 통해 보통 사용되는 HTTP 프로토콜을 통한 GraphQL API 서빙이 가능하다.

     

    import express from 'express';
    import { graphqlHTTP } from 'express-graphql';
    
    const app = express();
    app.use('/graphql', graphqlHTTP({ schema }));
    app.listen(4567);

     

    '인턴' 카테고리의 다른 글

    OpenAI Assistants API v2 stream 오브젝트의 in/outbound  (0) 2024.06.03
    GraphQL 알아보기  (0) 2024.01.18
    OpenAI Assistant Tools  (1) 2023.12.28
    OpenAI Assistant 작동 방식  (0) 2023.12.28
Designed by Tistory.