-
Notifications
You must be signed in to change notification settings - Fork 36
/
actions.js
104 lines (93 loc) · 2.01 KB
/
actions.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
export const SET_GAMES = 'SET_GAMES';
export const ADD_GAME = 'ADD_GAME';
export const GAME_FETCHED = 'GAME_FETCHED';
export const GAME_UPDATED = 'GAME_UPDATED';
export const GAME_DELETED = 'GAME_DELETED';
function handleResponse(response) {
if (response.ok) {
return response.json();
} else {
let error = new Error(response.statusText);
error.response = response;
throw error;
}
}
export function setGames(games) {
return {
type: SET_GAMES,
games
}
}
export function addGame(game) {
return {
type: ADD_GAME,
game
}
}
export function gameFetched(game) {
return {
type: GAME_FETCHED,
game
}
}
export function gameUpdated(game) {
return {
type: GAME_UPDATED,
game
}
}
export function gameDeleted(gameId) {
return {
type: GAME_DELETED,
gameId
}
}
export function saveGame(data) {
return dispatch => {
return fetch('/api/games', {
method: 'post',
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
}).then(handleResponse)
.then(data => dispatch(addGame(data.game)));
}
}
export function updateGame(data) {
return dispatch => {
return fetch(`/api/games/${data._id}`, {
method: 'put',
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
}).then(handleResponse)
.then(data => dispatch(gameUpdated(data.game)));
}
}
export function deleteGame(id) {
return dispatch => {
return fetch(`/api/games/${id}`, {
method: 'delete',
headers: {
"Content-Type": "application/json"
}
}).then(handleResponse)
.then(data => dispatch(gameDeleted(id)));
}
}
export function fetchGames() {
return dispatch => {
fetch('/api/games')
.then(res => res.json())
.then(data => dispatch(setGames(data.games)));
}
}
export function fetchGame(id) {
return dispatch => {
fetch(`/api/games/${id}`)
.then(res => res.json())
.then(data => dispatch(gameFetched(data.game)));
}
}