GraphQL 기초

  1. GraphQL
    1. 특징
      1. Over-fetching
      2. Under-fetching
      3. Rest API와 차이
    2. API(Application Programming Interface)
    3. GraphQL 사용해 보기
    4. Apollo Server
      1. Type Definition
        1. Nullable & Non-Nullable
        2. Mutation
      2. resolver
      3. Documentation
      4. Migrating from REST to GraphQL

GraphQL


특징


Over-fetching

  • 필요한 데이터보다 많은 데이터를 fetch

Under-fetching

  • 필요한 데이터보다 적은 데이터를 fetch

Rest API와 차이


REST

  • 서버간 통신이나 어플리케이션이 서버와 통신할 때 URL로 이루어진다.

API(Application Programming Interface)


GraphQL 사용해 보기

GraphiQL 사용해 보기 // graphQL query를 사용할 수 있게 해주는 browser tool

image description


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로 바꿔준다.