.
This commit is contained in:
1 parent
feeb30c6a9
commit
5286e4d1ed
13 files changed
+344
-82
No files matched your search
@@ -12,6 +12,7 @@ function makeHandler(overrides?: {
|
||||
}): MatchCancelHandler {
|
||||
const matchService = {
|
||||
cancelJoin: jest.fn(),
|
||||
list: jest.fn(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
@@ -29,13 +30,17 @@ const baseParams = {
|
||||
};
|
||||
|
||||
describe('MatchCancelHandler', () => {
|
||||
it('rejects invalid match id without touching services', async () => {
|
||||
const findUserByKakaoTalkId = jest.fn();
|
||||
it('rejects unknown match reference without cancelling', async () => {
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: { cancelJoin } as Partial<MatchService>,
|
||||
matchService: {
|
||||
cancelJoin,
|
||||
list: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId,
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
@@ -44,13 +49,12 @@ describe('MatchCancelHandler', () => {
|
||||
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'),
|
||||
text: expect.stringContaining('모집 중인 내전이 없습니다'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -87,6 +91,39 @@ describe('MatchCancelHandler', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves cancellation by short code', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const cancelJoin = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}, {}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const findUserByKakaoTalkId = jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
cancelJoin,
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'AB12',
|
||||
});
|
||||
|
||||
expect(cancelJoin).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
});
|
||||
});
|
||||
|
||||
it('asks unregistered user to register first', async () => {
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
|
||||
@@ -7,6 +7,7 @@ import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||
|
||||
interface CancelHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
@@ -23,11 +24,6 @@ export class MatchCancelHandler {
|
||||
) {}
|
||||
|
||||
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,
|
||||
@@ -39,9 +35,14 @@ export class MatchCancelHandler {
|
||||
);
|
||||
}
|
||||
|
||||
const matchTarget = await this.resolveCancelTarget(params);
|
||||
if (typeof matchTarget === 'string') {
|
||||
return this.errorReply(params, matchTarget);
|
||||
}
|
||||
|
||||
try {
|
||||
const match = await this.matchService.cancelJoin({
|
||||
matchId: matchObjectId,
|
||||
matchId: matchTarget,
|
||||
userId: user._id,
|
||||
});
|
||||
|
||||
@@ -69,6 +70,35 @@ export class MatchCancelHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveCancelTarget(
|
||||
params: CancelHandlerParams,
|
||||
): Promise<mongoose.Types.ObjectId | string> {
|
||||
if (mongoose.isValidObjectId(params.matchId)) {
|
||||
return new mongoose.Types.ObjectId(params.matchId);
|
||||
}
|
||||
|
||||
const recruitingMatches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 50,
|
||||
});
|
||||
if (recruitingMatches.length === 0) {
|
||||
return '모집 중인 내전이 없습니다.';
|
||||
}
|
||||
|
||||
const result = resolveRecruitingMatchReference(
|
||||
params.matchId,
|
||||
recruitingMatches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return result.match._id;
|
||||
}
|
||||
if (result.kind === 'ambiguous') {
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: CancelHandlerParams,
|
||||
message: string,
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('MatchJoinHandler', () => {
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('ID 또는 제목'),
|
||||
text: expect.stringContaining('코드 또는 제목'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -178,6 +178,46 @@ describe('MatchJoinHandler', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('resolves a recruiting match by short code', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
{
|
||||
_id: objectId('444444444444444444444444'),
|
||||
title: '심야 내전',
|
||||
shortCode: 'CD34',
|
||||
},
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: 'AB12 프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(join).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects ambiguous title prefixes', async () => {
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||
|
||||
interface JoinHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
@@ -145,10 +146,10 @@ export class MatchJoinHandler {
|
||||
};
|
||||
}
|
||||
if (titleTarget.kind === 'ambiguous') {
|
||||
return `내전 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 ID 또는 제목을 확인해주세요.';
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private parseRiotId(
|
||||
@@ -183,7 +184,10 @@ export class MatchJoinHandler {
|
||||
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
||||
if (!matchTitlePrefix || !gameName) continue;
|
||||
|
||||
const result = this.findByTitlePrefix(matches, matchTitlePrefix);
|
||||
const result = resolveRecruitingMatchReference(
|
||||
matchTitlePrefix,
|
||||
matches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return { kind: 'matched', match: result.match, gameName };
|
||||
}
|
||||
@@ -197,42 +201,6 @@ export class MatchJoinHandler {
|
||||
: { kind: 'not-found' };
|
||||
}
|
||||
|
||||
private findByTitlePrefix(
|
||||
matches: MatchDocument[],
|
||||
titlePrefix: string,
|
||||
):
|
||||
| { kind: 'matched'; match: MatchDocument }
|
||||
| { kind: 'ambiguous'; titles: string[] }
|
||||
| { kind: 'not-found' } {
|
||||
const normalizedPrefix = normalizeLookup(titlePrefix);
|
||||
const exactMatches = matches.filter(
|
||||
(match) => normalizeLookup(match.title) === normalizedPrefix,
|
||||
);
|
||||
if (exactMatches.length === 1) {
|
||||
return { kind: 'matched', match: exactMatches[0] };
|
||||
}
|
||||
if (exactMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: exactMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
const prefixMatches = matches.filter((match) =>
|
||||
normalizeLookup(match.title).startsWith(normalizedPrefix),
|
||||
);
|
||||
if (prefixMatches.length === 1) {
|
||||
return { kind: 'matched', match: prefixMatches[0] };
|
||||
}
|
||||
if (prefixMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: prefixMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
return { kind: 'not-found' };
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: JoinHandlerParams,
|
||||
message: string,
|
||||
@@ -281,7 +249,3 @@ function splitPositionsFromRight(value: string): number[] {
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
|
||||
function normalizeLookup(value: string): string {
|
||||
return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase();
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { MatchListHandler } from './match-list.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
describe('MatchListHandler', () => {
|
||||
it('prints short codes and compact KST dates', async () => {
|
||||
const match = {
|
||||
_id: objectId('333333333333333333333333'),
|
||||
title: '토요 내전',
|
||||
shortCode: 'AB12',
|
||||
participants: [{}, {}],
|
||||
maxParticipants: 10,
|
||||
scheduledAt: new Date('2026-05-02T10:30:00.000Z'),
|
||||
};
|
||||
const matchService = {
|
||||
list: jest.fn().mockResolvedValue([match]),
|
||||
ensureShortCode: jest.fn().mockResolvedValue(match),
|
||||
} as unknown as MatchService;
|
||||
const handler = new MatchListHandler(matchService);
|
||||
|
||||
const segments = await handler.handle({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
});
|
||||
|
||||
expect(matchService.ensureShortCode).toHaveBeenCalledWith(match);
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('토요 내전 (2/10) 5/2 19:30'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('코드: AB12'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.not.stringContaining('2026-05-02'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.not.stringContaining('ID:'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,12 +29,15 @@ export class MatchListHandler {
|
||||
];
|
||||
}
|
||||
|
||||
const lines = matches.map((m, i) => {
|
||||
const id = (m._id as mongoose.Types.ObjectId).toString();
|
||||
const matchesWithCodes = await Promise.all(
|
||||
matches.map((match) => this.matchService.ensureShortCode(match)),
|
||||
);
|
||||
|
||||
const lines = matchesWithCodes.map((m, i) => {
|
||||
const filled = m.participants.length;
|
||||
const cap = m.maxParticipants;
|
||||
const time = formatScheduledAt(m.scheduledAt);
|
||||
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`;
|
||||
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n 코드: ${m.shortCode}`;
|
||||
});
|
||||
|
||||
return [
|
||||
@@ -45,19 +48,18 @@ export class MatchListHandler {
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [ID 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <ID> 또는 !내전 참가취소 <ID>\n모집 중 내전이 1개면 신청 ID/제목은 생략할 수 있습니다.`,
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [코드 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <코드 또는 제목>\n모집 중 내전이 1개면 신청 코드/제목은 생략할 수 있습니다.`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function formatScheduledAt(date: Date): string {
|
||||
// YYYY-MM-DD HH:mm (KST 표기)
|
||||
// M/D HH:mm (KST 표기)
|
||||
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
||||
const yyyy = kst.getUTCFullYear();
|
||||
const mm = String(kst.getUTCMonth() + 1).padStart(2, '0');
|
||||
const dd = String(kst.getUTCDate()).padStart(2, '0');
|
||||
const month = kst.getUTCMonth() + 1;
|
||||
const day = kst.getUTCDate();
|
||||
const hh = String(kst.getUTCHours()).padStart(2, '0');
|
||||
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
||||
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
|
||||
return `${month}/${day} ${hh}:${mi}`;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { MatchDocument } from '../../global/database/schema';
|
||||
|
||||
export type MatchReferenceResult =
|
||||
| { kind: 'matched'; match: MatchDocument }
|
||||
| { kind: 'ambiguous'; titles: string[] }
|
||||
| { kind: 'not-found' };
|
||||
|
||||
export function resolveRecruitingMatchReference(
|
||||
reference: string,
|
||||
matches: MatchDocument[],
|
||||
): MatchReferenceResult {
|
||||
const normalizedCode = normalizeShortCode(reference);
|
||||
const codeMatches = matches.filter(
|
||||
(match) =>
|
||||
match.shortCode && normalizeShortCode(match.shortCode) === normalizedCode,
|
||||
);
|
||||
if (codeMatches.length === 1) {
|
||||
return { kind: 'matched', match: codeMatches[0] };
|
||||
}
|
||||
if (codeMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: codeMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedReference = normalizeLookup(reference);
|
||||
const exactMatches = matches.filter(
|
||||
(match) => normalizeLookup(match.title) === normalizedReference,
|
||||
);
|
||||
if (exactMatches.length === 1) {
|
||||
return { kind: 'matched', match: exactMatches[0] };
|
||||
}
|
||||
if (exactMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: exactMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
const prefixMatches = matches.filter((match) =>
|
||||
normalizeLookup(match.title).startsWith(normalizedReference),
|
||||
);
|
||||
if (prefixMatches.length === 1) {
|
||||
return { kind: 'matched', match: prefixMatches[0] };
|
||||
}
|
||||
if (prefixMatches.length > 1) {
|
||||
return {
|
||||
kind: 'ambiguous',
|
||||
titles: prefixMatches.map((match) => match.title),
|
||||
};
|
||||
}
|
||||
|
||||
return { kind: 'not-found' };
|
||||
}
|
||||
|
||||
function normalizeLookup(value: string): string {
|
||||
return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeShortCode(value: string): string {
|
||||
return value.normalize('NFC').trim().replace(/\s+/g, '').toUpperCase();
|
||||
}
|
||||
@@ -74,6 +74,13 @@ describe('parseCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-cancel command with short code', () => {
|
||||
expect(parseCommand('!내전 취소 AB12')).toEqual({
|
||||
kind: 'match-cancel',
|
||||
matchId: 'AB12',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses account register command', () => {
|
||||
expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({
|
||||
kind: 'account-register',
|
||||
@@ -110,12 +117,6 @@ describe('parseCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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 프리리 미드,탑'),
|
||||
|
||||
@@ -94,9 +94,6 @@ function parseCancelArgs(args: string): DakaoCommand {
|
||||
if (matchId.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
if (!isObjectIdHex(matchId)) {
|
||||
throw new CommandParseError('invalid_match_id', matchId);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-cancel',
|
||||
@@ -143,7 +140,3 @@ function parseJoinArgs(args: string): DakaoCommand {
|
||||
positions,
|
||||
};
|
||||
}
|
||||
|
||||
function isObjectIdHex(value: string): boolean {
|
||||
return /^[a-f0-9]{24}$/i.test(value);
|
||||
}
|
||||
@@ -420,6 +420,7 @@ export interface MatchScheduleItem {
|
||||
|
||||
export interface Match extends MongooseTimestamps {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
shortCode?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
|
||||
@@ -1068,6 +1069,14 @@ export const MatchSchema = new Schema<Match>(
|
||||
ref: 'community',
|
||||
required: true,
|
||||
},
|
||||
shortCode: {
|
||||
type: String,
|
||||
required: false,
|
||||
trim: true,
|
||||
uppercase: true,
|
||||
minlength: 4,
|
||||
maxlength: 6,
|
||||
},
|
||||
title: { type: String, required: true },
|
||||
description: { type: String, required: true, default: '' },
|
||||
mapId: { type: Number, required: true, default: 11 },
|
||||
@@ -1141,6 +1150,13 @@ export const MatchSchema = new Schema<Match>(
|
||||
|
||||
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
|
||||
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
|
||||
MatchSchema.index(
|
||||
{ communityId: 1, shortCode: 1 },
|
||||
{
|
||||
unique: true,
|
||||
partialFilterExpression: { shortCode: { $type: 'string' } },
|
||||
},
|
||||
);
|
||||
MatchSchema.index({ legacyImported: 1, scheduledAt: -1 });
|
||||
MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true });
|
||||
MatchSchema.index({ title: 'text', description: 'text' });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
@@ -17,6 +18,10 @@ import {
|
||||
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
|
||||
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const MATCH_SHORT_CODE_LENGTH = 4;
|
||||
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
||||
|
||||
interface CreateMatchParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
@@ -65,6 +70,9 @@ export class MatchService {
|
||||
.exec();
|
||||
return MatchModel.create({
|
||||
...params.data,
|
||||
shortCode:
|
||||
params.data.shortCode ??
|
||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||
gameCount:
|
||||
params.data.gameCount ??
|
||||
community?.matchGameCount ??
|
||||
@@ -89,6 +97,18 @@ export class MatchService {
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
|
||||
if (match.shortCode) return match;
|
||||
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
match.shortCode = await this.generateUniqueShortCode(
|
||||
MatchModel,
|
||||
match.communityId,
|
||||
);
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
|
||||
public async getById(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchDocument> {
|
||||
@@ -269,6 +289,36 @@ export class MatchService {
|
||||
};
|
||||
}
|
||||
|
||||
private async generateUniqueShortCode(
|
||||
MatchModel: mongoose.Model<Match>,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<string> {
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS;
|
||||
attempt += 1
|
||||
) {
|
||||
const shortCode = this.generateShortCode();
|
||||
const exists = await MatchModel.exists({ communityId, shortCode });
|
||||
if (!exists) return shortCode;
|
||||
}
|
||||
|
||||
throw new InternalServerErrorException(
|
||||
'Failed to generate unique match short code.',
|
||||
);
|
||||
}
|
||||
|
||||
private generateShortCode(): string {
|
||||
let code = '';
|
||||
for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) {
|
||||
const alphabetIndex = Math.floor(
|
||||
Math.random() * MATCH_SHORT_CODE_ALPHABET.length,
|
||||
);
|
||||
code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex];
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
private buildSeriesResults(
|
||||
games: NonNullable<Match['result']>['games'],
|
||||
): MatchSeriesResult[] {
|
||||
|
||||
Reference in new issue
Block a user