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

Refactors delete topic #9241

Merged
merged 7 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
39 changes: 39 additions & 0 deletions libs/model/src/community/DeleteTopic.command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { type Command } from '@hicommonwealth/core';
import * as schemas from '@hicommonwealth/schemas';
import { models } from '../database';
import { AuthContext, isAuthorized } from '../middleware';
import { mustBeAuthorized, mustExist } from '../middleware/guards';

export function DeleteTopic(): Command<
typeof schemas.DeleteTopic,
AuthContext
> {
return {
...schemas.DeleteTopic,
auth: [isAuthorized({})],
body: async ({ actor, auth }) => {
const { community_id, topic_id } = mustBeAuthorized(actor, auth);

const topic = await models.Topic.findOne({
where: { community_id, id: topic_id! },
});
mustExist('Topic', topic);

await models.sequelize.transaction(async (transaction) => {
await models.Thread.update(
{ topic_id: null },
{
where: {
community_id: topic.community_id,
topic_id,
},
transaction,
},
);
await topic.destroy({ transaction });
});

return { community_id, topic_id: topic.id! };
},
};
}
1 change: 1 addition & 0 deletions libs/model/src/community/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './CreateCommunity.command';
export * from './CreateGroup.command';
export * from './CreateStakeTransaction.command';
export * from './DeleteTopic.command';
export * from './GenerateStakeholderGroups.command';
export * from './GetCommunities.query';
export * from './GetCommunity.query';
Expand Down
6 changes: 3 additions & 3 deletions libs/model/src/middleware/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ export class RejectedMember extends InvalidActor {
* and authorized by prefilling the authorization context.
*
* Currenlty, the waterfall is:
* 1. by comment_id
* 3. or by thread_id
* 2. or by community_id (community_id or id)
* by comment_id
* or by thread_id
or by community_id (community_id or id)
*
* TODO: Find ways to cache() by args to avoid db trips
*
Expand Down
11 changes: 7 additions & 4 deletions libs/model/src/middleware/guards.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
Actor,
InvalidActor,
InvalidState,
logger,
type Actor,
} from '@hicommonwealth/core';
import { AddressInstance, ThreadInstance } from '../models';
import { AuthContext } from './authorization';
import type { AddressInstance, ThreadInstance } from '../models';
import type { AuthContext } from './authorization';

const log = logger(import.meta);

