friendStore.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import request from '../common/request';
  2. export default {
  3. state: {
  4. friends: []
  5. },
  6. mutations: {
  7. setFriends(state, friends) {
  8. state.friends = friends;
  9. },
  10. updateFriend(state, friend) {
  11. state.friends.forEach((f, index) => {
  12. if (f.id == friend.id) {
  13. // 拷贝属性
  14. let online = state.friends[index].online;
  15. Object.assign(state.friends[index], friend);
  16. state.friends[index].online = online;
  17. }
  18. })
  19. },
  20. removeFriend(state, id) {
  21. state.friends.forEach((f,idx) => {
  22. if(f.id == id){
  23. state.friends.splice(idx, 1)
  24. }
  25. });
  26. },
  27. addFriend(state, friend) {
  28. state.friends.push(friend);
  29. },
  30. setOnlineStatus(state, onlineIds) {
  31. state.friends.forEach((f) => {
  32. let onlineFriend = onlineIds.find((id) => f.id == id);
  33. f.online = onlineFriend != undefined;
  34. });
  35. state.friends.sort((f1, f2) => {
  36. if (f1.online && !f2.online) {
  37. return -1;
  38. }
  39. if (f2.online && !f1.online) {
  40. return 1;
  41. }
  42. return 0;
  43. });
  44. }
  45. },
  46. actions: {
  47. loadFriend(context) {
  48. return new Promise((resolve, reject) => {
  49. request({
  50. url: '/friend/list',
  51. method: 'GET'
  52. }).then((friends) => {
  53. context.commit("setFriends", friends);
  54. context.dispatch("refreshOnlineStatus");
  55. resolve()
  56. }).catch((res) => {
  57. reject();
  58. })
  59. });
  60. },
  61. refreshOnlineStatus(context) {
  62. if (context.state.friends.length > 0 ) {
  63. let userIds = [];
  64. context.state.friends.forEach((f) => {
  65. userIds.push(f.id)
  66. });
  67. request({
  68. url: '/user/online?userIds='+ userIds.join(','),
  69. method: 'GET'
  70. }).then((onlineIds) => {
  71. context.commit("setOnlineStatus", onlineIds);
  72. })
  73. }
  74. // 30s后重新拉取
  75. clearTimeout(context.timer);
  76. context.timer = setTimeout(() => {
  77. context.dispatch("refreshOnlineStatus");
  78. }, 30000)
  79. },
  80. }
  81. }