.
This commit is contained in:
1 parent
673ee3d80a
commit
bd3cd4fa5f
9 files changed
+332
-3
No files matched your search
@@ -111,6 +111,17 @@ export class DakaoUserService {
|
||||
return user;
|
||||
}
|
||||
|
||||
public async findUserByKakaoTalkId(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
}): Promise<UserDocument | null> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.findOne({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.kakaoTalkId,
|
||||
}).exec();
|
||||
}
|
||||
|
||||
public async resolveRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { DakaoSubscriber } from './dakao.subscriber';
|
||||
import { DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
|
||||
@@ -27,6 +28,7 @@ import { MatchListHandler } from './handlers/match-list.handler';
|
||||
AccountRegisterHandler,
|
||||
MatchListHandler,
|
||||
MatchJoinHandler,
|
||||
MatchCancelHandler,
|
||||
],
|
||||
exports: [DakaoPublisher],
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
|
||||
@@ -28,6 +29,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
private readonly accountRegisterHandler: AccountRegisterHandler,
|
||||
private readonly matchListHandler: MatchListHandler,
|
||||
private readonly matchJoinHandler: MatchJoinHandler,
|
||||
private readonly matchCancelHandler: MatchCancelHandler,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
@@ -116,6 +118,14 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
positions: command.positions.positions,
|
||||
});
|
||||
break;
|
||||
case 'match-cancel':
|
||||
segments = await this.matchCancelHandler.handle({
|
||||
communityId,
|
||||
matchId: command.matchId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
await this.publisher.sendMessage({
|
||||
@@ -194,9 +204,9 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
const text = ((): string => {
|
||||
switch (err.code) {
|
||||
case 'unknown_command':
|
||||
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`;
|
||||
case 'usage':
|
||||
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`;
|
||||
case 'invalid_match_id':
|
||||
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
|
||||
case 'invalid_riot_id':
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
import { MatchCancelHandler } from './match-cancel.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeHandler(overrides?: {
|
||||
matchService?: Partial<MatchService>;
|
||||
dakaoUserService?: Partial<DakaoUserService>;
|
||||
}): MatchCancelHandler {
|
||||
const matchService = {
|
||||
cancelJoin: jest.fn(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
findUserByKakaoTalkId: jest.fn(),
|
||||
...overrides?.dakaoUserService,
|
||||
} as unknown as DakaoUserService;
|
||||
return new MatchCancelHandler(matchService, dakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
};
|
||||
|
||||
describe('MatchCancelHandler', () => {
|
||||
it('rejects invalid match id without touching services', async () => {
|
||||
const findUserByKakaoTalkId = jest.fn();
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: { cancelJoin } as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'not-an-id',
|
||||
});
|
||||
|
||||
expect(findUserByKakaoTalkId).not.toHaveBeenCalled();
|
||||
expect(cancelJoin).not.toHaveBeenCalled();
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('유효하지 않은 내전 ID'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('replies with success for registered user cancellation', async () => {
|
||||
const cancelJoin = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}, {}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const findUserByKakaoTalkId = jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: { cancelJoin } as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(findUserByKakaoTalkId).toHaveBeenCalledWith({
|
||||
communityId: baseParams.communityId,
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
});
|
||||
expect(cancelJoin).toHaveBeenCalledWith({
|
||||
matchId: expect.any(mongoose.Types.ObjectId),
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('참가 취소 완료 (2/10)'),
|
||||
});
|
||||
});
|
||||
|
||||
it('asks unregistered user to register first', async () => {
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: { cancelJoin } as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue(null),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(cancelJoin).not.toHaveBeenCalled();
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('계정을 등록'),
|
||||
});
|
||||
});
|
||||
|
||||
it('translates not-joined cancellation errors', async () => {
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
cancelJoin: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new BadRequestException('User has not joined this match.'),
|
||||
),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('신청한 내전이 아닙니다'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
interface CancelHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: string;
|
||||
senderUserId: string; // kakaoTalkId
|
||||
senderNickname: string; // kakaoTalkNickname
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchCancelHandler {
|
||||
constructor(
|
||||
private readonly matchService: MatchService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
) {}
|
||||
|
||||
public async handle(params: CancelHandlerParams): Promise<DakaoSegment[]> {
|
||||
if (!mongoose.isValidObjectId(params.matchId)) {
|
||||
return this.errorReply(params, '유효하지 않은 내전 ID 입니다.');
|
||||
}
|
||||
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
|
||||
|
||||
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
});
|
||||
if (!user) {
|
||||
return this.errorReply(
|
||||
params,
|
||||
'먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.',
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const match = await this.matchService.cancelJoin({
|
||||
matchId: matchObjectId,
|
||||
userId: user._id,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 참가 취소 완료 (${match.participants.length}/${match.maxParticipants})` +
|
||||
`\n내전: ${match.title}`,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
if (err instanceof NotFoundException) {
|
||||
return this.errorReply(params, '내전을 찾을 수 없습니다.');
|
||||
}
|
||||
if (err instanceof BadRequestException) {
|
||||
return this.errorReply(params, this.translateBadRequest(err.message));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: CancelHandlerParams,
|
||||
message: string,
|
||||
): DakaoSegment[] {
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ` ${message}` },
|
||||
];
|
||||
}
|
||||
|
||||
private translateBadRequest(raw: string): string {
|
||||
if (raw.includes('different communities')) {
|
||||
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
|
||||
}
|
||||
if (raw.includes('not recruiting')) {
|
||||
return '모집 중인 내전만 참가 취소할 수 있습니다.';
|
||||
}
|
||||
if (raw.includes('has not joined')) return '신청한 내전이 아닙니다.';
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ export class MatchListHandler {
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <ID> <닉네임>#<태그> <포지션1>,<포지션2>`,
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <ID> <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <ID> 또는 !내전 참가취소 <ID>`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -48,6 +48,20 @@ describe('parseCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-cancel command (취소)', () => {
|
||||
expect(parseCommand('!내전 취소 69b63bc96da18dfdb218ee8c')).toEqual({
|
||||
kind: 'match-cancel',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-cancel command (참가취소)', () => {
|
||||
expect(parseCommand('!내전 참가취소 69b63bc96da18dfdb218ee8c')).toEqual({
|
||||
kind: 'match-cancel',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses account register command', () => {
|
||||
expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({
|
||||
kind: 'account-register',
|
||||
@@ -81,6 +95,12 @@ describe('parseCommand', () => {
|
||||
).toThrow(/invalid_match_id/);
|
||||
});
|
||||
|
||||
it('throws invalid_match_id for non-objectid cancel match', () => {
|
||||
expect(() => parseCommand('!내전 취소 not-an-id')).toThrow(
|
||||
/invalid_match_id/,
|
||||
);
|
||||
});
|
||||
|
||||
it('throws invalid_riot_id when # missing', () => {
|
||||
expect(() =>
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
|
||||
|
||||
@@ -14,6 +14,10 @@ export type DakaoCommand =
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
positions: ParsedPositions;
|
||||
}
|
||||
| {
|
||||
kind: 'match-cancel';
|
||||
matchId: string;
|
||||
};
|
||||
|
||||
export class CommandParseError extends Error {
|
||||
@@ -54,6 +58,9 @@ export function parseCommand(rawMessage: string): DakaoCommand {
|
||||
return { kind: 'match-list' };
|
||||
case '신청':
|
||||
return parseJoinArgs(args);
|
||||
case '취소':
|
||||
case '참가취소':
|
||||
return parseCancelArgs(args);
|
||||
case '계정등록':
|
||||
return parseAccountRegisterArgs(args);
|
||||
default:
|
||||
@@ -84,6 +91,21 @@ function parseAccountRegisterArgs(args: string): DakaoCommand {
|
||||
};
|
||||
}
|
||||
|
||||
function parseCancelArgs(args: string): DakaoCommand {
|
||||
const matchId = args.trim();
|
||||
if (matchId.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
if (!isObjectIdHex(matchId)) {
|
||||
throw new CommandParseError('invalid_match_id', matchId);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-cancel',
|
||||
matchId,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJoinArgs(args: string): DakaoCommand {
|
||||
if (args.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
|
||||
@@ -43,6 +43,11 @@ interface JoinMatchParams {
|
||||
riotPuuid?: string;
|
||||
}
|
||||
|
||||
interface CancelMatchJoinParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchService {
|
||||
constructor(
|
||||
@@ -209,6 +214,38 @@ export class MatchService {
|
||||
return match;
|
||||
}
|
||||
|
||||
public async cancelJoin(
|
||||
params: CancelMatchJoinParams,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
|
||||
const user = await UserModel.findById(params.userId);
|
||||
if (!user) throw new NotFoundException('User not found.');
|
||||
|
||||
const match = await MatchModel.findById(params.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(user.communityId)) {
|
||||
throw new BadRequestException(
|
||||
'User and match belong to different communities.',
|
||||
);
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
|
||||
const participantIndex = match.participants.findIndex((participant) =>
|
||||
participant.userId.equals(user._id),
|
||||
);
|
||||
if (participantIndex === -1) {
|
||||
throw new BadRequestException('User has not joined this match.');
|
||||
}
|
||||
|
||||
match.participants.splice(participantIndex, 1);
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
|
||||
const tier =
|
||||
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
|
||||
|
||||
Reference in new issue
Block a user