1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
| 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}`);
});
|