GraphQL server 만들기

Jiwontwopunch·2022년 6월 16일
0

독학

목록 보기
84/102
post-thumbnail

REST API와 GraphQL

// 메소드와 url 형태로 서버의 데이터를 조회, 생성, 수정, 삭제

// 책 목록보기
// get 메소드와 url 형태로 서버의 데이터를 조회
// get 메소드와 /book
axios.get(
	'https://api.handtube.tv/v1/book',
    {headers: `Bearer ${token}` },
);

// 책 추가하기
// post 요청과 /book 리소스가 새로 생성
axios.post(
	'https://api.handtube.tv/v1/book',
    {
    title,
    message,
    author,
    url,
    },
);

// 책 상세보기
// get 메소드와 ${book:id} 고유한 값으로 해당 리소스를 조회
axios.get(
	`https://api.handtube.tv/v1/book/${book:id}`,
    {headers: `Bearer ${token}` },
);

// 책 수정하기
axios.patch(
	`https://api.handtube.tv/v1/${book:id}`,
    {
    title,
    message,
    author,
    url,
    },
);

// 책 삭제하기
axios.delete(
	`https://api.handtube.tv/v1/book/${book:id}`,
    {headers: `Bearer ${token}` },
);

REST API의 단점과 GraphQL의 등장

요청이 항상 메소드와 url의 조합, 결과물을 완전히 유도할 수 없다.
그래서 등장한 것이 GraphQL.
GraphQL은 쿼리를 보내 원하는 데이터만 보낸다.
javascript -Apollo server 사용

Apollo를 이용해서 Node.js server 만들기

// $ mkdir graphql-server
// $ cd graphql-server
// $ npm init -y
// $ npm i graphql
// $ npm i apollo-server
// $ npm i nodemon -D
// $ code .
// index.js 파일 생성 → github에 있는 아폴로 시작 코드 복붙
// ApolloServer는 GraphQL 서버 인스턴스를 만들어주는 생성자
// gql은 자바스크립트로 GraphQL 스키마를 정의하기 위해 사용되는 템플릿 리터럴 태그
const { ApolloServer, gql } = require('apollo-server');

// The GraphQL schema
// typeDef(s) 변수에 gql을 이용하여 GraphQL 스키마 타입을 정의
const typeDefs = gql`
  type Query {
    "A simple type for getting started!"
    hello: String
  }
`;

// A map of functions which return data for the schema.
// resolver(s) 스키마에 해당하는 구현을 하는 곳
// 요청을 받아 데이털르 조회, 수정, 삭제
const resolvers = {
  Query: {
    hello: () => 'world',
  },
};

// typeDefs와 resolvers를 ApolloServer 생성자에 넘겨 
// GraphQL 서버 인스턴스를 생성하고 그 서버를 시작해주는 코드
const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

// package.json
  "scripts": {
    // test 제거 
    "dev": "nodemon index.js"
  },

$ npm run dev

0개의 댓글