GraphQL API 만들기 -3

Imnottired·2023년 2월 21일
0

이번에는 Mutation에 관한 Resolver를 만들려고 한다.

 type Mutation {
    postTweet(text: String, userId: ID): Tweet!
  }

const resolvers = {
  Mutation: {
    postTweet(root, { text, userId }) {
      const newTweet = { id: tweets.length + 1, text };
      tweets.push(newTweet);
      return newTweet;
    },
  },
};

SDL 에서 Tweet!라고 선언햇으니 resolvers의 Mutation에서도 return 해주어야한다.

아폴로에서 실행하니


원하는 대로 결과값이 잘나왔다.

  type Mutation {

    deleteTweet(id:ID!): Boolean!
  }
  
  
const resolvers = {
  Mutation: {
	deleteTweet(_,{id}){
    const tweet = tweets.find((tweet)=> tweet.id === id);
    if(!tweet) return false;
   tweets= tweets.filter(tweet => tweet.id !==id);
   return true;
    },
    },
 
};

쿼리로 받아 와보면

2번이 지워진걸 알 수 있다.

root에 대하여

  User: {
    fullName() {
      console.log(`second`);
      return "hello";
    },
  },

리졸브안에 유저에 대해 fullName을 콜한다.

그러고나서 allUser 겟하고
user를 리턴해주면



let users = [
  {
    id: "1",
    firstName: "나",
    lastName: "준",
  },
    {
    id: "2",
    firstName: "김",
    lastName: "치",
  },
];

const typeDefs = gql`
	type User {
    id: ID!
    firstName: String!
    lastName: String!
    fullName: String!
  }
    type Query {
    allUsers: [User!]!
  
  }
 `
 const resolvers = {
  Query: {
    allUsers() {
      console.log(`first`);
      return users;
    },
  },
  User: {
    fullName(root) {
      console.log(`second`);
      console.log(root);
      return "hello";
    },
  },
};
 

users에 fullName이 없지만 요청 받은 값이

위와 같아서 resolvers의 User를 콜해서 fullName을 만들어준다.

  User: {
    fullName({ firstName, lastName }) {
      console.log(`second`);

      return `${firstName} ${lastName}`;
    },
  },
  

위 화면을 이용하여 root대신에 { firstName, lastName } 넣어주고 리턴하면
쿼리했을 때 우리가 원하는 값이 나온다.

정리하면
type resolvers에 의해
User가 fullName을 갖는다. GraphQL에게 얘기했다.
fullName은 data에 값이 없지만 대신 data 기반해서 도출된다.
GraphQL은 똑똑해서 fullName이 resolver인것도 안다.


 Tweet: {
    author({ userId }) {
      return users.find((user) => user.id === userId);
    },
  },
  

resolver에 작성하였다.

그러면 먼저 Tweet의 author resolver에게 리턴값을 받고
author 타입을 User로 정의되어서 그안에 있는 User의 fullName resolver를 찾아서
리턴 값을 받는다.

이렇게 type resolver를 알아서 찾는 것은 GraphQL에 강력한 장점이다.

"""
이 방식을 이용해 설명을 달아줄 수 있다.
"""


이것은 클라이언트에서도 볼 수 있다.


이런 식으로 기존의 REST API도 사용할 수 있다.

profile
새로운 것을 배우는 것보다 정리하는 것이 중요하다.

0개의 댓글