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

refactor(core): update organization invitation apis #5474

Merged
merged 2 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
refactor(core): update organization invitation apis
  • Loading branch information
gao-sun committed Mar 6, 2024
commit 4e330dfbd838be6c18881ebfa2f102cf763859b9
13 changes: 10 additions & 3 deletions packages/core/src/libraries/organization-invitation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

import { type ConnectorLibrary } from './connector.js';

const invitationLinkPath = '/invitation';

/**
* The ending statuses of an organization invitation per RFC 0003. It means that the invitation
* status cannot be changed anymore.
Expand Down Expand Up @@ -58,6 +56,14 @@
) {
const { inviterId, invitee, organizationId, expiresAt, organizationRoleIds } = data;

if (await this.queries.organizations.relations.users.isMember(organizationId, invitee)) {
throw new RequestError({
status: 422,
code: 'request.invalid_input',
details: 'The invitee is already a member of the organization.',
});
}

return this.queries.pool.transaction(async (connection) => {
const organizationQueries = new OrganizationQueries(connection);
const invitation = await organizationQueries.invitations.insert({
Expand Down Expand Up @@ -117,7 +123,7 @@
status: OrganizationInvitationStatus.Accepted,
acceptedUserId: string
): Promise<OrganizationInvitationEntity>;
// TODO: Error i18n

Check warning on line 126 in packages/core/src/libraries/organization-invitation.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/core/src/libraries/organization-invitation.ts#L126

[no-warning-comments] Unexpected 'todo' comment: 'TODO: Error i18n'.
async updateStatus(
id: string,
status: OrganizationInvitationStatus,
Expand Down Expand Up @@ -186,7 +192,8 @@
});
}

protected async sendEmail(to: string, payload: SendMessagePayload) {
/** Send an organization invitation email. */
async sendEmail(to: string, payload: SendMessagePayload) {
const emailConnector = await this.connector.getMessageConnector(ConnectorType.Email);
return emailConnector.sendMessage({
to,
Expand Down
48 changes: 27 additions & 21 deletions packages/core/src/queries/organization/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,32 +88,34 @@ class OrganizationRolesQueries extends SchemaQueries<
}
}

type OrganizationInvitationSearchOptions = {
invitationId?: string;
organizationId?: string;
inviterId?: string;
};

class OrganizationInvitationsQueries extends SchemaQueries<
OrganizationInvitationKeys,
CreateOrganizationInvitation,
OrganizationInvitation
> {
override async findById(id: string): Promise<Readonly<OrganizationInvitationEntity>> {
return this.pool.one(this.#findEntity(id));
override async findById(invitationId: string): Promise<Readonly<OrganizationInvitationEntity>> {
return this.pool.one(this.#findEntity({ invitationId }));
}

override async findAll(
limit: number,
offset: number,
search?: SearchOptions<OrganizationInvitationKeys>
): Promise<[totalNumber: number, rows: Readonly<OrganizationInvitationEntity[]>]> {
return Promise.all([
this.findTotalNumber(search),
this.pool.any(this.#findEntity(undefined, limit, offset, search)),
]);
/** @deprecated Use `findEntities` instead. */
override async findAll(): Promise<never> {
throw new Error('Use `findEntities` instead.');
}

#findEntity(
invitationId?: string,
limit = 1,
offset = 0,
search?: SearchOptions<OrganizationInvitationKeys>
) {
// We don't override `.findAll()` since the function signature is different from the base class.
async findEntities(
options: Omit<OrganizationInvitationSearchOptions, 'invitationId'>
): Promise<Readonly<OrganizationInvitationEntity[]>> {
return this.pool.any(this.#findEntity({ ...options, invitationId: undefined }));
}

#findEntity({ invitationId, organizationId, inviterId }: OrganizationInvitationSearchOptions) {
const { table, fields } = convertToIdentifiers(OrganizationInvitations, true);
const roleRelations = convertToIdentifiers(OrganizationInvitationRoleRelations, true);
const roles = convertToIdentifiers(OrganizationRoles, true);
Expand Down Expand Up @@ -147,16 +149,20 @@ class OrganizationInvitationsQueries extends SchemaQueries<
on ${roleRelations.fields.organizationInvitationId} = ${fields.id}
left join ${roles.table}
on ${roles.fields.id} = ${roleRelations.fields.organizationRoleId}
where true
${conditionalSql(invitationId, (id) => {
return sql`where ${fields.id} = ${id}`;
return sql`and ${fields.id} = ${id}`;
})}
${conditionalSql(organizationId, (id) => {
return sql`and ${fields.organizationId} = ${id}`;
})}
${conditionalSql(inviterId, (id) => {
return sql`and ${fields.inviterId} = ${id}`;
})}
${buildSearchSql(OrganizationInvitations, search)}
group by ${fields.id}
${conditionalSql(this.orderBy, ({ field, order }) => {
return sql`order by ${fields[field]} ${order === 'desc' ? sql`desc` : sql`asc`}`;
})}
limit ${limit}
offset ${offset}
`;
}
}
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/queries/organization/relations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ export class UserRelationQueries extends TwoRelationsQueries<typeof Organization
super(pool, OrganizationUserRelations.table, Organizations, Users);
}

async isMember(organizationId: string, email: string): Promise<boolean> {
const users = convertToIdentifiers(Users, true);
const relations = convertToIdentifiers(OrganizationUserRelations, true);

return this.pool.exists(sql`
select 1
from ${relations.table}
join ${users.table}
on ${relations.fields.userId} = ${users.fields.id}
where ${relations.fields.organizationId} = ${organizationId}
and ${users.fields.primaryEmail} = ${email}
`);
}

async getFeatured(
organizationId: string
): Promise<[totalNumber: number, users: readonly FeaturedUser[]]> {
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/routes/organization/invitations.openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,21 @@
}
}
}
},
"/api/organization-invitations/{id}/message": {
"post": {
"summary": "Resend invitation message",
"description": "Resend the invitation message to the invitee.",
"requestBody": {
"description": "The message payload for the \"OrganizationInvitation\" template to use when sending the invitation via email.",
"required": true
},
"responses": {
"204": {
"description": "The invitation message was resent successfully."
}
}
}
}
}
}
36 changes: 35 additions & 1 deletion packages/core/src/routes/organization/invitations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,26 @@
const router = new SchemaRouter(OrganizationInvitations, invitations, {
errorHandler,
disabled: {
get: true,
post: true,
patchById: true,
},
entityGuard: organizationInvitationEntityGuard,
});

router.get(
'/',
koaGuard({
query: z.object({ organizationId: z.string().optional(), inviterId: z.string().optional() }),
response: organizationInvitationEntityGuard.array(),
status: [200],
}),
async (ctx, next) => {
ctx.body = await invitations.findEntities(ctx.guard.query);
return next();
}
);

router.post(
'/',
koaGuard({
Expand All @@ -51,7 +65,7 @@
messagePayload: sendMessagePayloadGuard.or(z.literal(false)).default(false),
}),
response: organizationInvitationEntityGuard,
status: [201, 400, 501],
status: [201, 400, 422, 501],
}),
async (ctx, next) => {
const {
Expand All @@ -72,6 +86,26 @@
}
);

router.post(
'/:id/message',
koaGuard({
params: z.object({ id: z.string() }),
body: sendMessagePayloadGuard,
status: [204],
}),
async (ctx, next) => {
const {
params: { id },
body,
} = ctx.guard;
const { invitee } = await invitations.findById(id);

await organizationInvitations.sendEmail(invitee, body);
ctx.status = 204;
return next();
}
);

router.put(
'/:id/status',
koaGuard({
Expand Down Expand Up @@ -100,7 +134,7 @@
return next();
}

// TODO: Error i18n

Check warning on line 137 in packages/core/src/routes/organization/invitations.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/core/src/routes/organization/invitations.ts#L137

[no-warning-comments] Unexpected 'todo' comment: 'TODO: Error i18n'.
assertThat(
acceptedUserId,
new RequestError({
Expand Down
Loading