-
Notifications
You must be signed in to change notification settings - Fork 1
/
BookligoModel.js
executable file
·66 lines (56 loc) · 1.44 KB
/
BookligoModel.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
58
59
60
61
62
63
64
65
66
import ObservableModel from "./ObservableModel";
import * as Constants from "./googlebooksapiConfig";
class BookligoModel extends ObservableModel {
constructor() {
super();
this.state = localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')) : {
numberOfBooks: 0,
};
}
updateLocalStorage() {
localStorage.setItem('state', JSON.stringify(this.state));
}
/**
* Get the number of books
* @returns {number}
*/
getNumberOfBooks() {
return this.state.numberOfBooks;
}
/**
* Set number of books
* @param {number} num
*/
setNumberOfBooks(num) {
if(num <= 0)
num = 1;
this.state.numberOfBooks = num;
this.updateLocalStorage();
this.notifyObservers("A number of books has changed");
}
// API methods:
// Returns a book of specific ID
getBook(id) {
if(!id)
id = '';
const url = `${Constants.ENDPOINT}/${id}`;
return fetch(url, Constants.httpOptions).then(this.processResponse);
}
/**
* Do an API call to the search API endpoint.
* @returns {Promise<any>}
*/
getAllBooks(query) {
const url = `${Constants.ENDPOINT}?q=${query}`;
return fetch(url, Constants.httpOptions).then(this.processResponse);
}
processResponse(response) {
if (response.ok) {
return response.json();
}
throw response;
}
}
// Export an instance of BookligoModel
const modelInstance = new BookligoModel();
export default modelInstance;