user.tsx 2.1 KB

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