Expand Down Expand Up @@ -66,7 +66,10 @@ export function mustBeSuperAdmin(actor: Actor) {
*/
export function mustBeAuthorized(actor: Actor, auth?: AuthContext) {
if (!auth?.address) throw new InvalidActor(actor, 'Not authorized');
return auth as AuthContext & { address: AddressInstance };
return auth as AuthContext & {
address: AddressInstance;
community_id: string;
};
}

/**
Expand Down
53 changes: 52 additions & 1 deletion libs/model/test/community/community-lifecycle.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
Actor,
InvalidActor,
InvalidInput,
InvalidState,
command,
Expand All @@ -12,12 +13,14 @@ import { afterAll, assert, beforeAll, describe, expect, test } from 'vitest';
import {
CreateCommunity,
CreateGroup,
DeleteTopic,
Errors,
GetCommunities,
MAX_GROUPS_PER_COMMUNITY,
UpdateCommunity,
UpdateCommunityErrors,
} from '../../src/community';
import { models } from '../../src/database';
import type {
ChainNodeAttributes,
CommunityAttributes,
Expand All @@ -29,7 +32,7 @@ const chance = Chance();
describe('Community lifecycle', () => {
let ethNode: ChainNodeAttributes, edgewareNode: ChainNodeAttributes;
let community: CommunityAttributes;
let superAdminActor: Actor, adminActor: Actor;
let superAdminActor: Actor, adminActor: Actor, memberActor: Actor;
const custom_domain = 'custom';
const group_payload = {
id: '',
Expand All @@ -50,6 +53,7 @@ describe('Community lifecycle', () => {
});
const [superadmin] = await seed('User', { isAdmin: true });
const [admin] = await seed('User', { isAdmin: false });
const [member] = await seed('User', { isAdmin: false });
const [base] = await seed('Community', {
chain_node_id: _ethNode!.id!,
base: ChainBase.Ethereum,
Expand All @@ -65,6 +69,10 @@ describe('Community lifecycle', () => {
role: 'admin',
user_id: admin!.id,
},
{
role: 'member',
user_id: member!.id,
},
],
custom_domain,
});
Expand All @@ -83,6 +91,14 @@ describe('Community lifecycle', () => {
user: { id: admin!.id!, email: admin!.email!, isAdmin: admin!.isAdmin! },
address: base?.Addresses?.at(1)?.address,
};
memberActor = {
user: {
id: member!.id!,
email: member!.email!,
isAdmin: member!.isAdmin!,
},
address: base?.Addresses?.at(2)?.address,
};
});

afterAll(async () => {
Expand Down Expand Up @@ -195,6 +211,41 @@ describe('Community lifecycle', () => {
});
});

describe('topics', () => {
test('should delete a topic', async () => {
// TODO: use CreateTopic
const topic = await models.Topic.create({
community_id: community.id,
name: 'hhh',
featured_in_new_post: false,
featured_in_sidebar: false,
});

const response = await command(DeleteTopic(), {
actor: superAdminActor,
payload: { community_id: community.id, topic_id: topic!.id! },
});
expect(response?.topic_id).to.equal(topic.id);
});

test('should throw if not authorized', async () => {
// TODO: use CreateTopic
const topic = await models.Topic.create({
community_id: community.id,
name: 'hhh',
featured_in_new_post: false,
featured_in_sidebar: false,
});

await expect(
command(DeleteTopic(), {
actor: memberActor,
payload: { community_id: community.id, topic_id: topic!.id! },
}),
).rejects.toThrow(InvalidActor);
});
});

describe('updates', () => {
const baseRequest = {
default_symbol: 'EDG',
Expand Down
11 changes: 11 additions & 0 deletions libs/schemas/src/commands/community.schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,14 @@ export const GenerateStakeholderGroups = {
})
.partial(),
};

export const DeleteTopic = {
input: z.object({
community_id: z.string(),
topic_id: PG_INT,
}),
output: z.object({
community_id: z.string(),
topic_id: PG_INT,
}),
};
Original file line number Diff line number Diff line change
@@ -1,29 +1,11 @@
import { useMutation } from '@tanstack/react-query';
import axios from 'axios';
import { ApiEndpoints, SERVER_URL, queryClient } from 'state/api/config';
import { userStore } from '../../ui/user';

interface DeleteTopicProps {
topicId: number;
communityId: string;
topicName: string;
}

const deleteTopic = async ({ topicId, communityId }: DeleteTopicProps) => {
await axios.delete(`${SERVER_URL}/topics/${topicId}`, {
data: {
community_id: communityId,
jwt: userStore.getState().jwt,
},
});
};
import { trpc } from 'client/scripts/utils/trpcClient';
import { ApiEndpoints, queryClient } from 'state/api/config';

const useDeleteTopicMutation = () => {
return useMutation({
mutationFn: deleteTopic,
onSuccess: async (data, variables) => {
return trpc.community.deleteTopic.useMutation({
onSuccess: async (response) => {
await queryClient.invalidateQueries({
queryKey: [ApiEndpoints.BULK_TOPICS, variables.communityId],
queryKey: [ApiEndpoints.BULK_TOPICS, response.community_id],
});
// TODO: add a new method in thread cache to deal with this
// await app.threads.listingStore.removeTopic(variables.topicName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,8 @@ export const EditTopicModal = ({
buttonHeight: 'sm',
onClick: async () => {
await deleteTopic({
topicId: id,
topicName: name,
communityId: app.activeChainId() || '',
community_id: app.activeChainId() || '',
topic_id: id,
});
if (noRedirect) {
onModalClose();
Expand Down
1 change: 1 addition & 0 deletions packages/commonwealth/server/api/community.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,5 @@ export const trpcRouter = trpc.router({
Community.UpdateCustomDomain,
trpc.Tag.Community,
),
deleteTopic: trpc.command(Community.DeleteTopic, trpc.Tag.Community),
});
2 changes: 2 additions & 0 deletions packages/commonwealth/server/api/external-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {
getCommunities,
getCommunity,
getMembers,
deleteTopic,
} = community.trpcRouter;
const { createThread, updateThread, createThreadReaction } = thread.trpcRouter;
const {
Expand All @@ -29,6 +30,7 @@ const api = {
getCommunities,
getCommunity,
getMembers,
deleteTopic,
getComments,
createThread,
updateThread,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,6 @@ import {
CreateTopicResult,
__createTopic,
} from './server_topics_methods/create_topic';
import {
DeleteTopicOptions,
DeleteTopicResult,
__deleteTopic,
} from './server_topics_methods/delete_topic';
import {
GetTopicsOptions,
GetTopicsResult,
Expand Down Expand Up @@ -48,10 +43,6 @@ export class ServerTopicsController {
return __updateTopic.call(this, options);
}

async deleteTopic(options: DeleteTopicOptions): Promise<DeleteTopicResult> {
return __deleteTopic.call(this, options);
}

async updateTopicsOrder(
options: UpdateTopicsOrderOptions,
): Promise<UpdateTopicsOrderResult> {
Expand Down

This file was deleted.

Loading
Loading