본문 바로가기
web

graphql 기본 문법 정리

by java개발자 2020. 7. 3.

참고: https://academy.nomadcoders.co/courses/357405/lectures/5476213

1.기본
2.객체
3.배열
4.mutaion
5.외부api (node-fetch)
6.외부api (axios)

 

1.기본

<!-- schema -->
type Query {
  name: String! # !(느낌표)는 요청했을때, resolvers에서 필수로 넘겨야 하는 값
}

<!-- resolvers -->
const resolvers = {
  Query: {
    name: () => "nicolas 2",
  },
};

<!-- 실행 -->
query {
  name
}

<!-- 결과 -->
{
  "data": {
    "name": "nicolas 2"
  }
}

2.객체

<!-- schema -->
type Nicolas {
  name: String!
  age: Int!
  gender: String!
}
type Query {
  person: Nicolas!
}

<!-- resolvers -->
const nicolas = {
  name: 'Nicolas',
  age: 18,
  gender: 'female'
}
const resolvers = {
  Query: {
    person: () => nicolas,
  },
};

<!-- 실행 -->
query {
  person {
    name
    age
    gender
  }
}

<!-- 결과 -->
{
  "data": {
    "person": {
      "name": "Nicolas",
      "age": 18,
      "gender": "female"
    }
  }
}


3.배열

<!-- schema -->
type Person {
  id: Int!
  name: String!
  age: Int!
  gender: String!
}
type Query {
  people: [Person]!
  person(id: Int!): Person # 파라메터(Int)를 필수로 넘겨서 Person을 리턴(느낌표가 없으니까 결과가 null일 수도 있다.)
}

<!-- resolvers -->
const people = [{
  id: '0',
  name: 'Nicolas',
  age: 18,
  gender: 'female'
}, {
  id: '1',
  name: 'Smith',
  age: 11,
  gender: 'male'
}]
const resolvers = {
  Query: {
    people: () => people,
    person: (_, args) => {
      console.log('args', args); // args { id: 1 }
      const result = people.filter(person => person.id === String(args.id));
      return result[0];
    }
  },
};

<!-- 실행 -->
query {
  person(id: 1) {
    id
    name
    age
    gender
  }
}

<!-- 결과 -->
{
  "data": {
    "person": {
      "id": 1,
      "name": "Smith",
      "age": 11,
      "gender": "male"
    }
  }
}


4.mutaion

<!-- schema -->
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 -->
let movies = [{
  id: 0,
  name: 'aaa',
  score: 1
}, {
  id: 1,
  name: 'bbb',
  score: 99
}]
const resolvers = {
  Query:{
    movies: () => movies,
    movie: (_, {id}) => {
      return movies.filter(movie => movie.id === id)[0]
    }
  },
  Mutation: {
    addMovie: (_, {name, score}) => {
      const newMovie = {
        id: movies.length + 1,
        name,
        score
      }
      movies.push(newMovie);
      return newMovie;
    },
    deleteMovie: (_, {id}) => {
      const remainMovies = movies.filter(movie => movie.id !== id)
      if (movies.length > remainMovies.length) {
        movies = remainMovies;
        return true;
      }
      return false;
    }
  }
}

<!-- 실행 -->
mutation {
  addMovie(name: "a", score: 1) {
    id
    name
    score
  }
  deleteMovie(id: 0) # Boolean으로 명확하므로, 리턴받을 것을 명시하지 않아도 된다.
}

<!-- 결과 -->
{
  "data": {
    "addMovie": {
      "id": 3,
      "name": "a",
      "score": 1
    },
    "deleteMovie": true
  }
}


5.외부api (node-fetch)

<!-- schema -->
type Movie {
  id: Int!
  title: String!
  rating: Float!
  summary: String!
  language: String!
  medium_cover_image: String!
}
type Query {
  movies(limit: Int, rating: Float): [Movie]!
}

<!-- resolvers -->
const resolvers = {
  Query: {
    movies: async (_, {limit, rating}) => {
      let QUERY_STRING = '';
      if (limit > 0) {
        QUERY_STRING += `limit=${limit}&`
      }
      if (rating > 0) {
        QUERY_STRING += `minimum_rating=${rating}`
      }
      const result = await fetch('https://yts.am/api/v2/list_movies.json?' + QUERY_STRING)
      .then(res => res.json())
      .then(json => json.data.movies)
      console.log('result', result);
      return result;
    }
  }
}

