Pārlūkot izejas kodu

update user info after chatUpsert

sheva77 3 gadi atpakaļ
vecāks
revīzija
9a83508759

+ 1 - 0
chat_final_bootstrap/src/Actions/ActionLogin.js

@@ -17,6 +17,7 @@ export const actionAuthInfo = ({ login, nick, _id, avatar, chats = [] }) => {
     return { type: "INFO", userInfo: { login, nick, _id, url, chats } };
 };
 
+// получить дополнительную более полную инфу о пользователе
 export const actionUserInfo = (userId) => async (dispatch) => {
     // console.log("actionUserInfo - ########### ", userId);
     let userData = await dispatch(

+ 22 - 19
chat_final_bootstrap/src/Actions/ActionsGqlUpsert.js

@@ -2,10 +2,11 @@
 //
 import { urlUploadConst } from "../const";
 import { actionPromise } from "../Reducers";
-import { gql, actionSearchMessagesByChatId } from "../Actions";
+import { gql, actionSearchMessagesByChatId, actionUserInfo } from "../Actions";
+import history from "../history";
 
 export const actionMessageUpsert = ({ text, chatId }) => async (dispatch) => {
-    console.log("actionMessageUpsert --- ", text, chatId);
+    // console.log("actionMessageUpsert --- ", text, chatId);
 
     let msgData = await dispatch(
         actionPromise(
@@ -21,10 +22,9 @@ export const actionMessageUpsert = ({ text, chatId }) => async (dispatch) => {
         )
     );
 
-    console.log("MessageUpsert - ", msgData);
+    // console.log("MessageUpsert - ", msgData);
 
     if (msgData && msgData.data && msgData.data.MessageUpsert && msgData.data.MessageUpsert._id) {
-        console.log("MessageUpsert - ", msgData);
         dispatch(actionSearchMessagesByChatId(chatId));
     }
 };
@@ -71,21 +71,24 @@ export const actionCreateNewChat = ({ title, members, avaFile }) => async (dispa
         )
     );
 
-    if (avaFile) {
-        let dataSingl = new FormData();
-        dataSingl.set("media", avaFile);
-        let avaUploadResult = await fetch(`${urlUploadConst}/upload`, {
-            method: "POST",
-            headers: localStorage.authToken ? { Authorization: "Bearer " + localStorage.authToken } : {},
-            body: dataSingl,
-        }).then((res) => res.json());
+    // console.log("898989898 ---- ", chatData);
 
-        dispatch(actionMediaUpsert({ chatId: chatData.data.ChatUpsert._id, mediaId: avaUploadResult._id }));
-    }
+    if (chatData && chatData.data && chatData.data.ChatUpsert && chatData.data.ChatUpsert._id) {
+        if (avaFile) {
+            let dataSingl = new FormData();
+            dataSingl.set("media", avaFile);
+            let avaUploadResult = await fetch(`${urlUploadConst}/upload`, {
+                method: "POST",
+                headers: localStorage.authToken ? { Authorization: "Bearer " + localStorage.authToken } : {},
+                body: dataSingl,
+            }).then((res) => res.json());
+
+            dispatch(actionMediaUpsert({ chatId: chatData.data.ChatUpsert._id, mediaId: avaUploadResult._id }));
+        }
 
-    // if (userData && userData.data.UserFindOne) {
-    //     dispatch(actionAuthInfo(userData.data.UserFindOne));
-    // } else {
-    //     console.log("UserFindOne - ошибка");
-    // }
+        // обновить списки моих чатов
+        await dispatch(actionUserInfo(members[0]._id));
+
+        history.push(`/main/${chatData.data.ChatUpsert._id}`);
+    }
 };

+ 1 - 1
chat_final_bootstrap/src/Components/AdditionalTools.js

@@ -32,7 +32,7 @@ export const AdditionalTools = ({ _userId, onSearch = null }) => {
                     history.push("/newchat");
                 }}
             >
