Apollo GraphQL

박상욱·2022년 3월 29일
0

Apollo GraphQL

-GraphQL을 구현해 놓은 라이브러리
-서버 , 클라이언트 두가지 다를 제공하면서 인기가 많은 라이브러리

Apollo server 구현

프로젝트 생성 및 index.js 생성

  1. mkdir
  2. cd
  3. npm init --yes
  4. npm install apollo-server graphql
  5. root에 index.js 생성
  6. test를위해 apollo에서 제공하는 임시 데이터셋 및 query 복붙
const { ApolloServer, gql } = require("apollo-server");

// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
  #서버에 주입해주면서 뭔가 만들어진다.
  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

  # This "Book" type defines the queryable fields for every book in our data source.
  type Book {
    title: String
    author: String
  }

  # The "Query" type is special: it lists all of the available queries that
  # clients can execute, along with the return type for each. In this
  # case, the "books" query returns an array of zero or more Books (defined above).
  type Query {
    books: [Book] #books로 Book Array를 리턴
  }
`;

resolver

데이터 세트를 정의했지만 Apollo Server는 쿼리를 실행할 때 해당 데이터 세트를 사용해야 한다는 것을 알지 못합니다 .
이 문제를 해결하기 위해 resolver 를 만듭니다 .

index.js

const resolvers = {
  Query: {
    books: () => books,
    // 원래라면 여기가 데이터를 패칭해오고 응답을 내려주는 부분
  },
};

아폴로 서버 구현

index.js

//(스키마 내용, 쿼리가 왔을때 어떻게 데이터를 내려줄것인가)
const server = new ApolloServer({ typeDefs, resolvers });

// The `listen` method launches a web server.
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

실행 방법

node index.js

실행화면

nodemon

실행 후 books 데이터를 변경해도 바로 반영이 안된다.
바로 반영하기위한 모듈을 받아야함.
npm install nodemon
change를 인지해서 바로 반영을 해준다.

profile
개발자

0개의 댓글