Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New getInvitations in clerk-js and invitations from useOrganization #1766

Merged
merged 5 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/fast-books-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/shared': patch
---

Introduce `invitations` in useOrganization, which enables to fetch invitations as paginated lists.
Deprecate `invitationList` in favor of the above introduction.
7 changes: 7 additions & 0 deletions .changeset/three-carrots-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': patch
'@clerk/types': patch
---

Introduces a new method for fetching organization invitations called `Organization.getInvitations`.
Deprecate `Organization.getPendingInvitations`
27 changes: 27 additions & 0 deletions packages/clerk-js/src/core/resources/Organization.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { deprecated } from '@clerk/shared';
import type {
AddMemberParams,
ClerkPaginatedResponse,
ClerkResourceReloadParams,
CreateOrganizationParams,
GetDomainsParams,
GetInvitationsParams,
GetMembershipRequestParams,
GetMemberships,
GetPendingInvitationsParams,
Expand All @@ -12,6 +14,7 @@ import type {
OrganizationDomainJSON,
OrganizationDomainResource,
OrganizationInvitationJSON,
OrganizationInvitationResource,
OrganizationJSON,
OrganizationMembershipJSON,
OrganizationMembershipRequestJSON,
Expand Down Expand Up @@ -193,6 +196,7 @@ export class Organization extends BaseResource implements OrganizationResource {
getPendingInvitations = async (
getPendingInvitationsParams?: GetPendingInvitationsParams,
): Promise<OrganizationInvitation[]> => {
deprecated('getPendingInvitations', 'Use the `getInvitations` method instead.');
return await BaseResource._fetch({
path: `/organizations/${this.id}/invitations/pending`,
method: 'GET',
Expand All @@ -205,6 +209,29 @@ export class Organization extends BaseResource implements OrganizationResource {
.catch(() => []);
};

getInvitations = async (
getInvitationsParams?: GetInvitationsParams,
): Promise<ClerkPaginatedResponse<OrganizationInvitationResource>> => {
return await BaseResource._fetch({
path: `/organizations/${this.id}/invitations`,
method: 'GET',
search: convertPageToOffset(getInvitationsParams) as any,
})
.then(res => {
const { data: requests, total_count } =
res?.response as unknown as ClerkPaginatedResponse<OrganizationInvitationJSON>;

return {
total_count,
data: requests.map(request => new OrganizationInvitation(request)),
};
})
.catch(() => ({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔧 Catching the error at this point prevents the global error handler of the FAPI client to kick-in. Is there a specific reason we want to do this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I am not sure if it's correct thought. We should the error bubble up.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't be breaking change to change it now ? Shall we aim to fix for v5 ?

total_count: 0,
data: [],
}));
};

addMember = async ({ userId, role }: AddMemberParams) => {
const newMember = await BaseResource._fetch({
method: 'POST',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Organization {
"destroy": [Function],
"getDomain": [Function],
"getDomains": [Function],
"getInvitations": [Function],
"getMembershipRequests": [Function],
"getMemberships": [Function],
"getPendingInvitations": [Function],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ OrganizationMembership {
"destroy": [Function],
"getDomain": [Function],
"getDomains": [Function],
"getInvitations": [Function],
"getMembershipRequests": [Function],
"getMemberships": [Function],
"getPendingInvitations": [Function],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,44 @@ import type { OrganizationInvitationResource } from '@clerk/types';

import { useCoreOrganization } from '../../contexts';
import { localizationKeys, Td, Text } from '../../customizables';
import { ThreeDotsMenu, useCardState, usePagination, UserPreview } from '../../elements';
import { ThreeDotsMenu, useCardState, UserPreview } from '../../elements';
import { handleError, roleLocalizationKey } from '../../utils';
import { DataTable, RowContainer } from './MemberListTable';

const ITEMS_PER_PAGE = 10;

export const InvitedMembersList = () => {
const card = useCardState();
const { page, changePage } = usePagination();
const { organization, invitationList, ...rest } = useCoreOrganization({
invitationList: { offset: (page - 1) * ITEMS_PER_PAGE, limit: ITEMS_PER_PAGE },
const { organization, invitations } = useCoreOrganization({
invitations: true,
});

const mutateSwrState = () => {
const unstable__mutate = (rest as any).unstable__mutate;
if (unstable__mutate && typeof unstable__mutate === 'function') {
unstable__mutate();
}
};

if (!organization) {
return null;
}

const revoke = (invitation: OrganizationInvitationResource) => () => {
return card
.runAsync(invitation.revoke)
.then(mutateSwrState)
.then(() => changePage(1))
.runAsync(async () => {
await invitation.revoke();
await (invitations as any).unstable__mutate?.();
})
.catch(err => handleError(err, [], card.setError));
};

return (
<DataTable
page={page}
onPageChange={changePage}
itemCount={organization.pendingInvitationsCount}
itemsPerPage={ITEMS_PER_PAGE}
isLoading={!invitationList}
page={invitations?.page || 1}
onPageChange={invitations?.fetchPage || (() => null)}
itemCount={invitations?.count || 0}
pageCount={invitations?.pageCount || 0}
isLoading={invitations?.isLoading}
emptyStateLocalizationKey={localizationKeys('organizationProfile.membersPage.invitationsTab.table__emptyRow')}
headers={[
localizationKeys('organizationProfile.membersPage.activeMembersTab.tableHeader__user'),
localizationKeys('organizationProfile.membersPage.invitedMembersTab.tableHeader__invited'),
localizationKeys('organizationProfile.membersPage.activeMembersTab.tableHeader__role'),
localizationKeys('organizationProfile.membersPage.activeMembersTab.tableHeader__actions'),
]}
rows={(invitationList || []).map(i => (
rows={(invitations?.data || []).map(i => (
<InvitationRow
key={i.id}
invitation={i}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ describe('OrganizationMembers', () => {

await waitFor(() => {
expect(fixtures.clerk.organization?.getMemberships).toHaveBeenCalled();
expect(fixtures.clerk.organization?.getPendingInvitations).not.toHaveBeenCalled();
expect(fixtures.clerk.organization?.getInvitations).not.toHaveBeenCalled();
expect(fixtures.clerk.organization?.getMembershipRequests).not.toHaveBeenCalled();
expect(queryByText('test_user1')).toBeInTheDocument();
expect(queryByText('First1 Last1')).toBeInTheDocument();
Expand Down Expand Up @@ -258,14 +258,19 @@ describe('OrganizationMembers', () => {
});
});

fixtures.clerk.organization?.getPendingInvitations.mockReturnValue(Promise.resolve(invitationList));
fixtures.clerk.organization?.getInvitations.mockReturnValue(
Promise.resolve({
data: invitationList,
total_count: 2,
}),
);
const { queryByText, getByRole } = render(<OrganizationMembers />, { wrapper });
await userEvent.click(getByRole('tab', { name: 'Invitations' }));
expect(fixtures.clerk.organization?.getPendingInvitations).toHaveBeenCalled();
expect(queryByText('[email protected]')).toBeDefined();
expect(queryByText('Admin')).toBeDefined();
expect(queryByText('[email protected]')).toBeDefined();
expect(queryByText('Member')).toBeDefined();
expect(fixtures.clerk.organization?.getInvitations).toHaveBeenCalled();
expect(queryByText('[email protected]')).toBeInTheDocument();
expect(queryByText('Admin')).toBeInTheDocument();
expect(queryByText('[email protected]')).toBeInTheDocument();
expect(queryByText('Member')).toBeInTheDocument();
});

it('changes tab and renders pending requests', async () => {
Expand Down Expand Up @@ -342,6 +347,6 @@ describe('OrganizationMembers', () => {
);
const { findByText } = render(<OrganizationMembers />, { wrapper });
await waitFor(() => expect(fixtures.clerk.organization?.getMemberships).toHaveBeenCalled());
expect(await findByText('You')).toBeDefined();
expect(await findByText('You')).toBeInTheDocument();
});
});
Loading