관리 메뉴

Silver Library (Archived)

GraphQL (GQL) 에 대한 기록. 본문

Fundamental of CS/Knowledge

GraphQL (GQL) 에 대한 기록.

Chesed Kim 2022. 11. 21. 20:17
반응형

tl;dr

typeDef, resolvers = schema & mutation, queries (as a notion)

 

 

GraphQL schema basics

Your GraphQL server uses a schema to describe the shape of your available data. This schema defines a hierarchy of types with fields that are populated from your back-end data stores. The schema also specifies exactly which queries and mutations are availa

www.apollographql.com


우선, GraphQL 에서 data 를 request, write, post 하는 방법은?

우선 GraphQL 의 핵심은: mutation 이냐, query 이냐 라고 합니다.

 

GET 이 Query 라면, PUT, DELETE, POST 는 Mutation 에 해당되는 의미죠.

또한, GraphQL 은 DB가 아닙니다.

 

GraphQL API (GQL) vs REST API (REST)

GQL 은 Endpoint 가 오직 하나.

/user -> /graphql
/episode -> /graphql
/title -> /graphql

 Overfetching 과, Underfetching 이란 개념이 있다는 걸 참고.

 

참고용:

{
	"anime": [
    	{
            "id": 0,
            "title": "whatever anime",
            "episode": "#"
        },
	]
}
 

What is Over-Fetching or Under-fetching?

I've been playing sometimes with graphQL. Before graphQL, we normally use REST API. Many developers said that graphQL fixes some problems of the REST. (e.g. over-fetching & under-fetching). I

stackoverflow.com

그리고 하다보면 ! 가 보입니다. JS의 그것과 같다고 봅니다.

JS 에서 !true == false

였다면, 곧 부정을 의미하는 용도로 쓰이듯이:

GraphQL 에서는 ! 라는 존재 자체가 '아니면 하지마' 용도로 쓰입니다.

 

즉, name: String! 이라면 String 이다 라고 type 을 지정해줄때 쓰입니다.

하다보면 타입스크립트와 궁합이 잘 맞을 것 같은 느낌이 듭니다. 

예시)

const Def = gql`
  type User {
    name: String!
    username: String!
    age: Int!
    nationality: String!
  }

이 용도의 공식 설명은:

 

Schemas and Types | GraphQL

Schemas and Types On this page, you'll learn all you need to know about the GraphQL type system and how it describes what data can be queried. Since GraphQL can be used with any backend framework or programming language, we'll stay away from implementation

graphql.org

(아래 글은 개요 파악 정도로 보는걸 권장합니다.)

 

GraphQL for Front End Developers

If you are a front end developer who is new to the world of GraphQL and you're thinking about getting started with it, this article is for you. In this article, we will explore GraphQL basics and kick start our journey with it by building a simple project.

www.freecodecamp.org

권장되는 준비물:

apollo-server, graphql

적어도 저는 이 두가지를 자주 사용하게 되었습니다.

그리고 nodemon 은 취향껏. 하다보니 lodash 라는 라이브러리도 쓰게 되었습니다.

다만 필자의 경우 복잡하게 쓰지 않고 특정 배열 부분에 한해서 find method 에 한해서 사용 해 볼 수 있었습니다.


find()
형식: .find(collection, [predicate=.identity], [thisArg])find()는 조건을 만족하는 컬렉션에서의 첫번째 요소를 찾는 메소드입니다.
var myFriend=[
 {name:'kys',job:'developer',age:27},
 {name:'cys',job:'webtoons man',age:27},
 {name:'yhs',job:'florist',age:26},
 {name:'chj',job:'nonghyup man',age:27},
 {name:'ghh',job:'coffee man',age:27},
 {name:'ldh',job:'kangaroo',age:27},
]

// 콜백함수가 처음으로 참이되는 객체를 반환
_.find(myFriend, function(friend) {
  return friend.age < 28;
});
// → { name: 'kys',job:'developer' ,'age': 27}
 

[개발상식] lodash 알고 쓰자.

안녕하세요. 김용성입니다. 오늘은 lodash에 대해 포스팅해보도록 하겠습니다.

velog.io


테스트 해 보면서 적용 한 예시:

const { UserList, MovieList } = require("../FakeData");
const _ = require("lodash");

const resolvers = {
  // User resolvers
  Query: {
    users: () => {
      return UserList;
    },
    user: (parent, args) => {
      const id = args.id;
      // .find(what do I want to find out, { key })
      // : Number(id) -> be sure to let it convert whatever passing value as Number
      const user = _.find(UserList, { id: Number(id) });
      return user;
    },

크게:

- schema 를 작성해야합니다. (여기에 type definition 과 resolver 개념이 있음)

- type 을 define 합니다.

- resolver 에서 해당 정의된 각 변수들을 가지고 (개인의 목표대로) 구성해줍니다.

- 이 중심에는 API 가 있어야 합니다.

 

(아래 링크에는 위에서 못다한 exclamation mark 에 대한 보충 설명이 있음)

 

GraphQL schema basics

Your GraphQL server uses a schema to describe the shape of your available data. This schema defines a hierarchy of types with fields that are populated from your back-end data stores. The schema also specifies exactly which queries and mutations are availa

www.apollographql.com

 

아래에서는 Handling Arguments를 참고. 

 

Resolvers

How Apollo Server processes GraphQL operations

www.apollographql.com

잠깐...! 그래서, 대망의 REST API 는?

아래의 방법을 참고해서 이것 저것 시도중. 조만간 업데이트 해보겠습니다.

 

Fetching data

Manage connections to databases and other data sources

www.apollographql.com

 

플랜 B.

 

Generating REST APIs from GraphQL Schemas, a Tutorial

Arguing about technology choices is a huge thing, but sometimes there methods to unite the different ways.

www.moesif.com