그래프QL Yoga

공부의 기록·2021년 11월 12일
0

Node.JS

목록 보기
23/32
post-thumbnail

GraphQL

GraphQL 은 FACEBOOK이 2012 년에 개발하여 2015 년에 공개적으로 발표한 데이터 질의어이다. 이는 REST 및 부속 웹 서비스의 아키텍쳐를 대처할 수 있다.

설치 & 깃

npm install graphql-yoga

21-11-theory-graphql-backend

문제점

GraphQL 및 AXIOS 도 경우에 따라서 좋은 솔루션이 될수도 있다.
하지만, 일반적으로 Data Request를 하는 와중에 두 문제가 발생할 수 있다.

  1. Over-fetching : 불필요한 데이터까지 Request 되는 문제
  2. Under-fetching : 여러 번에 걸쳐서 Request 해야 하는 문제

over-fetching

쓸모 없는 정보도 받았다!

만약 당신이 간이 정보를 보여주는 페이지를 만든다고 하자.
수많은 유저 정보 중에서 필요한 것은 오직 유저이름과 나이이다.
하지만 express 나 Rest 에서는 불필요한 데이터까지 일괄적으로 Request, Response 하게 된다.

under-fetching

GET request 를 많이 해야한다.

만약 당신이 한 페이지에 다양한 종류의 Data가 필요하다고 하자.
유저정보, 유저가 보유한 여러 파일 정보들이 필요하다.
하지만 express 에서는 그 모든 사항에 대해서 각각 GET Request를 해야한다.

solution

원하는 데이터만 요청하고 한꺼번에 묶어서 요청하자.

참고 코드

  1. GraphQL Query
query:{
    feed {
        comments,
        likeNumber
    },
    notifications {
        isRead
    },
    user {
        username,
        profilePic
    },
}
  1. Vanilla JS
{
    feed: [
        {
            comments: 1,
            likeNumber: 20,
        },
    ],
    notifications:[
        {
            isRead: true,
        }
    ];
    user: {
        username: "Uncahptered",
        profile: "http:"
    }
}

파일 구조

GraphQL 은 다음과 같은 파일 구성을 가지고 있습니다.
1. ./index.js
2. ./graphql/schema.graphql
3. ./graphql/resolvers.js
4. ./graphql/functions.js

각 파일의 역할은 다음과 같습니다.
1. [index.js] : GraphQLServer 생성
2. [schema.graphql] : GraqhQL 의 Query & Mutation 선언
3. [resolvers.js] : GraphQL 과 Node.js 사이를 연결할 함수 선언
4. [functions.js] : 클라이언트 의 요구사항을 받아들일 함수 생성

index.js

import { GraphQLServer } from "graphql-yoga";
import resolvers from "./graphql/resolvers.js";

const server=new GraphQLServer({
  typeDefs: "graphql/schema.grapqh"m
  resolvers
});

server.start(()=>console.log("✅ index.js : GraphQL Server Running"));

schema.graphql

GraphQl 의 Schema 는 크게 세 가지 항목이 있습니다.
1. 개별 modelSchema : 일종의 컴포넌트 처럼 개별적인 대상에 대한 속성 선언
2. Query : 개별 혹은 집합 modelSchema 를 그대로 참조 선언하거나 arguments 등의 조건을 걸어서 참조 선언
3. Mutation : 개별 혹은 집합 data 의 추가 및 제거

type Movie {
  id: Int!
  name: String!
  score: Int!
}

type Query {
  movies: [Movie]!
  movie(id: Int!): Movie
}

type Mutation {
  addMovie(name: String!, score: Int!): Movie!
  deleteMovie(id: Int!): Boolean!
}

resolvers.js

Resvolvers 의 역할은 GraphQl 의 Schema 를 Node.js 가 이해할 수 있게 재정의하여 작성합니다.
resolvers 를 변수 선언해두고 그 안에 Query 및 Muation 항목들을 적어내려 가줍니다.
다음과 같이 적으면 됩니다. 괄호 안의 arguments 들은 후술하였습니다.

queryName: ()=> functionName(),
mutationName: ()=> functionName(),

import { getMovies, getById, addMovie, deleteMovie } from "./functions.js";

const resolvers = {
  Query: {
    movies: () => getMovies(),
    movie: (_, { id }) => getById(id),
  },
  Mutation: {
    addMovie: (_, { name, score }) => addMovie(name, score),
    deleteMovie: (_, { id }) => deleteMovie(id),
  },
};

export default resolvers;

functions.js

node-fetchaxios 등을 이용해서 받아온 데이터를 Query 양식에 맞게 변환하여 return 해줍니다.

export let movies = [
  {
    id: 0,
    name: "Star Wars - The new one",
    score: 1,
  },
  {
    id: 1,
    name: "Avengers - The new one",
    score: 8,
  },
  {
    id: 2,
    name: "The Godfather I",
    score: 99,
  },
  {
    id: 3,
    name: "Logan",
    score: 2,
  },
];

export const getMovies = () => movies;

export const getById = (id) => {
  const filteredMovies = movies.filter((movie) => movie.id === id);
  return filteredMovies[0];
};

export const deleteMovie = (id) => {
  const cleanedMoveis = movies.filter((movie) => movie.id !== id);
  if (movies.length > cleanedMoveis.length) {
    movies = cleanedMoveis;
    return true;
  } else {
    return false;
  }
};

export const addMovie = (name, score) => {
  const newMovie = {
    id: `${movies.length + 1}`,
    name,
    score,
  };
  movies.push(newMovie);
  return newMovie;
};
profile
2022년 12월 9일 부터 노션 페이지에서 작성을 이어가고 있습니다.

0개의 댓글