friendStore.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import {defineStore} from "pinia";
  2. import FriendApi from "@/api/FriendApi";
  3. import type Friend from "@/mode/Friend";
  4. import type User from "@/mode/User";
  5. import SendCode from '@/utils/SendCode'
  6. import {useUserStore} from '@/store/userStore'
  7. import ChatType from '@/utils/ChatType'
  8. import MessageType from '@/utils/MessageType'
  9. import {useWsStore} from '@/store/WsStore'
  10. export interface State {
  11. friendList: User[];
  12. waitValidateList: Friend[];
  13. }
  14. export const useFriendStore = defineStore({
  15. id: "friend_store",
  16. state: (): State => ({
  17. friendList: [],
  18. waitValidateList:[]
  19. }),
  20. actions: {
  21. loadData() {
  22. const userStore = useUserStore()
  23. FriendApi.friends().then((res) => {
  24. this.friendList = res.data
  25. //缓存好友,用于聊天时头像名称显示
  26. res.data.forEach((item: User) => {
  27. userStore.storeUser(item.id, {
  28. name: item.name,
  29. avatar: item.avatar
  30. })
  31. })
  32. })
  33. },
  34. loadValidateList() {
  35. FriendApi.validateList().then((res) => {
  36. console.log(res);
  37. this.waitValidateList = res.data;
  38. });
  39. },
  40. /**
  41. * 告诉对方需要刷新store
  42. * @param userId 对方id
  43. */
  44. notifyFlushFriendStore(userId: string) {
  45. const fromId = useUserStore().getUser()?.id
  46. if (fromId) {
  47. const sendInfo = {
  48. code: SendCode.NEW_FRIEND,
  49. message: {
  50. mine: true,
  51. fromId: fromId,
  52. chatId: userId,
  53. type: ChatType.FRIEND,
  54. messageType: MessageType.text,
  55. content: '',
  56. timestamp: new Date().getTime()
  57. }
  58. }
  59. useWsStore().send(JSON.stringify(sendInfo))
  60. }
  61. }
  62. },
  63. });