actionsForUser.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { gql } from "../helpers/gql";
  2. import { actionAboutMe } from "./actionAboutMe";
  3. import { actionLeftChat, actionUpdateChat } from "./actionsForChats";
  4. import { actionPromise } from "./actionsPromise";
  5. export const actionFindUser = (value) =>
  6. actionPromise('usersList', gql(`query findUser($q: String) {
  7. UserFind(query: $q) {
  8. login
  9. _id
  10. nick
  11. avatar {
  12. _id
  13. url
  14. }
  15. }
  16. }`,{
  17. q: JSON.stringify([
  18. {
  19. $or : [{nick: `/${value}/`}]
  20. },
  21. {
  22. sort : [{login: 1}]
  23. }
  24. ])
  25. } ))
  26. export const actionUpdateUser = (user) =>
  27. actionPromise('updateUser', gql(`mutation leaveChatByUser($user: UserInput) {
  28. UserUpsert(user: $user) {
  29. login
  30. chats {
  31. title
  32. }
  33. }
  34. }`, {user: user}));
  35. export const actionUpsertUser = (login, nick, password, chatId) =>
  36. async (dispatch, getState) => {
  37. const state = getState();
  38. const currUserId = state.auth?.payload?.sub?.id;
  39. //remove chat from chats array
  40. const chats = chatId ? Object.values(state.chats).filter(chat => chat._id !== chatId).map(chat => {
  41. let {_id} = chat;
  42. //return only id
  43. return {"_id": _id}
  44. })
  45. : null;
  46. const user = Object.fromEntries(Object.entries({_id: currUserId, login, nick, password, chats}).filter(([_, v]) => v != null));
  47. const res = await dispatch(actionUpdateUser(user));
  48. (res && chatId) ?
  49. //actionUpdateChat doesn't work, but it helps to everyone members from the chat to get callback from socket,
  50. // because userUpsert doesn't work from socket
  51. (dispatch(actionLeftChat(state.chats[chatId])) && dispatch(actionUpdateChat({_id: chatId, title: state.chats[chatId].title}))) :
  52. dispatch(actionAboutMe());
  53. }