Browse Source

msgReduser

sheva77 3 years ago
parent
commit
562299dc2d

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

@@ -32,6 +32,7 @@ export const actionUserInfo = (userId) => async (dispatch) => {
                                 _id
                                 _id
                                 title
                                 title
                                 avatar {url}
                                 avatar {url}
+                                members{_id login nick avatar{url}}
                                 }
                                 }
                         }
                         }
                     }`,
                     }`,

+ 16 - 15
chat_final_bootstrap/src/Actions/ActionsGql.js

@@ -2,6 +2,7 @@
 
 
 import { urlConst } from "../const";
 import { urlConst } from "../const";
 import { actionPromise } from "../Reducers";
 import { actionPromise } from "../Reducers";
+import { actionMsgAdd } from "../Actions";
 
 
 const getGQL = (url) => (query, variables = {}) => {
 const getGQL = (url) => (query, variables = {}) => {
     return fetch(url, {
     return fetch(url, {
@@ -27,16 +28,16 @@ const toQuery = (str, fields = ["title", "text"]) => {
     return { $or: arr };
     return { $or: arr };
 };
 };
 
 
-export const actionSearchMessagesByChatId = (_chatId, str) => async (dispatch) => {
-    let searchStr;
+export const actionSearchMessagesByChatId = (_chatId, skip = 0, limit = 10, str = "") => async (dispatch) => {
+    let searchObj;
     str = toQuery(str);
     str = toQuery(str);
 
 
     if (_chatId) {
     if (_chatId) {
-        searchStr = { $and: [{ "chat._id": _chatId }] };
-        searchStr.$and.push(str);
-    } else searchStr = { str };
+        searchObj = { $and: [{ "chat._id": _chatId }] };
+        searchObj.$and.push(str);
+    } else searchObj = { str };
 
 
-    let ChatFindOne = await dispatch(
+    let messages = await dispatch(
         actionPromise(
         actionPromise(
             "MessageFind",
             "MessageFind",
             gql(
             gql(
@@ -59,11 +60,15 @@ export const actionSearchMessagesByChatId = (_chatId, str) => async (dispatch) =
                         }
                         }
                     }
                     }
                 }`,
                 }`,
-                { searchMsgStr: JSON.stringify([searchStr, { sort: [{ _id: 1 }] }]) }
+                { searchMsgStr: JSON.stringify([searchObj, { sort: [{ _id: -1 }], skip: [skip], limit: [limit] }]) }
             )
             )
         )
         )
     );
     );
-    // console.log("actionFindMessagesByChatId result: ", ChatFindOne);
+    // console.log("actionFindMessagesByChatId result: ", messages);
+
+    if (messages && messages.data && messages.data.MessageFind && messages.data.MessageFind.length) {
+        dispatch(actionMsgAdd(messages.data.MessageFind.reverse()));
+    }
 };
 };
 
 
 // получить все сообщения из чата с такм-то _id
 // получить все сообщения из чата с такм-то _id
@@ -77,9 +82,7 @@ export const actionGetMessagesByChatId = (_chatId) => async (dispatch) => {
                         _id
                         _id
                         title
                         title
                         createdAt
                         createdAt
-                        members {
-                            login
-                        }
+                        members {login}
                         messages {
                         messages {
                             _id
                             _id
                             createdAt
                             createdAt
@@ -89,16 +92,14 @@ export const actionGetMessagesByChatId = (_chatId) => async (dispatch) => {
                             }
                             }
                             text
                             text
                         }
                         }
-                        avatar {
-                            url
-                        }
+                        avatar {url}
                     }
                     }
                     }`,
                     }`,
                 { chatId: JSON.stringify([{ _id: _chatId }, { sort: [{ _id: 1 }] }]) }
                 { chatId: JSON.stringify([{ _id: _chatId }, { sort: [{ _id: 1 }] }]) }
             )
             )
         )
         )
     );
     );
