-
Notifications
You must be signed in to change notification settings - Fork 643
/
BookStore.js
57 lines (51 loc) · 1.47 KB
/
BookStore.js
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
import { types, getParent, process } from "mobx-state-tree"
export const Book = types.model("Book", {
id: types.identifier(),
name: types.string,
author: types.string,
price: types.number,
isAvailable: true
})
export const BookStore = types
.model("BookStore", {
isLoading: true,
books: types.map(Book)
})
.views(self => ({
get shop() {
return getParent(self)
},
get sortedAvailableBooks() {
return sortBooks(self.books.values())
}
}))
.actions(self => {
function markLoading(loading) {
self.isLoading = loading
}
function updateBooks(json) {
self.books.values().forEach(book => (book.isAvailable = false))
json.forEach(bookJson => {
self.books.put(bookJson)
self.books.get(bookJson.id).isAvailable = true
})
}
const loadBooks = process(function* loadBooks() {
try {
const json = yield self.shop.fetch("/books.json")
updateBooks(json)
markLoading(false)
} catch (err) {
console.error("Failed to load books ", err)
}
})
return {
updateBooks,
loadBooks
}
})
function sortBooks(books) {
return books
.filter(b => b.isAvailable)
.sort((a, b) => (a.name > b.name ? 1 : a.name === b.name ? 0 : -1))
}