friendStore.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. let f = this.findFriend(friend.id);
  22. let copy = JSON.parse(JSON.stringify(f));
  23. Object.assign(f, friend);
  24. f.online = copy.online;
  25. f.onlineWeb = copy.onlineWeb;
  26. f.onlineApp = copy.onlineApp;
  27. },
  28. removeFriend(id) {
  29. this.friends.forEach((f, idx) => {
  30. if (f.id == id) {
  31. this.friends.splice(idx, 1)
  32. }
  33. })
  34. },
  35. addFriend(friend) {
  36. this.friends.push(friend);
  37. },
  38. setOnlineStatus(onlineTerminals) {
  39. this.friends.forEach((f) => {
  40. let userTerminal = onlineTerminals.find((o) => f.id == o.userId);
  41. if (userTerminal) {
  42. f.online = true;
  43. f.onlineWeb = userTerminal.terminals.indexOf(TERMINAL_TYPE.WEB) >= 0
  44. f.onlineApp = userTerminal.terminals.indexOf(TERMINAL_TYPE.APP) >= 0
  45. } else {
  46. f.online = false;
  47. f.onlineWeb = false;
  48. f.onlineApp = false;
  49. }
  50. });
  51. },
  52. refreshOnlineStatus() {
  53. if (this.friends.length > 0) {
  54. let userIds = [];
  55. this.friends.forEach(f => userIds.push(f.id));
  56. http({
  57. url: '/user/terminal/online?userIds=' + userIds.join(','),
  58. method: 'GET'
  59. }).then((onlineTerminals) => {
  60. this.setOnlineStatus(onlineTerminals);
  61. })
  62. }
  63. // 30s后重新拉取
  64. clearTimeout(this.timer);
  65. this.timer = setTimeout(() => {
  66. this.refreshOnlineStatus();
  67. }, 30000)
  68. },
  69. clear() {
  70. clearTimeout(this.timer);
  71. this.friends = [];
  72. this.timer = null;
  73. },
  74. loadFriend() {
  75. return new Promise((resolve, reject) => {
  76. http({
  77. url: '/friend/list',
  78. method: 'GET'
  79. }).then((friends) => {
  80. this.setFriends(friends);
  81. this.refreshOnlineStatus();
  82. resolve()
  83. }).catch((res) => {
  84. reject();
  85. })
  86. });
  87. }
  88. },
  89. getters: {
  90. findFriend: (state) => (id) => {
  91. return state.friends.find((f) => f.id == id);
  92. }
  93. }
  94. })