useContacts.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * 会话列表:拉取并更新 chatStore.contacts
  3. */
  4. import { getContacts, getToken } from '../utils/api'
  5. import { chatStore } from '../store/chat'
  6. /**
  7. * 拉取会话列表
  8. * @param {{ silent?: boolean }} [opts] - silent 为 false 时会置 loadingContacts(默认 true:刷新不闪屏、不挡列表)
  9. */
  10. export async function fetchContactsList(opts = {}) {
  11. const silent = opts.silent !== false
  12. const token = getToken()
  13. if (!token) {
  14. chatStore.contacts = []
  15. chatStore.contactsFetchFailed = false
  16. return
  17. }
  18. if (!silent) chatStore.loadingContacts = true
  19. try {
  20. const data = await getContacts(token)
  21. const list = Array.isArray(data) ? data : (data.list || data.items || data.conversations || [])
  22. chatStore.setContacts(
  23. list.map((c) => {
  24. const id = String(c.user_id ?? c.userId ?? c.id ?? '')
  25. const unreadCount = Number(c.unread_count ?? c.unreadCount ?? 0) || 0
  26. return {
  27. id,
  28. user_id: c.user_id ?? c.userId ?? c.id,
  29. title: c.full_name ?? c.name ?? c.title ?? '未知',
  30. lastMessage: typeof c.last_message === 'string'
  31. ? c.last_message
  32. : (c.last_message && (c.last_message.content || c.last_message.text)) ?? c.last_message_preview ?? '',
  33. time: c.updated_at ?? c.last_message?.created_at ?? '',
  34. avatar: c.avatar ?? c.avatar_url ?? '',
  35. unread_count: unreadCount,
  36. is_system: !!c.is_system,
  37. app_id: c.app_id ?? null,
  38. app_name: c.app_name ?? ''
  39. }
  40. })
  41. )
  42. chatStore.contactsFetchFailed = false
  43. } catch (e) {
  44. // 网络或接口失败:不覆盖已有会话列表;空列表时用于展示「请下拉刷新」
  45. chatStore.contactsFetchFailed = true
  46. } finally {
  47. if (!silent) chatStore.loadingContacts = false
  48. }
  49. }
  50. export function useContacts() {
  51. return {
  52. contacts: chatStore.contacts,
  53. loadingContacts: chatStore.loadingContacts,
  54. fetchContacts: fetchContactsList
  55. }
  56. }