[ GraphQL ] 데이터 CRUD 연습

SeungJin·2022년 8월 17일
0

GraphQL

목록 보기
3/3

디렉토리 경로

  • My-Project/graphql-server/index.js

  • My-Project/graphql-server/index.js 코드

    const { ApolloServer, gql } = require('apollo-server');
    const { readFileSync, writeFileSync } = require('fs');
    const { join } = require('path');
    
    // The GraphQL schema
    const typeDefs = gql`
      type Query {
        "A simple type for getting started!"
        hello: String
        books: [Book]
        book(bookId: Int): Book
      }
      type Mutation {
        addBook(title: String, message: String, author: String, url: String): Book
        editBook(
          bookId: Int
          title: String
          message: String
          author: String
          url: String
        ): Book
        deleteBook(bookId: Int): Book
      }
      type Book {
        bookId: Int
        title: String
        message: String
        author: String
        url: String
      }
    `;
    
      // A map of functions which return data for the schema.
      const resolvers = {
        Query: {
          hello: () => 'Hello World',
          books: () => {
            return JSON.parse(readFileSync(join(__dirname, 'books.json')).toString());
          },
          book: (parent, args, context, info) => {
            const books = JSON.parse(
              readFileSync(join(__dirname, 'books.json')).toString()
            );
            return books.find((book) => book.bookId === args.bookId);
          },
        },
        Mutation: {
          addBook: (parent, args, context, info) => {
            const books = JSON.parse(
              readFileSync(join(__dirname, 'books.json')).toString()
            );
            const maxId = Math.max(...books.map((book) => book.bookId));
            const newBook = { bookId: maxId + 1, ...args };
            writeFileSync(
              join(__dirname, 'books.json'),
              JSON.stringify([...books, newBook])
            );
            return newBook;
          },
          editBook: (parent, args, context, info) => {
            const books = JSON.parse(
              readFileSync(join(__dirname, 'books.json')).toString()
            );
            const newBooks = books.map((book) => {
              if (book.bookId === args.bookId) {
                return args;
              } else {
                return book;
              }
            });
            writeFileSync(join(__dirname, 'books.json'), JSON.stringify(newBooks));
            return args;
          },
          deleteBook: (parent, args, context, info) => {
            const books = JSON.parse(
              readFileSync(join(__dirname, 'books.json')).toString()
            );
            const deletedBook = books.find((book) => book.bookId === args.bookId);
            const newBooks = books
              .filter((book) => book.bookId !== args.bookId)
              .map((book, index) => {
                book.bookId = index;
                return { ...book };
              });
            writeFileSync(join(__dirname, 'books.json'), JSON.stringify(newBooks));
            return deletedBook;
          },
        },
      };
    
      const server = new ApolloServer({
        typeDefs,
        resolvers,
        playground: true,
      });
    
      server.listen().then(({ url }) => {
        console.log(`🚀 Server ready at ${url}`);
      });
    

특정 데이터 조회

  • bookId를 받아오는 쿼리 작성

    const typeDefs = gql`
      type Query {
        hello: String
        books:[Book]
        
        // bookId를 받아오는 쿼리
        book(bookId : Int) : Book
        
      },
      type Book {
        bookId: Int,
        title: String,
        message: String,
        author: String,
        url: String
      }
    `;
  • bookId를 받아 데이터를 찾아 리턴 하는 함수 작성

    const resolvers = {
      Query: {
        hello: () => 'Hello World',
        books: () => {
          return JSON.parse(
            readFileSync(join(__dirname, 'books.json')).toString()
          );
        },
        book: (parent, args, context, info) => {
          const books = JSON.parse(
            readFileSync(join(__dirname, 'books.json')).toString()
          );
          return books.find((book) => book.bookId === args.bookId);
        },
      },
    };

데이터 추가

  • 데이터를 추가하는 쿼리 작성

    const typeDefs = gql`
      type Mutation {
        addBook(title: String, message: String, author: String, url: String): Book
      }
    `;
  • 데이터를 받아와 기존의 bookId +1을 가진 새로운 객체를 만들어 받아온 데이터를 새로운 객체에 추가 하는 함수를 작성.

    const resolvers = {
      Mutation: {
        addBook: (parent, args, context, info) => {
          const books = JSON.parse(
            readFileSync(join(__dirname, 'books.json')).toString()
          );
          const maxId = Math.max(...books.map((book) => book.bookId));
          const newBook = { bookId: maxId + 1, ...args };
          writeFileSync(
            join(__dirname, 'books.json'),
            JSON.stringify([...books, newBook])
          );
          return newBook;
        },
      },
    };

특정 데이터 삭제

  • 특정 데이터의 bookId를 받아오는 쿼리 작성

    const typeDefs = gql`
      type Mutation {
        deleteBook(bookId: Int): Book
      }
    `;
  • bookId 데이터를 받아와 받아온 bookId 와 같은 bookId 를 가진 객체 삭제

    const resolvers = {
      Mutation: {
        deleteBook: (parent, args, context, info) => {
          const books = JSON.parse(
            readFileSync(join(__dirname, 'books.json')).toString()
          );
          // 객체 배열 books를 find 함수를 이용해 받아온 bookId와 같은 데이터를 찾아 deletedBook에 할당
          const deletedBook = books.find((book) => book.bookId === args.bookId);
          // 객체 배열 books를 filter 함수를 이용해 받아온 bookId와 같은 데이터를 걸러 newBooks에 할당
          // 할당된 데이터들의 bookId를 0부터 순서대로 재할당
          const newBooks = books
            .filter((book) => book.bookId !== args.bookId)
            .map((book, index) => {
              book.bookId = index;
              return { ...book };
            });
          writeFileSync(join(__dirname, 'books.json'), JSON.stringify(newBooks));
          // 삭제한 데이터를 반환
          return deletedBook;
        },
      },
    };

GitHub 링크

profile
혼자 공부해 보고 적어두는 블로그입니다 문제 있다고 생각되시는 부분이 있으면 피드백이라도 남겨주시면 감사하겠습니다

0개의 댓글