GraphQL 기초
GraphQL
- data를 요청한 것만 받을 수 있다. Graphql 설명서
특징
Over-fetching
- 필요한 데이터보다 많은 데이터를 fetch
Under-fetching
- 필요한 데이터보다 적은 데이터를 fetch
Rest API와 차이
REST
- 서버간 통신이나 어플리케이션이 서버와 통신할 때 URL로 이루어진다.
API(Application Programming Interface)
GraphQL 사용해 보기
GraphiQL 사용해 보기 // graphQL query를 사용할 수 있게 해주는 browser tool

Apollo Server
- node.js server와 같이 graphQL을 이해하는 서버
🔧 npm install apollo-server graphql
package.json 아래에 "type": "module" 추가
=> import문을 사용하기 위함
⚠️ graphql은 data의 shape을 미리 알고 있어야 한다.
⭐ user가 data를 받도록 하고 싶으면 Query type안에 있어야 한다.
Type Definition
Nullable & Non-Nullable
Mutation
- API와 소통하게 해주는 역할을 한다.
- Database에 영향을 준다.
resolver
- 필드를 실행 했을 때 실행되는 함수
⭐ user가 argument를 보낼 때 그 argument는 resolver function의 두번 째 argument가 된다.
const tweets = [
{
id: "1",
text: "hello",
}
];
const typeDefs = gql`
type Query {
allTweets: [Tweet!]!
tweet(id: ID!): Tweet
}
`;
const resolvers = {
Query: {
allTweets() {
return tweets;
},
tweet(root, args) {
console.log(args);
return null;
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
Documentation
- type, field 그리고 argument에 대한 설명을 제공한다.
ex. fullName에 대한 설명 “”” fullName => firstName + lastName “””
Migrating from REST to GraphQL
- REST API를 GraphQL API로 바꿔준다.