user.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. { use: [checkAndUpdateImageUrlCached] },
  14. );
  15. };
  16. type usernameRequestOptions = {
  17. isIncludeActiveUser?: boolean,
  18. isIncludeInactiveUser?: boolean,
  19. isIncludeActivitySnapshotUser?: boolean,
  20. isIncludeMixedUsernames?: boolean,
  21. }
  22. type userData = {
  23. usernames: string[]
  24. totalCount: number
  25. }
  26. type usernameResult = {
  27. activeUser?: userData
  28. inactiveUser?: userData
  29. activitySnapshotUser?: userData
  30. mixedUsernames?: string[]
  31. }
  32. export const useSWRxUsernames = (q: string, offset?: number, limit?: number, options?: usernameRequestOptions): SWRResponse<usernameResult, Error> => {
  33. return useSWRImmutable(
  34. (q != null && q.trim() !== '') ? ['/users/usernames', q, offset, limit, options] : null,
  35. (endpoint, q, offset, limit, options) => apiv3Get(endpoint, {
  36. q, offset, limit, options,
  37. }).then(result => result.data),
  38. );
  39. };