-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathserverapi_ajax.js
58 lines (47 loc) · 1.38 KB
/
serverapi_ajax.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
/* ServerAPI talks REST with the backend server.
*
* All server communication takes place via this singleton module!
*
* Calls return promises.
*
* (Wish I could use async/await but browser support is still lacking.)
*
* My Python REST API server implements this simple movie API:
* https://github.com/tomimick/restpie3
*/
import axios from "axios"
const URL_MOVIES = "http://localhost:8100/api/movies/";
class ServerAPI {
constructor() {
this.client = axios.create({
withCredentials: true, // pass cookies to cross-site api
});
}
query_movies() {
let url = URL_MOVIES;
return this.client.get(url).then(reply => {return reply.data});
// have a cache here so the request would not always reach server
}
get_movie(id) {
let url = `${URL_MOVIES}${id}`;
return this.client.get(url).then(reply => {return reply.data});
}
save_movie(item) {
if (!item.id) {
// create
let url = URL_MOVIES;
return this.client.post(url, item);
} else {
// update
let url = `${URL_MOVIES}${item.id}`;
return this.client.put(url, item);
}
}
delete_movie(id) {
let url = `${URL_MOVIES}${id}`;
return this.client.delete(url);
}
}
// export singleton API
const api = new ServerAPI();
export default api;