[graphQL] Mutation

김민재·2024년 4월 8일

GraphQL

목록 보기
8/11

Mutation이란?

  • CRUD를 가능하게 해준다.

    Mutation 사용해서 post create

    1. graphql 파일에 Mutation 지정
    
    ```
    // posts.graphql
    type Mutation {
    addNewPost(id: ID!, title: String!, description: String!): Post
     }  
    1. resolver 파일에 Mutation을 이용해 함수 실행

      // posts.resolvers.js
      const postsModel = require("./posts.model");
      
      module.exports = {
      Query: {
       posts: () => {
         return postsModel.getAllPosts();
       },
       post: (_, args) => {
         return postsModel.getPost(args.id);
       },
      },
      Mutation: {
       addNewPost: (_, args) => {
         return postsModel.addNewPost(args.id, args.title, args.description);
       },
      },
      };
      
      
    2. model 파일에 함수 생성

      // posts.model.js
      function addNewPost(id, title, description) {
      const newPost = {
       id,
       title,
       description,
       comments: [],
      };
      
      posts.push(newPost);
      return newPost;
      }
      

  • {
    title
    description
    } 은 return 값으로 뭘 받을지

    Mutation 사용해서 comment create

  1. comments.graphql Mutation 지정

    type Query {
     comments: [Comment]
     commentsByLikes(minLikes: Int!): [Comment]
    }
    
    type Mutation {
     addNewComment(id: ID!, text: String!): Comment
    }
    
    type Comment {
     id: ID!
     text: String!
     likes: Int
    }
  1. resolvers 파일에 Mutation을 이용한 함수 실행
 const commentsModel = require("./comments.model");

 module.exports = {
  Query: {
    comments: () => {
      return commentsModel.getAllComments();
    },
    commentsByLikes: (_, args) => {
      return commentsModel.getCommentsByLikes(args.minLikes);
    },
    // parent가 필요없으면 _를 넣어주자
    // passport done의 null 값과 같다
  },
  Mutation: {
    addNewComment: (_, args) => {
      return commentsModel.addNewComment(args.id, args.text);
    },
  },
};
  1. model 파일에 함수 생성
function addNewComment(id, text) {
  const newComment = {
    id,
    text,
    likes: 0,
  };

  comments.push(newComment);
  return newComment;
}

profile
개발 경험치 쌓는 곳

0개의 댓글