|
@@ -1,41 +1,43 @@
|
|
|
import { actionIsLoading } from '../../loading/action';
|
|
|
-
|
|
|
import {
|
|
|
actionLogInSuccess,
|
|
|
actionLogInReject,
|
|
|
actionLogOutSuccess,
|
|
|
actionLogOutReject,
|
|
|
+ actionCurrentSuccess,
|
|
|
+ actionCurrentReject
|
|
|
} from '../action';
|
|
|
+import { setToken, loginUser, updateCredentials, updateUserAvatar, currentUser } from '../../../api-data';
|
|
|
+import { IAuthorizationState } from '../../../typescript/redux/authorization/interfaces'
|
|
|
+import { TResPromiseAll } from '../../../typescript/redux/authorization/types'
|
|
|
|
|
|
-import { setToken, loginUser,updateCredentials,updateUserAvatar } from '../../../api-data';
|
|
|
-
|
|
|
-const asyncCreateUser = (name:string, lastName: string,file:any) => async (dispatch:any) => {
|
|
|
+const asyncCreateUser = (name:string, lastName: string,file:object) => async (dispatch:any) => {
|
|
|
try {
|
|
|
dispatch(actionIsLoading(true));
|
|
|
const reader: any = new FileReader()
|
|
|
const formData:any = new FormData()
|
|
|
reader.onload = async () => {
|
|
|
formData.append("avatar", file);
|
|
|
- const data = await Promise.all([updateUserAvatar(formData), updateCredentials(name, lastName)])
|
|
|
- const res = data.find(el => el.token)
|
|
|
- res?.token&&dispatch(actionLogInSuccess(res.token))
|
|
|
+ const data = await Promise.all<TResPromiseAll>(
|
|
|
+ [updateUserAvatar(formData), updateCredentials(name, lastName)])
|
|
|
+ const token = data.find(el => el?.token)?.token
|
|
|
+ token&&dispatch(actionLogInSuccess(token))
|
|
|
}
|
|
|
await reader.readAsArrayBuffer(file)
|
|
|
} catch (e) {
|
|
|
- console.log(e)
|
|
|
+ dispatch(actionLogInReject())
|
|
|
} finally {
|
|
|
dispatch(actionIsLoading(false));
|
|
|
}
|
|
|
};
|
|
|
|
|
|
-
|
|
|
-
|
|
|
const asyncLogin = (number:string, code: string,cb:() => void ) => async (dispatch:any) => {
|
|
|
try {
|
|
|
dispatch(actionIsLoading(true));
|
|
|
const data = await loginUser<{ token: string, registered: boolean }>(number, code);
|
|
|
const token = data?.token
|
|
|
const registered = data?.registered
|
|
|
+ console.log(token,registered)
|
|
|
if (!token) return
|
|
|
setToken.set(token)
|
|
|
if (!registered) return cb()
|
|
@@ -60,6 +62,17 @@ const asyncLogout = () => async (dispatch:any) => {
|
|
|
}
|
|
|
};
|
|
|
|
|
|
+const asyncCurrentUser = () => async (dispatch:any) => {
|
|
|
+ try {
|
|
|
+ dispatch(actionIsLoading(true));
|
|
|
+ const data = await currentUser<IAuthorizationState>()
|
|
|
+ data && dispatch(actionCurrentSuccess(data));
|
|
|
+ if(!data?.token) throw new Error('old token')
|
|
|
+ } catch (e) {
|
|
|
+ dispatch(actionCurrentReject());
|
|
|
+ } finally {
|
|
|
+ dispatch(actionIsLoading(false));
|
|
|
+ }
|
|
|
+};
|
|
|
|
|
|
-
|
|
|
-export { asyncCreateUser, asyncLogin, asyncLogout };
|
|
|
+export { asyncCreateUser, asyncLogin, asyncLogout, asyncCurrentUser };
|