본문 바로가기
개발/GraphQL , Apollo

GraphQL로 restAPI 사용하기

by 안뇽! 2022. 1. 23.
반응형

기존 RestAPI를 GraphQL로 감싸주었다.

 

db.js에서는 url을 fetch한 리턴값을 getMovies에 할당했다.

//db.js

import fetch from "node-fetch";

const API_URL = "https://yts.am/api/v2/list_movies.json?";

export const getMovies = (limit, rating) => {
  let REQUEST_URL = API_URL;
  if (limit > 0) {
    REQUEST_URL += `limit=${limit}`;
  }
  if (rating > 0) {
    REQUEST_URL += `&minimum_rating=${rating}`;
  }
  return fetch(`${REQUEST_URL}`)
    .then((res) => res.json())
    .then((json) => json.data.movies);
};

index.js에서 db.js의 getMovies 를 쿼리에 할당한다.

//index.js

import { GraphQLServer } from "graphql-yoga";
import { getMovies } from "./db/db";

const resolvers = {
  Query: {
    movies: (_, { rating, limit }) => getMovies(limit, rating),
  },
};

const server = new GraphQLServer({
  //typeDefs : 모든 타입들에 대한 정의
  typeDefs: "./graphql/schema.graphql",

  resolvers,
});

server.start(() => console.log("GraphQL Server Running"));

스키마는 다음과 같이 작성했다.

//schema.graphql

type Movie {
  limit: Int!
  title: String!
  rating: Float!
  summary: String!
  language: String!
  medium_cove_image: String!
}

type Query {
  movies(limit: Int, rating: Float): [Movie]!
}

 

1. db에서 restAPI를 이용하여 fetch한 리턴값을 임의의 변수 getMovies에 익명함수로 지정하고,

2. index.js에서 getMovies를 쿼리로 이용하였다.

 

아래 사진은 graphQL yoga를 이용하여 리턴값을 확인한 사진이다.

파라미터에 따라 평점 8.5이상인 영화 4개를 리턴한다.

반응형

'개발 > GraphQL , Apollo' 카테고리의 다른 글

Express, graphql로 서버생성  (0) 2022.02.27
Apollo 를 이용한 상태관리  (0) 2022.02.12
Apollo 공식문서 첫부분  (0) 2022.01.22
Apollo Client  (0) 2022.01.21
GraphQL Mutation은 CRUD중 CUD이다.  (0) 2022.01.21