friendStore.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { defineStore } from 'pinia';
  2. import http from '../common/request'
  3. import { TERMINAL_TYPE } from '../common/enums.js'
  4. export default defineStore('friendStore', {
  5. state: () => {
  6. return {
  7. friends: [],
  8. timer: null
  9. }
  10. },
  11. actions: {
  12. setFriends(friends) {
  13. friends.forEach((f) => {
  14. f.online = false;
  15. f.onlineWeb = false;
  16. f.onlineApp = false;
  17. })
  18. this.friends = friends;
  19. },
  20. updateFriend(friend) {
  21. this.friends.forEach((f, index) => {
  22. if (f.id == friend.id) {
  23. // 拷贝属性
  24. let online = this.friends[index].online;
  25. Object.assign(this.friends[index], friend);
  26. this.friends[index].online = online;
  27. }
  28. })
  29. },
  30. removeFriend(id) {
  31. this.friends.forEach((f, idx) => {
  32. if (f.id == id) {
  33. this.friends.splice(idx, 1)
  34. }
  35. })
  36. },
  37. addFriend(friend) {
  38. this.friends.push(friend);
  39. },
  40. setOnlineStatus(onlineTerminals) {
  41. this.friends.forEach((f) => {
  42. let userTerminal = onlineTerminals.find((o) => f.id == o.userId);
  43. if (userTerminal) {
  44. f.online = true;
  45. f.onlineWeb = userTerminal.terminals.indexOf(TERMINAL_TYPE.WEB) >= 0
  46. f.onlineApp = userTerminal.terminals.indexOf(TERMINAL_TYPE.APP) >= 0
  47. } else {
  48. f.online = false;
  49. f.onlineWeb = false;
  50. f.onlineApp = false;
  51. }
  52. });
  53. },
  54. refreshOnlineStatus() {
  55. if (this.friends.length > 0) {
  56. let userIds = [];
  57. this.friends.forEach(f => userIds.push(f.id));
  58. http({
  59. url: '/user/terminal/online?userIds=' + userIds.join(','),
  60. method: 'GET'
  61. }).then((onlineTerminals) => {
  62. this.setOnlineStatus(onlineTerminals);
  63. })
  64. }
  65. // 30s后重新拉取
  66. clearTimeout(this.timer);
  67. this.timer = setTimeout(() => {
  68. this.refreshOnlineStatus();
  69. }, 30000)
  70. },
  71. clear() {
  72. clearTimeout(this.timer);
  73. this.friends = [];
  74. this.timer = null;
  75. },
  76. loadFriend() {
  77. return new Promise((resolve, reject) => {
  78. http({
  79. url: '/friend/list',
  80. method: 'GET'
  81. }).then((friends) => {
  82. this.setFriends(friends);
  83. this.refreshOnlineStatus();
  84. resolve()
  85. }).catch((res) => {
  86. reject();
  87. })
  88. });
  89. }
  90. },
  91. getters: {
  92. findFriend: (state) => (id) => {
  93. return state.friends.find((f) => f.id == id);
  94. }
  95. }
  96. })