Nodejs - graphql,apollo 사용법(1)-addition1

any1ok·2021년 9월 19일
0

query 에서 특정값으로 해당 값 불러오기!

스키마에 데이터를 추가하고

  type Query {
    books: [Book]
    book(id:Int) : Book //추가
  }

resolvers book 에대한걸 추가하면

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];
      }

    },
    
  };

id 값으로 조회해볼수 있다.

Join 처럼 하위항목 함께가져오기

먼저 데이터를 추가하고

let contents = [
  {
    book_id: 1,
    page : 1,
    text : "aaaaa"
  },
  {
    book_id: 1,
    page : 2,
    text : "bbbbb"
  },
  {
    book_id: 1,
    page : 3,
    text : "cccccc"
  },
  {
    book_id: 1,
    page : 4,
    text : "ddddd"
  },
  {
    book_id: 1,
    page : 5,
    text : "eeeee"
  },
  {
    book_id: 2,
    page : 1,
    text : "asdf"
  },
  {
    book_id: 2,
    page : 2,
    text : "qwer"
  },
  {
    book_id: 2,
    page : 3,
    text : "dfgh"
  },
  {
    book_id: 2,
    page : 4,
    text : "dgh"
  }
]

스키마도 추가하고

const typeDefs = gql`
  type Content{
    book_id: Int
    page :Int
    text: String
  }
  //위처럼 content 형식을 추가한후
  type Book {
    id : Int
    title: String
    author: String
    contents : [Content]
  }
 // Book 타입에다 contents argument 를 추가하여 contents 는 새로추가한 content 의 배열을 가진 형식이다! 라고 선언해준것이다.

  type Query {
    books: [Book]
    book(id:Int) : Book
  }
  
  type Mutation {
    createBook(title: String!,author: String!): Boolean
    deleteBook(id: Int!): Boolean
  }
`;

resolver 도 약간의 수정을 고쳐보면

const resolvers = {

	//아래의 books book 은 유사한 방법으로 변경되었는데
    books book 둘다 books 의 id 값과 content 의 book_id 이 동일한것을 매핑 시켜주었다.
    Query: {
      books: () => books.map((book) =>{
        book.contents = contents.filter((content) =>{
          return book.id == content.book_id
        })
        return book
      }),
      
      book: (_,args) => {

        //const result = books.filter((book) => {book.id === args.id}); 
        const result = books.filter((book) =>{
          book.contents = contents.filter((content) =>{
            return book.id == content.book_id
          }) 
          return book.id === args.id});

        return result[0];
      }

    },

결과는

잘 매핑된듯하다!

전체코드

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

const { ApolloServer, gql } = require("apollo-server");


const typeDefs = gql`
type Content{
  book_id: Int
  page :Int
  text: String
}
  type Book {
    id : Int
    title: String
    author: String
    contents : [Content]
  }
 

  type Query {
    books: [Book]
    book(id:Int) : Book
  }
  
  type Mutation {
    createBook(title: String!,author: String!): Boolean
    deleteBook(id: Int!): Boolean
  }

`;

let books = [
    {
      id: 1,
      title: 'The Awakening',
      author: 'Kate Chopin',
    },
    {
      id: 2,
      title: 'City of Glass',
      author: 'Paul Auster',
    },
  ];

let contents = [
  {
    book_id: 1,
    page : 1,
    text : "aaaaa"
  },
  {
    book_id: 1,
    page : 2,
    text : "bbbbb"
  },
  {
    book_id: 1,
    page : 3,
    text : "cccccc"
  },
  {
    book_id: 1,
    page : 4,
    text : "ddddd"
  },
  {
    book_id: 1,
    page : 5,
    text : "eeeee"
  },
  {
    book_id: 2,
    page : 1,
    text : "asdf"
  },
  {
    book_id: 2,
    page : 2,
    text : "qwer"
  },
  {
    book_id: 2,
    page : 3,
    text : "dfgh"
  },
  {
    book_id: 2,
    page : 4,
    text : "dgh"
  }
]

const resolvers = {
    Query: {
      books: () => books.map((book) =>{
        book.contents = contents.filter((content) =>{
          return book.id == content.book_id
        })
        return book
      }),
      
      book: (_,args) => {

        //const result = books.filter((book) => {book.id === args.id}); 
        const result = books.filter((book) =>{
          book.contents = contents.filter((content) =>{
            return book.id == content.book_id
          }) 
          return book.id === args.id});

        return result[0];
      }

    },
    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);
      }
    }
  };

const server = new ApolloServer({ typeDefs, resolvers });


// server를 감시하고 있다가, 실행되면 콘솔창에 알림메시지를 보내줌

server.listen().then(({ url }) => {
console.log(`🚀  Server ready at ${url}`);
});

  
app.get("/", function (req, res) {
    res.send("Hello graphql----");
  });

app.listen(3000, function () {
    console.log("App started");
});
  
profile
백엔드 개발자

0개의 댓글