const typeDefs = gql`
type Book {
title: String
author: String
url: String
bookId: Int
}
type Mutation {
addBook(title: String, author: String, url: String): Book
editBook(bookId: Int, title: String, author: String, url: String): Book
deleteBook(bookId: Int): Book
}
`;
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 = { ...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: (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);
writeFileSync(join(__dirname, "books.json"), JSON.stringify(newBooks));
return deletedBook;
},
},
};