티스토리 뷰
GraphQL으로 간단한 project를 진행할 수 있는 기회가 생겨서 GraphQL을 조사하고 개발하되었다. 기존에는 REST API 형식으로 api를 구성했다. GraphQL을 사용하면서 느낀 것은 schema 변화에 많이 자유로워 질 수 있는 장점이 크다. REST API로 구성하게 되면 client에서 어떤 정보를 추가해달라는 요청이 들어오면 항상 코드 수정이 필요했다. 하지만 GraphQL은 client가 필요한 정보를 요청하여 받아올 수 있어 코드 수정이 줄어든다.
REST API는 URL, METHOD등을 조합하기 때문에 다양한 Endpoint가 존재 합니다. 반면, gql은 단 하나의 Endpoint가 존재 합니다. 또한, gql API에서는 불러오는 데이터의 종류를 쿼리 조합을 통해서 결정 합니다. 예를 들면, REST API에서는 각 Endpoint마다 데이터베이스 SQL 쿼리가 달라지는 반면, gql API는 gql 스키마의 타입마다 데이터베이스 SQL 쿼리가 달라집니다.
node.js로 GraphQL 서버를 만들 때 사용한 dependency는 아래와 같다.
- prisma
- apollo-server
- type-graphql
Prisma
prisma는 데이터베이스 도구 포함 ORM, 마이그레이션 및 관리자 UI, DB 프록시 서버 역할을 한다. 사용자는 GraphQL Schema만 정의하면 되고 DB는 설계할 필요가 없다. DB는 GraphQL 스키마를 기반으로 자동 생성된다. DB의 모든 Schema와 Table을 GraphQL로 관리할 수 있다.
기존의 ORM과 많은 차이가 있고 자동으로 schema를 정의하고 prisma client를 생성해준다. prisma client는 schema로 client에서 DB로 query할 때 사용하는 함수들을 자동으로 생성해주는 DB query library이다. 자동으로 생성되고 관리해주는 부분들이 많아 생산 속도에 장점을 가질 수 있다. prisma server는 DB server의 proxy 역할을 한다. DB connection 관리를 prisma server에서 하게되어 DB와의 종속성이 많이 떨어뜨릴 수 있는 장점이 있다.
apollo-server
apollo-server는 graphql server를 만드는 module이다. apollo server는 node.js에서 사용되는 많은 framework(express, koa, hapi....)를 지원한다. 또한 apollo-server-lambda도 있어 lamdba에 서버를 구축할 때 추가적인 구현이 필요 없다. apollo-server Standalone의 내부 구조를 보면 express를 내부적으로 사용하고 있고 apollo-server-express를 확장하여 사용하고 있다. express를 사용하는 분은 apollo-server-express를 사용하는 것이 더 적합하다는 생각이 든다.
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Recipe {
id: ID!
title: String!
}
`;
const recipeData = [
{
id: 1,
title: 'title1',
},
{
id: 2,
title: 'title2',
},
];
const resolvers = {
Query: {
recipes: () => recipeData,
},
};
const server = new ApolloServer({ typeDefs, resolvers });
type-graphql
graphQL server에서 gql는 쿼리 언어를 사용한다. apollo-server를 사용하게 된면 gql언어로 query를 해야한다. apollo-server code 예시에서 보면 해독하기 어려운 코드가 된다. type-graphql는 class와 decorators를 사용하여 GraphQL의 schema와 resolver를 만들 수 있다.
@ObjectType()
class Recipe {
@Field(type => ID)
id: string;
@Field()
title: string;
}
@Resolver(Recipe)
class RecipeResolver {
constructor() {}
@Query(returns => [Recipe])
recipes() {
return recipeData;
}
}
위의 코드를 class와 decorators를 사용하여 type-graphql로 변환한 것이다. type-graphql로 변환하면 typescript에 친화적인 코드로 변환할 수 있고 lint나 type check하기가 쉬워진다.
import { buildSchema, buildTypeDefsAndResolvers } from 'type-graphql';
import * as resolver from '../resolvers';
export const createSchema = async () =>
await buildSchema({
resolvers: Object.keys(resolver).map((key) => resolver[key]),
emitSchemaFile: {
path: __dirname + '/schema.gql',
commentDescriptions: true,
},
});
type-graphql로 선언한 class는 ApolloServer에 넣기 전에 ApolloServer에서 인식할 수 있는 gql 언어로 변환해서 넣어주어야 한다. 위의 createSchema를 호출하면 schema.gql 파일이 성생된다.
'develop' 카테고리의 다른 글
MongoDB Slow operation을 확인하는 방법 (1) | 2020.04.02 |
---|---|
Error 객체 JSON.stringify() (0) | 2020.03.20 |
3. Test code 작성 + DI (0) | 2020.03.03 |
2. inversify factory (0) | 2020.02.19 |
1. inversify 시작하기 (0) | 2020.02.04 |
- Total
- Today
- Yesterday
- Python
- mognodb
- shorten
- Terraform
- Prisma
- mongoDB
- Neptune
- conventional commit
- typescript
- Cloudfront
- AWS community day seoul
- Github Actions
- pagination
- graphql
- JavaScript
- lambda@edge
- slowquery
- commit message
- Elasticsearch
- Cognito
- Lifecycle
- inversify
- aws
- sementic version
- Clickjacking
- nginx
- NLP
- Airflow
- Develop
- nltk
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |