UNPKG

2.61 kBJavaScriptView Raw
1import { polyfill } from 'es6-promise';
2import request from 'axios';
3import { push } from 'react-router-redux';
4
5import * as types from '../types';
6
7polyfill();
8
9const getMessage = res => res.response && res.response.data && res.response.data.message;
10
11function makeUserRequest(method, data, api = '/login') {
12 return request[method](api, data);
13}
14
15
16// Log In Action Creators
17export function beginLogin() {
18 return { type: types.MANUAL_LOGIN_USER };
19}
20
21export function loginSuccess(message) {
22 return {
23 type: types.LOGIN_SUCCESS_USER,
24 message
25 };
26}
27
28export function loginError(message) {
29 return {
30 type: types.LOGIN_ERROR_USER,
31 message
32 };
33}
34
35// Sign Up Action Creators
36export function signUpError(message) {
37 return {
38 type: types.SIGNUP_ERROR_USER,
39 message
40 };
41}
42
43export function beginSignUp() {
44 return { type: types.SIGNUP_USER };
45}
46
47export function signUpSuccess(message) {
48 return {
49 type: types.SIGNUP_SUCCESS_USER,
50 message
51 };
52}
53
54// Log Out Action Creators
55export function beginLogout() {
56 return { type: types.LOGOUT_USER};
57}
58
59export function logoutSuccess() {
60 return { type: types.LOGOUT_SUCCESS_USER };
61}
62
63export function logoutError() {
64 return { type: types.LOGOUT_ERROR_USER };
65}
66
67export function toggleLoginMode() {
68 return { type: types.TOGGLE_LOGIN_MODE };
69}
70
71export function manualLogin(data) {
72 return (dispatch) => {
73 dispatch(beginLogin());
74
75 return makeUserRequest('post', data, '/login')
76 .then((response) => {
77 if (response.status === 200) {
78 dispatch(loginSuccess(response.data.message));
79 dispatch(push('/'));
80 } else {
81 dispatch(loginError('Oops! Something went wrong!'));
82 }
83 })
84 .catch((err) => {
85 dispatch(loginError(getMessage(err)));
86 });
87 };
88}
89
90export function signUp(data) {
91 return (dispatch) => {
92 dispatch(beginSignUp());
93
94 return makeUserRequest('post', data, '/signup')
95 .then((response) => {
96 if (response.status === 200) {
97 dispatch(signUpSuccess(response.data.message));
98 dispatch(push('/'));
99 } else {
100 dispatch(signUpError('Oops! Something went wrong'));
101 }
102 })
103 .catch((err) => {
104 dispatch(signUpError(getMessage(err)));
105 });
106 };
107}
108
109export function logOut() {
110 return (dispatch) => {
111 dispatch(beginLogout());
112
113 return makeUserRequest('post', null, '/logout')
114 .then((response) => {
115 if (response.status === 200) {
116 dispatch(logoutSuccess());
117 } else {
118 dispatch(logoutError());
119 }
120 });
121 };
122}