|
1 | 1 | // Use our automatically generated Book and AddBookMutationResponse types
|
2 | 2 | // for type safety in our data source class
|
3 |
| -import { AddBookMutationResponse, Book } from './__generated__/resolvers-types'; |
| 3 | +import { AddBookMutationResponse, Book } from "./__generated__/resolvers-types"; |
4 | 4 |
|
5 |
| -export class BooksDataSource { |
6 |
| - // Our example static data set |
7 |
| - books: { title?: string; author?: string }[] = [ |
8 |
| - { |
9 |
| - title: 'The Awakening', |
10 |
| - author: 'Kate Chopin', |
11 |
| - }, |
12 |
| - { |
13 |
| - title: 'City of Glass', |
14 |
| - author: 'Paul Auster', |
15 |
| - }, |
16 |
| - ]; |
| 5 | +const BooksDB: Omit<Required<Book>, "__typename">[] = [ |
| 6 | + { |
| 7 | + title: "The Awakening", |
| 8 | + author: "Kate Chopin", |
| 9 | + }, |
| 10 | + { |
| 11 | + title: "City of Glass", |
| 12 | + author: "Paul Auster", |
| 13 | + }, |
| 14 | +]; |
17 | 15 |
|
| 16 | +export class BooksDataSource { |
18 | 17 | getBooks(): Book[] {
|
19 | 18 | // simulate fetching a list of books
|
20 |
| - return this.books; |
| 19 | + return BooksDB; |
21 | 20 | }
|
22 | 21 |
|
23 | 22 | // We are using a static data set for this small example, but normally
|
24 | 23 | // this Mutation would *mutate* our underlying data using a database
|
25 | 24 | // or a REST API.
|
26 | 25 | async addBook(book: Book): Promise<AddBookMutationResponse> {
|
27 |
| - this.books.push(book); |
28 |
| - console.log(this.books); |
| 26 | + if (book.title && book.author) { |
| 27 | + BooksDB.push({ title: book.title, author: book.author }); |
29 | 28 |
|
30 |
| - return { |
31 |
| - code: '200', |
32 |
| - success: true, |
33 |
| - message: 'New book added!', |
34 |
| - book: this.books[this.books.length - 1], |
35 |
| - }; |
| 29 | + return { |
| 30 | + code: "200", |
| 31 | + success: true, |
| 32 | + message: "New book added!", |
| 33 | + book, |
| 34 | + }; |
| 35 | + } else { |
| 36 | + return { |
| 37 | + code: "400", |
| 38 | + success: false, |
| 39 | + message: "Invalid input", |
| 40 | + book: null, |
| 41 | + }; |
| 42 | + } |
36 | 43 | }
|
37 | 44 | }
|
0 commit comments