user.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import useSWR, { SWRResponse } from 'swr';
  2. import useSWRImmutable from 'swr/immutable';
  3. import { apiv3Get } from '~/client/util/apiv3-client';
  4. import { IUserHasId } from '~/interfaces/user';
  5. import { checkAndUpdateImageUrlCached } from '~/stores/middlewares/user';
  6. export const useSWRxUsersList = (userIds: string[]): SWRResponse<IUserHasId[], Error> => {
  7. const distinctUserIds = userIds.length > 0 ? Array.from(new Set(userIds)).sort() : [];
  8. return useSWR(
  9. distinctUserIds.length > 0 ? ['/users/list', distinctUserIds] : null,
  10. ([endpoint, userIds]) => apiv3Get(endpoint, { userIds: userIds.join(',') }).then((response) => {
  11. return response.data.users;
  12. }),
  13. {
  14. use: [checkAndUpdateImageUrlCached],
  15. revalidateOnFocus: false,
  16. revalidateOnReconnect: false,
  17. },
  18. );
  19. };
  20. type usernameRequestOptions = {
  21. isIncludeActiveUser?: boolean,
  22. isIncludeInactiveUser?: boolean,
  23. isIncludeActivitySnapshotUser?: boolean,
  24. isIncludeMixedUsernames?: boolean,
  25. }
  26. type userData = {
  27. usernames: string[]
  28. totalCount: number
  29. }
  30. type usernameResult = {
  31. activeUser?: userData
  32. inactiveUser?: userData
  33. activitySnapshotUser?: userData
  34. mixedUsernames?: string[]
  35. }
  36. export const useSWRxUsernames = (q: string, offset?: number, limit?: number, options?: usernameRequestOptions): SWRResponse<usernameResult, Error> => {
  37. return useSWRImmutable(
  38. (q != null && q.trim() !== '') ? ['/users/usernames', q, offset, limit, options] : null,
  39. ([endpoint, q, offset, limit, options]) => apiv3Get(endpoint, {
  40. q, offset, limit, options,
  41. }).then(result => result.data),
  42. );
  43. };