-    // console.log("actionGetMessagesByChatId");
+    console.log("actionGetMessagesByChatId");
 };
 };
 
 
 export const actionSearchChat = (_userId = "", str = "") => async (dispatch) => {
 export const actionSearchChat = (_userId = "", str = "") => async (dispatch) => {

+ 4 - 0
chat_final_bootstrap/src/Actions/ActionsMsg.js

@@ -0,0 +1,4 @@
+export const actionMsgAdd = (msgArr) => {
+    // console.log("actionMsgAdd - ", JSON.stringify(msgArr, null, 4));
+    return { type: "ADDMSG", msgs: { [msgArr[0].chat._id]: msgArr } };
+};

+ 2 - 0
chat_final_bootstrap/src/Actions/index.js

@@ -1,5 +1,6 @@
 import { actionAuthLogin, actionAuthLogout, actionLogin, actionRegistration, actionUserInfo } from "./ActionLogin";
 import { actionAuthLogin, actionAuthLogout, actionLogin, actionRegistration, actionUserInfo } from "./ActionLogin";
 import { gql, actionSearchMessagesByChatId, actionGetMessagesByChatId, actionSearchChat } from "./ActionsGql";
 import { gql, actionSearchMessagesByChatId, actionGetMessagesByChatId, actionSearchChat } from "./ActionsGql";
+import { actionMsgAdd } from "./ActionsMsg";
 
 
 export {
 export {
     actionUserInfo,
     actionUserInfo,
@@ -11,4 +12,5 @@ export {
     actionGetMessagesByChatId,
     actionGetMessagesByChatId,
     actionSearchChat,
     actionSearchChat,
     actionSearchMessagesByChatId,
     actionSearchMessagesByChatId,
+    actionMsgAdd,
 };
 };

+ 43 - 29
chat_final_bootstrap/src/Components/ChatContain.js

@@ -32,7 +32,6 @@ const MessageItem = ({
     // date.getSeconds().toString().padStart(2, 0);
     // date.getSeconds().toString().padStart(2, 0);
 
 
     return (
     return (
-        // <div className="list-group-item list-group-item-success m-2 gradient shadow-sm border-2">
         <div
         <div
             className={`messageItem list-group-item m-2 gradient shadow-sm border-2 ${
             className={`messageItem list-group-item m-2 gradient shadow-sm border-2 ${
                 myId === ownerId ? "start-right list-group-item-success text-success" : " list-group-item-light"
                 myId === ownerId ? "start-right list-group-item-success text-success" : " list-group-item-light"
@@ -77,9 +76,11 @@ const MessageItem = ({
     );
     );
 };
 };
 
 
-const MessagesList = ({ arrayOfMessages, myId }) => {
+const MessagesList = ({ messages, myId, chatId }) => {
     const messagesEndRef = useRef(null); // указатель на пустой div  в коце сообщений для перемотки
     const messagesEndRef = useRef(null); // указатель на пустой div  в коце сообщений для перемотки
 
 
+    let arrayOfMessages = messages[chatId];
+
     // скролл в самый низ при приходе новых сообщений
     // скролл в самый низ при приходе новых сообщений
     const scrollToBottom = () => messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
     const scrollToBottom = () => messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
 
 
@@ -106,18 +107,26 @@ const MessagesList = ({ arrayOfMessages, myId }) => {
 
 
 const CMessagesList = connect(
 const CMessagesList = connect(
     (s) => ({
     (s) => ({
-        arrayOfMessages:
+        //FIXME: приконнектить массив сообщений
+        chatId:
             s.promise.MessageFind &&
             s.promise.MessageFind &&
             s.promise.MessageFind.payload &&
             s.promise.MessageFind.payload &&
             s.promise.MessageFind.payload.data &&
             s.promise.MessageFind.payload.data &&
-            s.promise.MessageFind.payload.data.MessageFind,
+            s.promise.MessageFind.payload.data.MessageFind &&
+            s.promise.MessageFind.payload.data.MessageFind[0] &&
+            s.promise.MessageFind.payload.data.MessageFind[0].chat &&
+            s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
+        messages: s.msg,
         myId: s.auth && s.auth.payloadId,
         myId: s.auth && s.auth.payloadId,
     }),
     }),
     {}
     {}
 )(MessagesList);
 )(MessagesList);
 
 
-const Messages = ({ avatar, _id = "", title = "No Title", getMsg }) => {
-    // id чата, аватар чата
+const Messages = ({ _id = "", messages, getMsg }) => {
+    // id чата,
+
+    let avatar = messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat.avatar;
+    let title = messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat.title;
 
 
     useEffect(() => {
     useEffect(() => {
         if (typeof doSearchMsg === "function") getMsg(_id);
         if (typeof doSearchMsg === "function") getMsg(_id);
@@ -172,29 +181,34 @@ const CMessages = connect(
     (s) => ({
     (s) => ({
         //id чата
         //id чата
         _id:
         _id:
-            s.promise.chatFindOne &&
-            s.promise.chatFindOne.payload &&
-            s.promise.chatFindOne.payload.data &&
-            s.promise.chatFindOne.payload.data.ChatFindOne &&
-            s.promise.chatFindOne.payload.data.ChatFindOne._id,
-        arrayOfMessages:
-            s.promise.chatFindOne &&
-            s.promise.chatFindOne.payload &&
-            s.promise.chatFindOne.payload.data &&
-            s.promise.chatFindOne.payload.data.ChatFindOne &&
-            s.promise.chatFindOne.payload.data.ChatFindOne.messages,
-        avatar:
-            s.promise.chatFindOne &&
-            s.promise.chatFindOne.payload &&
-            s.promise.chatFindOne.payload.data &&
-            s.promise.chatFindOne.payload.data.ChatFindOne &&
-            s.promise.chatFindOne.payload.data.ChatFindOne.avatar,
-        title:
-            s.promise.chatFindOne &&
-            s.promise.chatFindOne.payload &&
-            s.promise.chatFindOne.payload.data &&
-            s.promise.chatFindOne.payload.data.ChatFindOne &&
-            s.promise.chatFindOne.payload.data.ChatFindOne.title,
+            s.promise.MessageFind &&
+            s.promise.MessageFind.payload &&
+            s.promise.MessageFind.payload.data &&
+            s.promise.MessageFind.payload.data.MessageFind &&
+            s.promise.MessageFind.payload.data.MessageFind[0] &&
+            s.promise.MessageFind.payload.data.MessageFind[0].chat &&
+            s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
+        messages: s.msg,
+        //     s.promise.chatFindOne.payload &&
+        //     s.promise.chatFindOne.payload.data &&
+        //     s.promise.chatFindOne.payload.data.ChatFindOne &&
+        //     s.promise.chatFindOne.payload.data.ChatFindOne.messages,
+        // avatar:
+        //     s.promise.MessageFind &&
+        //     s.promise.MessageFind.payload &&
+        //     s.promise.MessageFind.payload.data &&
+        //     s.promise.MessageFind.payload.data.MessageFind &&
+        //     s.promise.MessageFind.payload.data.MessageFind[0] &&
+        //     s.promise.MessageFind.payload.data.MessageFind[0].chat &&
+        //     s.promise.MessageFind.payload.data.MessageFind[0].chat.avatar,
+        // title:
+        //     s.promise.MessageFind &&
+        //     s.promise.MessageFind.payload &&
+        //     s.promise.MessageFind.payload.data &&
+        //     s.promise.MessageFind.payload.data.MessageFind &&
+        //     s.promise.MessageFind.payload.data.MessageFind[0] &&
+        //     s.promise.MessageFind.payload.data.MessageFind[0].chat &&
+        //     s.promise.MessageFind.payload.data.MessageFind[0].chat.title,
     }),
     }),
     { getMsg: actionGetMessagesByChatId }
     { getMsg: actionGetMessagesByChatId }
 )(Messages);
 )(Messages);

+ 12 - 6
chat_final_bootstrap/src/Components/ChatsList.js

@@ -5,6 +5,8 @@ import { Link } from "react-router-dom";
 import { Counter } from "../Components";
 import { Counter } from "../Components";
 import personFillIcon from "../icons/person-fill.svg";
 import personFillIcon from "../icons/person-fill.svg";
 import history from "../history";
 import history from "../history";
+import { useEffect } from "react";
+import { useState } from "react";
 
 
 const CCounter = connect;
 const CCounter = connect;
 
 
@@ -52,7 +54,7 @@ const ChatItem = ({ _id = "", avatar, title, messages, userId, currentChatId })
                         {Counter(_id)}
                         {Counter(_id)}
                         <span className="visually-hidden">всего сообщений</span>
                         <span className="visually-hidden">всего сообщений</span>
                     </span>
                     </span>
-                    {/* <span className="text-nowrap"> chatID: {_id}</span> */}
+                    <span className="text-nowrap"> chatID: {_id}</span>
                 </li>
                 </li>
             </>
             </>
         </Link>
         </Link>
@@ -97,12 +99,16 @@ const List = ({ arrayOfChats, userId, currentChatId }) => {
 
 
 const CList = connect((s) => ({
 const CList = connect((s) => ({
     currentChatId:
     currentChatId:
-        s.promise.chatFindOne &&
-        s.promise.chatFindOne.payload &&
-        s.promise.chatFindOne.payload.data &&
-        s.promise.chatFindOne.payload.data.ChatFindOne &&
-        s.promise.chatFindOne.payload.data.ChatFindOne._id,
+        s.promise &&
+        s.promise.MessageFind &&
+        s.promise.MessageFind.payload &&
+        s.promise.MessageFind.payload.data &&
+        s.promise.MessageFind.payload.data.MessageFind &&
+        s.promise.MessageFind.payload.data.MessageFind[0] &&
+        s.promise.MessageFind.payload.data.MessageFind[0].chat &&
+        s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
 
 
+    //FIXME: для сортировки надо подсоеденить правильный массив
     arrayOfChats: s.auth && s.auth.chats,
     arrayOfChats: s.auth && s.auth.chats,
 
 
     userId: s.auth && s.auth.payloadId,
     userId: s.auth && s.auth.payloadId,

+ 9 - 7
chat_final_bootstrap/src/Layout/Sidebar.js

@@ -1,10 +1,12 @@
 import { CUserInfo } from "../Layout";
 import { CUserInfo } from "../Layout";
 import { CAdditionalTools, ChatsList } from "../Components";
 import { CAdditionalTools, ChatsList } from "../Components";
 
 
-export const Sidebar = () => (
-    <aside className="Sidebar">
-        <CUserInfo />
-        <CAdditionalTools />
-        <ChatsList className="ChatsList" />
-    </aside>
-);
+export const Sidebar = () => {
+    return (
+        <aside className="Sidebar">
+            <CUserInfo />
+            <CAdditionalTools />
+            <ChatsList className="ChatsList" />
+        </aside>
+    );
+};

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

@@ -2,7 +2,7 @@ import { ChatContain } from "../Components";
 import { Sidebar } from "../Layout";
 import { Sidebar } from "../Layout";
 import { store } from "../Reducers";
 import { store } from "../Reducers";
 import history from "../history";
 import history from "../history";
-import { actionGetMessagesByChatId, actionSearchChat } from "../Actions";
+import { actionGetMessagesByChatId, actionSearchChat, actionSearchMessagesByChatId } from "../Actions";
 import { connect } from "react-redux";
 import { connect } from "react-redux";
 import { useState, useEffect } from "react";
 import { useState, useEffect } from "react";
 
 
@@ -43,7 +43,7 @@ const PageMain = ({
             <div className="row g-3">
             <div className="row g-3">
                 <div className="col-md-4">
                 <div className="col-md-4">
                     {/* {_userId + ` - подмена id`} */}
                     {/* {_userId + ` - подмена id`} */}
-                    <Sidebar />
+                    <Sidebar/>
                 </div>
                 </div>
                 <div className="col-md-8">
                 <div className="col-md-8">
                     <ChatContain _chatId={_chatId} />
                     <ChatContain _chatId={_chatId} />
@@ -56,5 +56,5 @@ const PageMain = ({
 // prettier-ignore
 // prettier-ignore
 export const CPageMain = connect((s) => ({ _userId: s.auth && s.auth.payloadId }), {
 export const CPageMain = connect((s) => ({ _userId: s.auth && s.auth.payloadId }), {
     // getChatList: actionSearchChat,
     // getChatList: actionSearchChat,
-    getMesagesList: actionGetMessagesByChatId,
+    getMesagesList: actionSearchMessagesByChatId,
 })(PageMain);
 })(PageMain);

+ 9 - 8
chat_final_bootstrap/src/Reducers/index.js

@@ -55,6 +55,14 @@ function authReducer(state, action) {
     return state;
     return state;
 }
 }
 
 
+function msgReduser(state = {}, action) {
+    if (["LOGOUT", "LOGIN"].includes(action.type)) return {}; // кликнули по новому чату в sideBar
+    if (action.type === "ADDMSG") {
+        return { ...state, ...action.msgs };
+    }
+    return state;
+}
+
 function promiseReducer(state = {}, action) {
 function promiseReducer(state = {}, action) {
     if (["LOGOUT", "LOGIN"].includes(action.type)) return {};
     if (["LOGOUT", "LOGIN"].includes(action.type)) return {};
     if (action.type === "PROMISE") {
     if (action.type === "PROMISE") {
@@ -73,13 +81,6 @@ function promiseReducer(state = {}, action) {
     return state;
     return state;
 }
 }
 
 
-function messagesReduser(state = {}, action) {
-    if (["LOGOUT", "LOGIN"].includes(action.type)) return {};
-    if (action.type === "ADDMSG") {
-    }
-    return state;
-}
-
 export const actionPromise = (name, promise) => {
 export const actionPromise = (name, promise) => {
     const actionPending = () => ({ type: "PROMISE", name, status: "PENDING", payload: null, error: null });
     const actionPending = () => ({ type: "PROMISE", name, status: "PENDING", payload: null, error: null });
     const actionResolved = (payload) => ({ type: "PROMISE", name, status: "RESOLVED", payload, error: null });
     const actionResolved = (payload) => ({ type: "PROMISE", name, status: "RESOLVED", payload, error: null });
@@ -99,7 +100,7 @@ export const actionPromise = (name, promise) => {
 };
 };
 
 
 export const store = createStore(
 export const store = createStore(
-    combineReducers({ auth: authReducer, promise: promiseReducer }),
+    combineReducers({ auth: authReducer, promise: promiseReducer, msg: msgReduser }),
     applyMiddleware(thunk)
     applyMiddleware(thunk)
 );
 );