forked from CodeForPoznan/pah-fm
/
actions.js
103 lines (93 loc) · 2.83 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
import { post } from '../services/api/http';
import { login, saveToken, deleteToken } from '../services/api/auth';
import { getMyself } from '../services/api/user';
import * as mutations from './mutations';
import { mapDrive } from './helpers';
import { i18n } from '../main';
import {
actions as apiActions,
namespaces,
SYNC,
SYNC_ITEM_SUCCESS,
SYNC_ITEM_FAILURE,
UNSYNCHRONISED_DRIVES,
} from './constants';
export const FETCH_USER = 'FETCH_USER';
export const LOGIN = 'LOGIN';
export const LOGOUT = 'LOGOUT';
export const SUBMIT = 'SUBMIT';
export const SWITCH_LANGUAGE = 'SWITCH_LANGUAGE';
export const actions = {
[FETCH_USER]({ dispatch, commit }, { callback } = {}) {
getMyself().then((user) => {
commit(mutations.SET_USER, user);
dispatch(`${namespaces.passengers}/${apiActions.fetchPassengers}`);
dispatch(`${namespaces.cars}/${apiActions.fetchCars}`);
dispatch(`${namespaces.drives}/${apiActions.fetchDrives}`);
dispatch(`${namespaces.projects}/${apiActions.fetchProjects}`);
if (callback) {
callback();
}
});
},
[LOGIN]({ commit, dispatch }, { username, password }) {
commit(mutations.SET_LOGIN_PROGRESS, true);
login(username, password)
.then((token) => {
commit(mutations.SET_LOGIN_ERROR, null);
saveToken(token);
dispatch(FETCH_USER, {
callback: () => window.location.replace('/drive'),
});
})
.catch(() => {
commit(mutations.SET_LOGIN_ERROR, i18n.tc('login.login_error'));
})
.finally(() => {
commit(mutations.SET_LOGIN_PROGRESS, false);
});
},
[LOGOUT]({ commit }) {
commit(mutations.SET_USER, null);
deleteToken();
window.location.replace('/logout_success');
},
[SUBMIT]({ commit, dispatch }, { form }) {
commit(mutations.ADD_DRIVE, form);
dispatch(SYNC);
},
[SWITCH_LANGUAGE]({ commit }, language) {
commit(mutations.SET_LANG, language);
i18n.locale = language;
},
async [SYNC]({ dispatch, state, commit }) {
if (state[UNSYNCHRONISED_DRIVES].length === 0 && state.user) {
dispatch(`${namespaces.drives}/${apiActions.fetchDrives}`);
return;
}
if (
state[UNSYNCHRONISED_DRIVES].length === 0 ||
!state.user ||
!navigator.onLine
) {
return;
}
const mappedDrive = mapDrive(state[UNSYNCHRONISED_DRIVES][0]);
const { timestamp } = mappedDrive;
try {
await post('drives', mappedDrive);
commit(SYNC_ITEM_SUCCESS, timestamp);
} catch (e) {
if (e.response && e.response.status === 409) {
// was synced previously
commit(SYNC_ITEM_SUCCESS, timestamp);
} else if (
e.response &&
(e.response.status === 400 || e.response.status === 500)
) {
commit(SYNC_ITEM_FAILURE, timestamp);
}
}
dispatch(SYNC);
},
};