GraphQL

miiin_sseong·2021년 11월 8일
0

Code_camp

목록 보기
3/11

typeDef(s)

  1. GraphQl Schema를 정의하는 곳
    • Object
    • Query
    • Mutation
    • input
  2. GQL과 Tagged Template Literals로 작성한다
styled Component처럼 Template String을 통해 함수 뒤에 붙여준다.

resolver(s)

  1. Schema에 해당하는 구현을 하는곳
  2. 요청을 받아 데이터를 조회,수정,삭제

여러개의 데이터 조회하기

join할때 꼭 require('path')주의!

index.js

const { ApolloServer, gql } = require('apollo-server');
const { readFileSync } = 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 query 생성
  }
//Book의 타입정해주기
  type Book { 
    bookId: Int
    title: String
    message: String
    author: String
    url: String
  }
`;

// A map of functions which return data for the schema.
// 스키마에 해당하는 데이터를 리턴하는 함수의 map
// 함수 매핑
const resolvers = {
  Query: {
    hello: () => 'world',
    books: () => {
      return JSON.parse(readFileSync(join(__dirname, 'books.json')).toString());
    },
  },
};

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

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

books.json

[
  {
    "bookId": 1,
    "title": "title test",
    "message": "message test",
    "author": "author test",
    "url": "url test"
  },
  {
    "bookId": 2,
    "title": "title test2",
    "message": "message test2",
    "author": "author test2",
    "url": "url test2"
  }
]

특정데이터 조회하기

index.js

const { ApolloServer, gql } = require('apollo-server');
const { readFileSync } = 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       // 1. book추가
  }
  type Book {
    bookId: Int
    title: String
    message: String
    author: String
    url: String
  }
`;

// A map of functions which return data for the schema.
// 스키마에 해당하는 데이터를 리턴하는 함수의 map
// 함수 매핑
const resolvers = {
  Query: {
    hello: () => 'world',
    books: () => {
      return JSON.parse(readFileSync(join(__dirname, 'books.json')).toString());
    },
    book: (parent, args, context, info) => {      // 2. resolvers 추가
      const books = JSON.parse(                  
        readFileSync(join(__dirname, 'books.json')).toString()
      );
      return books.find(book => book.bookId === args.bookId);
    }
  },
};

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

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

데이터추가

Mutation

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 { 				//1. 스키마 추가
    addBook(title: String, message: String, author: String, url: String): Book
  }
  type Book {
    bookId: Int
    title: String
    message: String
    author: String
    url: String
  }
`;

// A map of functions which return data for the schema.
// 스키마에 해당하는 데이터를 리턴하는 함수의 map
// 함수 매핑
const resolvers = {
  Query: {
    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: {             // 2. resolver 추가
    addBook: (parent, args, context, info) => {
      const books = JSON.parse(
        readFileSync(join(__dirname, 'books.json')).toString()
      );
      const maxId = Math.max(...books.map(book => book.bookId));
      [...books, { ...args, bookId: maxId + 1 }]
      const newBook = { ...args, bookId: maxId + 1 };
      writeFileSync(
        join(__dirname, 'books.json'),
        JSON.stringify([...books, newBook])
      );
      return newBook;
    }
  }
};

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

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

데이터 변경

항상 typeDefs과 resolvers의 변수가 같은지 확인!

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
  }
  type Book {
    bookId: Int
    title: String
    message: String
    author: String
    url: String
  }
`;

// A map of functions which return data for the schema.
// 스키마에 해당하는 데이터를 리턴하는 함수의 map
// 함수 매핑
const resolvers = {
  Query: {
    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));
      [...books, { ...args, bookId: maxId + 1 }]
      const newBook = { ...args, bookId: maxId + 1 };
      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;
    },
  }
};

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

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

데이터 삭제

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.
// 스키마에 해당하는 데이터를 리턴하는 함수의 map
// 함수 매핑
const resolvers = {
  Query: {
    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));
      [...books, { ...args, bookId: maxId + 1 }]
      const newBook = { ...args, bookId: maxId + 1 };
      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 함수
    deleteBook: (parent, args, context, info) => {
      const books = JSON.parse(
        readFileSync(join(__dirname, 'books.json')).toString()
      );

      const deleted = books.find(book => book.bookId === args.bookId)
      // filter를 써서 자료를 빼온다
      const newBooks = books.filter((book) => book.bookId !== args.bookId)

      writeFileSync(
        join(__dirname, 'books.json'),
        JSON.stringify(newBooks)
      );
      return deleted;
    },
  }
};

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

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});
profile
Github잔디를 채우기 위해 Github에서 적는중

0개의 댓글