user.tsx 1.6 KB

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