-                <i class="bi bi-chat-left-text"></i> New Chat
+                <i className="bi bi-chat-left-text"></i> New Chat
             </Button>
             {/* <Button className="gradient" variant="secondary btn-sm  m-2">
                 Join to another chat

+ 1 - 1
chat_final_bootstrap/src/Components/ButtonLogout.js

@@ -4,7 +4,7 @@ import { Button } from "react-bootstrap";
 
 const ButtonLogout = ({ onLogout, isLoggedIn }) => (
     <Button className="gradient" variant="secondary btn-sm" onClick={onLogout} disabled={!isLoggedIn}>
-        <i class="bi bi-door-open"></i> Logout
+        <i className="bi bi-door-open"></i> Logout
     </Button>
 );
 export const CButtonLogout = connect((s) => ({ isLoggedIn: s.auth.login }), { onLogout: actionAuthLogout })(

+ 2 - 2
chat_final_bootstrap/src/Components/ChatsList.js

@@ -21,8 +21,8 @@ const ChatItem = ({ _id = "", avatar, title, messages, userId, currentChatId })
                 <li
                     className={
                         _id === currentChatId
-                            ? "list-group-item list-group-item-success m-1 gradient shadow border-2"
-                            : "list-group-item list-group-item-light m-1 gradient shadow-sm border-2"
+                            ? "list-group-item list-group-item-success m-1 gradient shadow border-2 rounded-pill"
+                            : "list-group-item list-group-item-light m-1 gradient shadow-sm border-2 rounded-3"
                     }
                 >
                     <div className="d-flex justify-content-start align-items-center">

+ 8 - 18
chat_final_bootstrap/src/Components/NewChatDashBoard.js

@@ -56,11 +56,13 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
     }, [members]);
 
     const doCreateNewChat = () => {
-        createNewChat({
-            title: inpTitle,
-            members: chatMembers,
-            avaFile: uploadRef.current && uploadRef.current.files && uploadRef.current.files[0],
-        });
+        if (typeof createNewChat === "function") {
+            createNewChat({
+                title: inpTitle,
+                members: chatMembers,
+                avaFile: uploadRef.current && uploadRef.current.files && uploadRef.current.files[0],
+            });
+        }
     };
 
     function previewFile() {
@@ -83,7 +85,7 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
     return (
         <>
             <div className="ChatDashBoard bg-light">
-                <h4>ChatDashBoard</h4>
+                <h5>New Chat:</h5>
                 <table className="table table-bordered align-middle">
                     <tbody>
                         <tr>
@@ -138,18 +140,6 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
                                     className="form-control form-control-sm m-2"
                                     aria-label="file example"
                                 />
-                                {/* <br />
-                                <img src={srcAva} height="200" alt="Image preview..." ref={uploadImgRef}></img> */}
-
-                                {/*  */}
-
-                                {/* <span className="avatarka">
-                                    <img
-                                        src={chat_square_text}
-                                        className="border border-2 border-success bg-light "
-                                        alt="Avatar"
-                                    />
-                                </span> */}
                             </td>
                         </tr>
                         <tr>

+ 8 - 3
chat_final_bootstrap/src/Layout/AllUsersList.js

@@ -47,6 +47,8 @@ const AllUsersConst = [
 
 const UserItem = ({ _id, login, nick, avatar, myId, addUserToList = null, delUserFromList = null, newChatUsers }) => {
     const avatarUrl = avatar && avatar.url;
+
+    // если нет ника, то берем логин
     nick = !!nick ? nick : login;
 
     const doSelectUser = () => {
@@ -67,8 +69,8 @@ const UserItem = ({ _id, login, nick, avatar, myId, addUserToList = null, delUse
         <>
             <li
                 className={`list-group-item list-group-item-${
-                    _id in newChatUsers || _id === myId ? "success" : "light"
-                } m-1 gradient shadow-sm border-2 `}
+                    _id in newChatUsers || _id === myId ? "success rounded-pill shadow" : "light rounded-3 shadow-sm"
+                } m-1 gradient border-2 `}
                 onClick={doSelectUser}
             >
                 <div className="d-flex justify-content-start align-items-center">
@@ -101,7 +103,7 @@ const UserItem = ({ _id, login, nick, avatar, myId, addUserToList = null, delUse
                 </div>
                 <span className="position-absolute bottom-0 end-0  badge rounded-pill bg-secondary">
                     {_id}
-                    <span className="visually-hidden">всего сообщений</span>
+                    <span className="visually-hidden">_id пользователя</span>
                 </span>
             </li>
         </>
@@ -139,6 +141,9 @@ const AllUsersList = ({
     // если из базы ничего еще не пришло по поиску пользователей,
     // то посмотрим на всех, с кeм мы вообще уже общались в чатах
 
+    // эта проверка нужна, так как если моих чатов нет, то из базы приходит null
+    if (!myChats) myChats = [];
+
     if (!searchUserStr || !searchUserResultArr) {
         let tempObj = {};
         for (let chat of myChats) {

+ 3 - 3
chat_final_bootstrap/src/Pages/PageMain.js

@@ -16,9 +16,9 @@ const MessageInput = ({ curChatId: { curChatId } = {}, messageUpsert }) => {
         // console.log(e);
     };
 
-    // отправка по Ctrl+Enter но не по Enter
+    // отправка по Enter
     const sendMsgByEnterKey = (e) => {
-        if (["NumpadEnter", "Enter"].includes(e.code) && e.ctrlKey && text.trim()) {
+        if (["NumpadEnter", "Enter"].includes(e.code) && text.trim()) {
             sendMsg();
         }
     };
@@ -51,7 +51,7 @@ const MessageInput = ({ curChatId: { curChatId } = {}, messageUpsert }) => {
                             role-button="true"
                             onClick={sendMsg}
                         >
-                            <i class="bi bi-chat-dots"></i> <i class="bi bi-reply-fill"></i>
+                            <i className="bi bi-chat-dots"></i> <i className="bi bi-reply-fill"></i>
                         </span>
                     </div>
                 </div>

+ 2 - 2
chat_final_bootstrap/src/Reducers/index.js

@@ -23,9 +23,9 @@ function authReducer(state, action) {
                 login: true,
                 token: action.jwt,
                 payload: jwt_decode(action.jwt).sub.login,
-                // payloadId: jwt_decode(action.jwt).sub.id,
+                payloadId: jwt_decode(action.jwt).sub.id,
                 //FIXME: отладочный _userId
-                payloadId: "5e97105693e2915e617c6fc1",
+                // payloadId: "5e97105693e2915e617c6fc1",
             };
         } catch (error) {
             console.log(error);