feat(api): add community endpoints
This commit is contained in:
1 parent
caf517123b
commit
6cd213a462
5 files changed
+366
No files matched your search
@@ -0,0 +1,107 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
|
import { Roles } from '../auth/roles.decorator';
|
||||||
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
|
import type { UserDocument } from '../global/database/schema';
|
||||||
|
import '../auth/auth-request';
|
||||||
|
import { CommunityService } from './community.service';
|
||||||
|
import { CreateCommunityDto } from './dto/create-community.dto';
|
||||||
|
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
|
||||||
|
|
||||||
|
@Controller('communities')
|
||||||
|
export class CommunityController {
|
||||||
|
constructor(private readonly communityService: CommunityService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@AllowPublicAccess()
|
||||||
|
public async createCommunity(
|
||||||
|
@Body() body: CreateCommunityDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
) {
|
||||||
|
if (!req.identity && !body.owner) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'owner is required when not authenticated.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.communityService.createCommunityWithOwner({
|
||||||
|
...body,
|
||||||
|
identityId: req.identity?._id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':communityId')
|
||||||
|
@AllowPublicAccess()
|
||||||
|
public async getCommunity(
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
return this.communityService.getById(communityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':communityId/members/:userId/promote')
|
||||||
|
@Roles('owner')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async promoteToAdmin(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
this.assertOwnerOfCommunity(currentUser, communityId);
|
||||||
|
return this.communityService.promoteToAdmin({ communityId, targetUserId });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':communityId/members/:userId/demote')
|
||||||
|
@Roles('owner')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async demoteToMember(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
this.assertOwnerOfCommunity(currentUser, communityId);
|
||||||
|
return this.communityService.demoteToMember({ communityId, targetUserId });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':communityId/transfer-ownership')
|
||||||
|
@Roles('owner')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async transferOwnership(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Body() body: TransferOwnershipDto,
|
||||||
|
) {
|
||||||
|
this.assertOwnerOfCommunity(currentUser, communityId);
|
||||||
|
return this.communityService.transferOwnership({
|
||||||
|
communityId,
|
||||||
|
currentOwnerUserId: currentUser._id,
|
||||||
|
newOwnerUserId: new mongoose.Types.ObjectId(body.newOwnerUserId),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertOwnerOfCommunity(
|
||||||
|
user: UserDocument,
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): void {
|
||||||
|
if (!user.communityId.equals(communityId)) {
|
||||||
|
throw new ForbiddenException('You do not belong to this community.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { CommunityController } from './community.controller';
|
||||||
|
import { CommunityService } from './community.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [CommunityController],
|
||||||
|
providers: [CommunityService],
|
||||||
|
exports: [CommunityService],
|
||||||
|
})
|
||||||
|
export class CommunityModule {}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
InternalServerErrorException,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import {
|
||||||
|
CommunityDocument,
|
||||||
|
UserDocument,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
|
||||||
|
export interface CreateCommunityInput {
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
identityId?: mongoose.Types.ObjectId;
|
||||||
|
owner?: {
|
||||||
|
kakaoTalkId?: string;
|
||||||
|
kakaoTalkNickname?: string;
|
||||||
|
discordId?: string;
|
||||||
|
discordNickname?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CommunityService {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async getById(
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<CommunityDocument> {
|
||||||
|
const CommunityModel = await this.connectionService.getModel('community');
|
||||||
|
const community = await CommunityModel.findById(communityId).exec();
|
||||||
|
if (!community) throw new NotFoundException('Community not found.');
|
||||||
|
return community;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{
|
||||||
|
community: CommunityDocument;
|
||||||
|
owner: UserDocument;
|
||||||
|
}> {
|
||||||
|
const CommunityModel = await this.connectionService.getModel('community');
|
||||||
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
|
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const ownerUserId = new mongoose.Types.ObjectId();
|
||||||
|
|
||||||
|
const session = await this.connectionService.createSession();
|
||||||
|
if (!session) {
|
||||||
|
throw new InternalServerErrorException('Failed to start DB session.');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
session.startTransaction();
|
||||||
|
|
||||||
|
const [community] = await CommunityModel.create(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
_id: communityId,
|
||||||
|
name: input.name,
|
||||||
|
description: input.description ?? '',
|
||||||
|
ownerUserId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
|
||||||
|
const [owner] = await UserModel.create(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
_id: ownerUserId,
|
||||||
|
communityId,
|
||||||
|
identityId: input.identityId,
|
||||||
|
role: 'owner',
|
||||||
|
kakaoTalkId: input.owner?.kakaoTalkId,
|
||||||
|
kakaoTalkNickname: input.owner?.kakaoTalkNickname,
|
||||||
|
discordId: input.owner?.discordId,
|
||||||
|
discordNickname: input.owner?.discordNickname,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
|
||||||
|
await session.commitTransaction();
|
||||||
|
return { community, owner };
|
||||||
|
} catch (err) {
|
||||||
|
await session.abortTransaction();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await session.endSession();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async promoteToAdmin(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
targetUserId: mongoose.Types.ObjectId;
|
||||||
|
}): Promise<UserDocument> {
|
||||||
|
return this.changeNonOwnerRole({ ...params, nextRole: 'admin' });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async demoteToMember(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
targetUserId: mongoose.Types.ObjectId;
|
||||||
|
}): Promise<UserDocument> {
|
||||||
|
return this.changeNonOwnerRole({ ...params, nextRole: 'member' });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async transferOwnership(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
currentOwnerUserId: mongoose.Types.ObjectId;
|
||||||
|
newOwnerUserId: mongoose.Types.ObjectId;
|
||||||
|
}): Promise<{
|
||||||
|
community: CommunityDocument;
|
||||||
|
previousOwner: UserDocument;
|
||||||
|
newOwner: UserDocument;
|
||||||
|
}> {
|
||||||
|
if (params.currentOwnerUserId.equals(params.newOwnerUserId)) {
|
||||||
|
throw new BadRequestException('New owner is already the current owner.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const CommunityModel = await this.connectionService.getModel('community');
|
||||||
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
|
|
||||||
|
const session = await this.connectionService.createSession();
|
||||||
|
if (!session) {
|
||||||
|
throw new InternalServerErrorException('Failed to start DB session.');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
session.startTransaction();
|
||||||
|
|
||||||
|
const community = await CommunityModel.findById(
|
||||||
|
params.communityId,
|
||||||
|
).session(session);
|
||||||
|
if (!community) throw new NotFoundException('Community not found.');
|
||||||
|
if (!community.ownerUserId.equals(params.currentOwnerUserId)) {
|
||||||
|
throw new BadRequestException('Acting user is not the current owner.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const [previousOwner, newOwner] = await Promise.all([
|
||||||
|
UserModel.findById(params.currentOwnerUserId).session(session),
|
||||||
|
UserModel.findById(params.newOwnerUserId).session(session),
|
||||||
|
]);
|
||||||
|
if (!previousOwner)
|
||||||
|
throw new NotFoundException('Previous owner user not found.');
|
||||||
|
if (!newOwner) throw new NotFoundException('New owner user not found.');
|
||||||
|
if (!newOwner.communityId.equals(params.communityId)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'New owner does not belong to this community.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
community.ownerUserId = newOwner._id;
|
||||||
|
previousOwner.role = 'admin';
|
||||||
|
newOwner.role = 'owner';
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
community.save({ session }),
|
||||||
|
previousOwner.save({ session }),
|
||||||
|
newOwner.save({ session }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await session.commitTransaction();
|
||||||
|
return { community, previousOwner, newOwner };
|
||||||
|
} catch (err) {
|
||||||
|
await session.abortTransaction();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await session.endSession();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async changeNonOwnerRole(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
targetUserId: mongoose.Types.ObjectId;
|
||||||
|
nextRole: 'admin' | 'member';
|
||||||
|
}): Promise<UserDocument> {
|
||||||
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
|
const user = await UserModel.findById(params.targetUserId);
|
||||||
|
if (!user) throw new NotFoundException('Target user not found.');
|
||||||
|
if (!user.communityId.equals(params.communityId)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Target user does not belong to this community.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (user.role === 'owner') {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Owner role must be changed via transferOwnership.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
user.role = params.nextRole;
|
||||||
|
await user.save();
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import {
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
class CreateCommunityOwnerDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(64)
|
||||||
|
kakaoTalkId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(64)
|
||||||
|
kakaoTalkNickname?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(64)
|
||||||
|
discordId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(64)
|
||||||
|
discordNickname?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateCommunityDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(64)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(1024)
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => CreateCommunityOwnerDto)
|
||||||
|
owner?: CreateCommunityOwnerDto;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsMongoId } from 'class-validator';
|
||||||
|
|
||||||
|
export class TransferOwnershipDto {
|
||||||
|
@IsMongoId()
|
||||||
|
newOwnerUserId!: string;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user