<!-- 실행 -->
query {
  movies(limit: 1, rating: 9.1) {
    id
    title
    rating
    summary
    language
    medium_cover_image
  }
}

<!-- 결과 -->
{
  "data": {
    "movies": [
      {
        "id": 18871,
        "title": "Shark School",
        "rating": 2.7,
        "summary": "Two young fish, love to attend fish school each and every day! They learn along with their beloved teacher, who shows them the way! Fish School is fun and educational experience for kids of all ages!",
        "language": "English",
        "medium_cover_image": "https://yts.mx/assets/images/movies/shark_school_2019/medium-cover.jpg"
      }
    ]
  }
}


6.외부api (axios)

schema

type Movie {
  id: Int!
  title: String!
  rating: Float!
  summary: String!
  language: String!
  medium_cover_image: String!
}
type Query {
  movies(limit: Int, rating: Float): [Movie]!
  movie(id: Int!): Movie
  suggestions(id: Int!): [Movie]
}

resolvers

const resolvers = {
  Query: {
    movies: async (_, {limit, rating}) => {
      const result = await axios(`https://yts.am/api/v2/list_movies.json`, {
        params: {
          limit,
          minimum_rating: rating
        }
      });
      return lodash.get(result, 'data.data.movies') || [];
    },
    movie: async (_, {id}) => {
      const result = await axios(`https://yts.am/api/v2/movie_details.json`, {
        params: {
          movie_id: id
        }
      });
      return lodash.get(result, 'data.data.movie');
    },
    suggestions: async (_, {id}) => {
      const result = await axios(`https://yts.am/api/v2/movie_suggestions.json`, {
        params: {
          movie_id: id
        }
      });
      return lodash.get(result, 'data.data.movies') || [];
    }
  }
}

playground 실행

query {
  movies(limit: 1, rating: 9.1) {
    id
    title
    rating
    summary
    language
    medium_cover_image
  }
  movie(id: 18870) {
    id
    title
    rating
    language
    medium_cover_image
  }
  suggestions(id: 7893) {
    id
    title
    rating
    language
    medium_cover_image
  }
}

playground 결과

{
  "data": {
    "movies": [
      {
        "id": 18871,
        "title": "Shark School",
        "rating": 2.7,
        "summary": "Two young fish, love to attend fish school each and every day! They learn along with their beloved teacher, who shows them the way! Fish School is fun and educational experience for kids of all ages!",
        "language": "English",
        "medium_cover_image": "https://yts.mx/assets/images/movies/shark_school_2019/medium-cover.jpg"
      }
    ],
    "movie": {
      "id": 18870,
      "title": "The Missing",
      "rating": 6.5,
      "language": "English",
      "medium_cover_image": "https://yts.mx/assets/images/movies/the_missing_2003/medium-cover.jpg"
    },
    "suggestions": [
      {
        "id": 2515,
        "title": "Resolution",
        "rating": 6.4,
        "language": "English",
        "medium_cover_image": "https://yts.mx/assets/images/movies/Resolution_2012/medium-cover.jpg"
      },
      {
        "id": 6880,
        "title": "Score",
        "rating": 7.5,
        "language": "English",
        "medium_cover_image": "https://yts.mx/assets/images/movies/score_a_film_music_documentary_2016/medium-cover.jpg"
      },
      {
        "id": 6661,
        "title": "Pocket Listing",
        "rating": 6.5,
        "language": "English",
        "medium_cover_image": "https://yts.mx/assets/images/movies/pocket_listing_2015/medium-cover.jpg"
      },
      {
        "id": 8822,
        "title": "Jurassic World: Fallen Kingdom",
        "rating": 6.2,
        "language": "English",
        "medium_cover_image": "https://yts.mx/assets/images/movies/jurassic_world_fallen_kingdom_2018/medium-cover.jpg"
      }
    ]
  }
}

'web' 카테고리의 다른 글

브라우저 탭 2개 스크롤 동기화 (웨일, 크롬 브라우저)  (2) 2022.10.06
github actions  (0) 2021.04.27
react.js  (0) 2020.07.03
vue.js vs react.js  (0) 2020.06.24
[spring을 spring 답게] spring 세팅  (0) 2020.03.27