user.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 type { PopulatedGrantedGroup } from '~/interfaces/page-grant';
  7. import { checkAndUpdateImageUrlCached } from '~/stores/middlewares/user';
  8. export const useSWRxUsersList = (userIds: string[]): SWRResponse<IUserHasId[], Error> => {
  9. const distinctUserIds = userIds.length > 0 ? Array.from(new Set(userIds)).sort() : [];
  10. return useSWR(
  11. distinctUserIds.length > 0 ? ['/users/list', distinctUserIds] : null,
  12. ([endpoint, userIds]) => apiv3Get(endpoint, { userIds: userIds.join(',') }).then((response) => {
  13. return response.data.users;
  14. }),
  15. {
  16. use: [checkAndUpdateImageUrlCached],
  17. revalidateOnFocus: false,
  18. revalidateOnReconnect: false,
  19. },
  20. );
  21. };
  22. type usernameRequestOptions = {
  23. isIncludeActiveUser?: boolean,
  24. isIncludeInactiveUser?: boolean,
  25. isIncludeActivitySnapshotUser?: boolean,
  26. isIncludeMixedUsernames?: boolean,
  27. }
  28. type userData = {
  29. usernames: string[]
  30. totalCount: number
  31. }
  32. type usernameResult = {
  33. activeUser?: userData
  34. inactiveUser?: userData
  35. activitySnapshotUser?: userData
  36. mixedUsernames?: string[]
  37. }
  38. export const useSWRxUsernames = (q: string, offset?: number, limit?: number, options?: usernameRequestOptions): SWRResponse<usernameResult, Error> => {
  39. return useSWRImmutable(
  40. (q != null && q.trim() !== '') ? ['/users/usernames', q, offset, limit, JSON.stringify(options)] : null,
  41. ([endpoint, q, offset, limit, options]) => apiv3Get(endpoint, {
  42. q, offset, limit, options,
  43. }).then(result => result.data),
  44. );
  45. };
  46. type RelatedGroupsResponse = {
  47. relatedGroups: PopulatedGrantedGroup[]
  48. }
  49. export const useSWRxUserRelatedGroups = (): SWRResponse<RelatedGroupsResponse, Error> => {
  50. return useSWRImmutable<RelatedGroupsResponse>(
  51. ['/user/related-groups'],
  52. ([endpoint]) => apiv3Get(endpoint).then(response => response.data),
  53. );
  54. };