Skip to content
Permalink
Browse files

Sorting and filtering the books

  • Loading branch information...
Qaiser Abbas Qaiser Abbas
Qaiser Abbas authored and Qaiser Abbas committed May 13, 2018
1 parent 925920c commit 620be74af6c5bbf119478405388c8bf978d85586
Showing with 47 additions and 3 deletions.
  1. +28 −2 src/stores/book/__tests__/index.js
  2. +18 −0 src/stores/book/index.js
  3. +1 −1 src/stores/book/mock-api/api.js
@@ -1,8 +1,34 @@
import { BookStore } from '../index'
import api from '../mock-api/api'

it('bookstore fetches data', async () => {
const store = BookStore.create({ books: [] }, { api })
let store = null

beforeEach(async () => {
store = BookStore.create({ books: [] }, { api })
await store.loadBooks()
})

it('Bookstore fetches data', () => {
expect(store.books.length).toBe(10)
})

it(`Bookstore filter is set when setGenre() is called with a valid filter value`, async () => {
store.setGenre('Nonfiction')
expect(store.filter).toBe('Nonfiction')
})

it(`Bookstore filter is NOT set when setGenre() is called with an invalid filter value`, async () => {
expect(() => store.setGenre('Adventure')).toThrow()
})

it(`Books are sorted by title`, async () => {
const books = store.sortedBooks
expect(books[0].title).toBe('By The Book')
expect(books[1].title).toBe('Jane Eyre')
})

it(`Books are sorted by title`, async () => {
store.setGenre('Nonfiction')
const books = store.sortedBooks
expect(books.length).toBe(7)
})
@@ -6,27 +6,40 @@ let store = null
const Book = t.model('Book', {
id: t.identifier(),
title: t.string,
genre: t.string,
pageCount: t.number,
authors: t.array(t.string),
image: t.maybe(t.string),
inStock: t.optional(t.boolean, true),
})

const sortFn = (a, b) => (a.title > b.title ? 1 : a.title === b.title ? 0 : -1)

export const BookStore = t
.model('BookStore', {
books: t.array(Book),
filter: t.optional(
t.enumeration('FilterEnum', ['All', 'Fiction', 'Nonfiction']),
'All'
),
})
.views(self => ({
get api() {
return getEnv(self).api
},
get sortedBooks() {
return self.filter === 'All'
? self.books.sort(sortFn)
: self.books.filter(bk => bk.genre === self.filter).sort(sortFn)
},
}))
.actions(self => {
function updateBooks(books) {
books.items.forEach(book => {
self.books.push({
id: book.id,
title: book.volumeInfo.title,
genre: book.volumeInfo.categories[0],
pageCount: book.volumeInfo.pageCount,
authors: book.volumeInfo.authors,
publisher: book.volumeInfo.publisher,
@@ -44,8 +57,13 @@ export const BookStore = t
}
})

const setGenre = genre => {
self.filter = genre
}

return {
loadBooks,
setGenre,
}
})

@@ -3,7 +3,7 @@ const books = require('./books')
const delayedPromise = (data, delaySecs = 2) =>
new Promise(resolve => setTimeout(() => resolve(data), delaySecs * 1000))

const fetchBooks = () => delayedPromise(books)
const fetchBooks = () => delayedPromise(books, 0.3)

export default {
fetchBooks,

0 comments on commit 620be74

Please sign in to comment.
You can’t perform that action at this time.