Nodejs - graphql,apollo 사용법(2)

any1ok·2021년 9월 19일
0

https://velog.io/@any1ok/Nodejs - graphql,apollo 사용법(1)
이 스크립트를 보기전에 이전회차인 이부분을 보도록 하자!

오늘의 스크맆트에서는 mutation 을 추가해보려 한다.
mutation 은 rest api 의 insert,put,delete 를 담당하고있다.

Mutation

먼저 GraphQL 스키마를 추가하고

const typeDefs = gql`

  type Book {
    id : Int
    title: String
    author: String
  }
  
  type Query {
    books: [Book]
    book(id:Int) : Book
  }
  // 이부분이 추가되엇다
  type Mutation {
    createBook(title: String!,author: String!): Boolean
    deleteBook(title: String!): Boolean
  }

`;

resolvers도 추가해보자

const resolvers = {
    Query: {
      books: () => books,
      
      book: (_,args) => {
        console.log('args', args);
        console.log(books);
        const result = books.filter(book => book.id === args.id); 
        console.log('result',result);
        return result[0];
      }

    },
    // mutation 부분 추가
     Mutation: {
  
      createBook: (_,args) => {
       
        console.log(args);
        let title = args.title;
        let author = args.author;
        let id = books.length+1;
        let book_temp = {id : id,title : title, author : author }
        books.push(book_temp);
        return true
      },
      deleteBook: (_,args) => {
        const findbook= books.find(function(book) {
          return book.id === 1
          });
          const idx = books.indexOf(findbook);
          books.splice(idx, 1);
      }
    }
  };

실행 시켜서

돌려보면

잘 추가되었음을 알수있다.

profile
백엔드 개발자

0개의 댓글