feat(api): add Dakao command integration
This commit is contained in:
1 parent
7c4e968c5d
commit
1d203d6f89
19 files changed
+1948
No files matched your search
@@ -0,0 +1,90 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RiotAccount, UserDocument } from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotAccountService } from '../riot/riot-account.service';
|
||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeQuery<T>(value: T) {
|
||||
return {
|
||||
exec: jest.fn().mockResolvedValue(value),
|
||||
};
|
||||
}
|
||||
|
||||
function makeService(params: {
|
||||
user: Partial<UserDocument>;
|
||||
riotAccountService?: Partial<RiotAccountService>;
|
||||
enrichmentService?: Partial<RiotAccountEnrichmentService>;
|
||||
}) {
|
||||
const findOneAndUpdate = jest
|
||||
.fn()
|
||||
.mockReturnValue(makeQuery(params.user as UserDocument));
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ findOneAndUpdate }),
|
||||
} as unknown as ConnectionService;
|
||||
const riotAccountService = {
|
||||
getByRiotId: jest.fn(),
|
||||
...params.riotAccountService,
|
||||
} as unknown as RiotAccountService;
|
||||
const enrichmentService = {
|
||||
enrichRiotAccount: jest.fn(),
|
||||
...params.enrichmentService,
|
||||
} as unknown as RiotAccountEnrichmentService;
|
||||
|
||||
return {
|
||||
service: new DakaoUserService(
|
||||
connectionService,
|
||||
riotAccountService,
|
||||
enrichmentService,
|
||||
),
|
||||
connectionService,
|
||||
findOneAndUpdate,
|
||||
riotAccountService,
|
||||
enrichmentService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('DakaoUserService', () => {
|
||||
it('rejects account registration when the user already has a Riot account', async () => {
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
const existingAccount = {
|
||||
puuid: 'puuid-1',
|
||||
gameName: '기존소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
} as RiotAccount;
|
||||
const {
|
||||
service,
|
||||
connectionService,
|
||||
riotAccountService,
|
||||
enrichmentService,
|
||||
} = makeService({
|
||||
user: {
|
||||
_id: objectId('222222222222222222222222'),
|
||||
riotAccounts: [existingAccount],
|
||||
save,
|
||||
} as Partial<UserDocument>,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.registerPrimaryRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: 'riot_account_already_registered',
|
||||
detail: '기존소환사#KR1',
|
||||
} satisfies Partial<DakaoUserError>);
|
||||
|
||||
expect(connectionService.getModel).toHaveBeenCalledTimes(1);
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('user');
|
||||
expect(riotAccountService.getByRiotId).not.toHaveBeenCalled();
|
||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,393 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose, { isValidObjectId } from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RiotAccount, UserDocument } from '../global/database/schema';
|
||||
import { RiotApiError } from '../riot/riot.client.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotAccountService } from '../riot/riot-account.service';
|
||||
import {
|
||||
RIOT_PLATFORM_ROUTES,
|
||||
RIOT_REGIONAL_ROUTES,
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
} from '../riot/riot.types';
|
||||
import { formatCodePoints, normalizeRiotIdPart } from './riot-id.util';
|
||||
|
||||
export class DakaoUserError extends Error {
|
||||
constructor(
|
||||
public readonly code:
|
||||
| 'invalid_project_id'
|
||||
| 'community_not_found'
|
||||
| 'riot_account_not_found'
|
||||
| 'riot_account_already_registered'
|
||||
| 'riot_account_conflict'
|
||||
| 'riot_account_lookup_failed',
|
||||
public readonly detail?: string,
|
||||
) {
|
||||
super(`Dakao user error: ${code}${detail ? ` (${detail})` : ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
interface ResolveContext {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
kakaoTalkNickname: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
}
|
||||
|
||||
interface ResolveResult {
|
||||
user: UserDocument;
|
||||
riotAccount: RiotAccount;
|
||||
}
|
||||
|
||||
interface RiotRouting {
|
||||
platform: RiotPlatformRoute;
|
||||
region: RiotRegionalRoute;
|
||||
}
|
||||
|
||||
interface ResolvedRiotIdentity {
|
||||
requestedGameName: string;
|
||||
requestedTagLine: string;
|
||||
dto: { puuid: string; gameName: string | null; tagLine: string | null };
|
||||
}
|
||||
|
||||
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoUserService {
|
||||
private readonly logger = new Logger(DakaoUserService.name);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly riotAccountService: RiotAccountService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
) {}
|
||||
|
||||
public async resolveCommunityIdByDakaoProjectId(
|
||||
dakaoProjectId: string,
|
||||
): Promise<mongoose.Types.ObjectId> {
|
||||
if (!isValidObjectId(dakaoProjectId)) {
|
||||
throw new DakaoUserError('invalid_project_id', dakaoProjectId);
|
||||
}
|
||||
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findOne({
|
||||
dakaoProjectId: dakaoProjectId,
|
||||
})
|
||||
.select({ _id: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
if (!community) {
|
||||
throw new DakaoUserError('community_not_found', dakaoProjectId);
|
||||
}
|
||||
return community._id as mongoose.Types.ObjectId;
|
||||
}
|
||||
|
||||
public async upsertUser(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
kakaoTalkNickname: string;
|
||||
}): Promise<UserDocument> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findOneAndUpdate(
|
||||
{ communityId: params.communityId, kakaoTalkId: params.kakaoTalkId },
|
||||
{
|
||||
$set: { kakaoTalkNickname: params.kakaoTalkNickname },
|
||||
$setOnInsert: {
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.kakaoTalkId,
|
||||
role: 'member',
|
||||
isActivated: true,
|
||||
},
|
||||
},
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||
).exec();
|
||||
if (!user) {
|
||||
// upsert + returnDocument='after' 이면 항상 반환되지만 타입 안전을 위해 가드.
|
||||
throw new DakaoUserError('community_not_found');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
public async resolveRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
const user = await this.upsertUser(context);
|
||||
const routing = await this.resolveRiotRouting(context.communityId);
|
||||
const { requestedGameName, requestedTagLine, dto } =
|
||||
await this.lookupRiotIdentity(context, routing);
|
||||
|
||||
const existing = user.riotAccounts.find(
|
||||
(a) =>
|
||||
a.gameName.toLowerCase() === requestedGameName.toLowerCase() &&
|
||||
a.tagLine.toLowerCase() === requestedTagLine.toLowerCase(),
|
||||
);
|
||||
if (existing) {
|
||||
this.logger.log(
|
||||
`Found existing Riot account ${requestedGameName}#${requestedTagLine}: puuid=${existing.puuid}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
const nextGameName = dto.gameName ?? requestedGameName;
|
||||
const nextTagLine = dto.tagLine ?? requestedTagLine;
|
||||
if (existing.puuid !== dto.puuid) {
|
||||
this.logger.warn(
|
||||
`Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`,
|
||||
);
|
||||
existing.puuid = dto.puuid;
|
||||
existing.gameName = nextGameName;
|
||||
existing.tagLine = nextTagLine;
|
||||
this.clearRiotCache(existing);
|
||||
await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine);
|
||||
return this.enrichAttachedAccount({
|
||||
user,
|
||||
riotAccount: existing,
|
||||
platform: routing.platform,
|
||||
region: routing.region,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
existing.gameName !== nextGameName ||
|
||||
existing.tagLine !== nextTagLine
|
||||
) {
|
||||
existing.gameName = nextGameName;
|
||||
existing.tagLine = nextTagLine;
|
||||
await user.save();
|
||||
}
|
||||
return { user, riotAccount: existing };
|
||||
}
|
||||
|
||||
return this.attachRiotAccount({
|
||||
user,
|
||||
puuid: dto.puuid,
|
||||
gameName: dto.gameName ?? requestedGameName,
|
||||
tagLine: dto.tagLine ?? requestedTagLine,
|
||||
platform: routing.platform,
|
||||
region: routing.region,
|
||||
});
|
||||
}
|
||||
|
||||
public async registerPrimaryRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
const user = await this.upsertUser(context);
|
||||
const existingPrimary = user.riotAccounts.find(
|
||||
(account) => account.isPrimary,
|
||||
);
|
||||
const existingAccount = existingPrimary ?? user.riotAccounts[0];
|
||||
if (existingAccount) {
|
||||
throw new DakaoUserError(
|
||||
'riot_account_already_registered',
|
||||
`${existingAccount.gameName}#${existingAccount.tagLine}`,
|
||||
);
|
||||
}
|
||||
|
||||
const routing = await this.resolveRiotRouting(context.communityId);
|
||||
const { requestedGameName, requestedTagLine, dto } =
|
||||
await this.lookupRiotIdentity(context, routing);
|
||||
const nextGameName = dto.gameName ?? requestedGameName;
|
||||
const nextTagLine = dto.tagLine ?? requestedTagLine;
|
||||
|
||||
return this.attachRiotAccount({
|
||||
user,
|
||||
puuid: dto.puuid,
|
||||
gameName: nextGameName,
|
||||
tagLine: nextTagLine,
|
||||
platform: routing.platform,
|
||||
region: routing.region,
|
||||
});
|
||||
}
|
||||
|
||||
private async lookupRiotIdentity(
|
||||
context: ResolveContext,
|
||||
routing: RiotRouting,
|
||||
): Promise<ResolvedRiotIdentity> {
|
||||
const requestedGameName = normalizeRiotIdPart(context.gameName);
|
||||
const requestedTagLine = normalizeRiotIdPart(context.tagLine);
|
||||
this.logRiotIdNormalization(context, requestedGameName, requestedTagLine);
|
||||
|
||||
try {
|
||||
const dto = await this.riotAccountService.getByRiotId(
|
||||
requestedGameName,
|
||||
requestedTagLine,
|
||||
{ region: routing.region },
|
||||
);
|
||||
this.logger.log(
|
||||
`Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`,
|
||||
);
|
||||
return { requestedGameName, requestedTagLine, dto };
|
||||
} catch (err) {
|
||||
if (err instanceof RiotApiError && err.status === 404) {
|
||||
throw new DakaoUserError(
|
||||
'riot_account_not_found',
|
||||
`${requestedGameName}#${requestedTagLine}`,
|
||||
);
|
||||
}
|
||||
this.logger.error(
|
||||
`Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
throw new DakaoUserError(
|
||||
'riot_account_lookup_failed',
|
||||
(err as Error)?.message,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private logRiotIdNormalization(
|
||||
context: ResolveContext,
|
||||
normalizedGameName: string,
|
||||
normalizedTagLine: string,
|
||||
): void {
|
||||
if (
|
||||
context.gameName === normalizedGameName &&
|
||||
context.tagLine === normalizedTagLine
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.warn(
|
||||
`Normalized Riot ID input ${context.gameName}#${context.tagLine} -> ${normalizedGameName}#${normalizedTagLine} ` +
|
||||
`(gameNameCodePoints=${formatCodePoints(context.gameName)}, tagLineCodePoints=${formatCodePoints(context.tagLine)})`,
|
||||
);
|
||||
}
|
||||
|
||||
private async resolveRiotRouting(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<RiotRouting> {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(communityId)
|
||||
.select({ riotPlatform: 1, riotRegion: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
return {
|
||||
platform: this.toRiotPlatform(community?.riotPlatform),
|
||||
region: this.toRiotRegion(community?.riotRegion),
|
||||
};
|
||||
}
|
||||
|
||||
private async attachRiotAccount(params: {
|
||||
user: UserDocument;
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
platform: RiotPlatformRoute;
|
||||
region: RiotRegionalRoute;
|
||||
}): Promise<ResolveResult> {
|
||||
const { user } = params;
|
||||
const isFirst = user.riotAccounts.length === 0;
|
||||
user.riotAccounts.push({
|
||||
puuid: params.puuid,
|
||||
gameName: params.gameName,
|
||||
tagLine: params.tagLine,
|
||||
profileIconId: 0,
|
||||
revisionDate: 0,
|
||||
summonerLevel: 0,
|
||||
isPrimary: isFirst,
|
||||
tiers: [],
|
||||
tierHistory: [],
|
||||
matchIds: [],
|
||||
championMasteries: [],
|
||||
championRecords: {},
|
||||
} as unknown as RiotAccount);
|
||||
|
||||
await this.saveUserHandlingDuplicate(user, params.gameName, params.tagLine);
|
||||
|
||||
const attached = user.riotAccounts.find((a) => a.puuid === params.puuid);
|
||||
if (!attached) {
|
||||
throw new DakaoUserError('riot_account_lookup_failed', 'attach failed');
|
||||
}
|
||||
|
||||
return this.enrichAttachedAccount({
|
||||
user,
|
||||
riotAccount: attached,
|
||||
platform: params.platform,
|
||||
region: params.region,
|
||||
});
|
||||
}
|
||||
|
||||
private async enrichAttachedAccount(params: {
|
||||
user: UserDocument;
|
||||
riotAccount: RiotAccount;
|
||||
platform: RiotPlatformRoute;
|
||||
region: RiotRegionalRoute;
|
||||
}): Promise<ResolveResult> {
|
||||
// 외부 API 실패는 등록 자체를 막지 않음.
|
||||
try {
|
||||
const enrichResult = await this.enrichmentService.enrichRiotAccount({
|
||||
userId: params.user._id,
|
||||
puuid: params.riotAccount.puuid,
|
||||
options: {
|
||||
force: true,
|
||||
platform: params.platform,
|
||||
region: params.region,
|
||||
},
|
||||
});
|
||||
if (enrichResult.account) {
|
||||
return { user: params.user, riotAccount: enrichResult.account };
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Riot enrichment failed (continuing with empty data): ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
return { user: params.user, riotAccount: params.riotAccount };
|
||||
}
|
||||
|
||||
private async saveUserHandlingDuplicate(
|
||||
user: UserDocument,
|
||||
gameName: string,
|
||||
tagLine: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await user.save();
|
||||
} catch (err) {
|
||||
// 같은 communityId + puuid 중복은 다른 유저가 이미 등록한 케이스.
|
||||
if ((err as { code?: number })?.code === 11000) {
|
||||
throw new DakaoUserError(
|
||||
'riot_account_conflict',
|
||||
`${gameName}#${tagLine}`,
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private clearRiotCache(account: RiotAccount): void {
|
||||
account.profileIconId = 0;
|
||||
account.revisionDate = 0;
|
||||
account.summonerLevel = 0;
|
||||
account.tiers = [];
|
||||
account.tierHistory = [];
|
||||
account.matchIds = [];
|
||||
account.matchIdsFetchedAt = undefined;
|
||||
account.recentStatsSummary = undefined;
|
||||
account.recentStatsFetchedAt = undefined;
|
||||
account.championMasteries = [];
|
||||
account.championMasteriesFetchedAt = undefined;
|
||||
account.championRecords = {};
|
||||
account.championRecordsFetchedAt = undefined;
|
||||
}
|
||||
|
||||
private toRiotPlatform(value: unknown): RiotPlatformRoute {
|
||||
return typeof value === 'string' &&
|
||||
RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
|
||||
? (value as RiotPlatformRoute)
|
||||
: DEFAULT_RIOT_PLATFORM;
|
||||
}
|
||||
|
||||
private toRiotRegion(value: unknown): RiotRegionalRoute {
|
||||
return typeof value === 'string' &&
|
||||
RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute)
|
||||
? (value as RiotRegionalRoute)
|
||||
: DEFAULT_RIOT_REGION;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MatchModule } from '../match/match.module';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import {
|
||||
DAKAO_OPTIONS,
|
||||
createDefaultDakaoOptions,
|
||||
} from './dakao.options';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoSubscriber } from './dakao.subscriber';
|
||||
import { DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, MatchModule],
|
||||
providers: [
|
||||
{
|
||||
provide: DAKAO_OPTIONS,
|
||||
useFactory: createDefaultDakaoOptions,
|
||||
},
|
||||
DakaoPublisher,
|
||||
DakaoSubscriber,
|
||||
DakaoUserService,
|
||||
IdempotencyCache,
|
||||
AccountRegisterHandler,
|
||||
MatchListHandler,
|
||||
MatchJoinHandler,
|
||||
],
|
||||
exports: [DakaoPublisher],
|
||||
})
|
||||
export class DakaoModule {}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
export const DAKAO_OPTIONS = Symbol('DAKAO_OPTIONS');
|
||||
|
||||
export interface DakaoOptions {
|
||||
instanceId: string;
|
||||
}
|
||||
|
||||
export function createDefaultDakaoOptions(): DakaoOptions {
|
||||
return {
|
||||
instanceId: process.env.DAKAO_INSTANCE_ID || randomUUID(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
|
||||
function makePublisher() {
|
||||
const natsService = {
|
||||
publish: jest.fn().mockResolvedValue(undefined),
|
||||
subscribe: jest.fn(),
|
||||
} as unknown as NatsService;
|
||||
const secretService = {} as SecretService;
|
||||
const publisher = new DakaoPublisher(natsService, secretService, {
|
||||
instanceId: 'test',
|
||||
});
|
||||
|
||||
return { publisher, natsService };
|
||||
}
|
||||
|
||||
function getPublishedPayload(natsService: NatsService): DakaoSendMessagePayload {
|
||||
const publish = natsService.publish as jest.Mock;
|
||||
const envelope = publish.mock.calls[0][1] as DakaoCommandEnvelope<
|
||||
DakaoSendMessagePayload
|
||||
>;
|
||||
return envelope.payload;
|
||||
}
|
||||
|
||||
describe('DakaoPublisher', () => {
|
||||
it('keeps valid mention segments intact', async () => {
|
||||
const { publisher, natsService } = makePublisher();
|
||||
|
||||
await publisher.sendMessage({
|
||||
chatroomId: '18474390111480678',
|
||||
segments: [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: '6215844374579825921',
|
||||
displayText: '날으는꼴뚜기/95/여/D',
|
||||
},
|
||||
{ kind: 'text', text: ' 신청 완료' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(getPublishedPayload(natsService).segments).toEqual([
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: '6215844374579825921',
|
||||
displayText: '날으는꼴뚜기/95/여/D',
|
||||
},
|
||||
{ kind: 'text', text: ' 신청 완료' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('downgrades invalid mention segments to text before publishing', async () => {
|
||||
const { publisher, natsService } = makePublisher();
|
||||
|
||||
await publisher.sendMessage({
|
||||
chatroomId: '18474390111480678',
|
||||
segments: [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: '-123',
|
||||
displayText: '소쿠리',
|
||||
},
|
||||
{ kind: 'text', text: ' 신청 완료' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(getPublishedPayload(natsService).segments).toEqual([
|
||||
{ kind: 'text', text: '@소쿠리' },
|
||||
{ kind: 'text', text: ' 신청 완료' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import {
|
||||
DakaoCommandEnvelope,
|
||||
DakaoResultEnvelope,
|
||||
DakaoSegment,
|
||||
DakaoSendMessagePayload,
|
||||
} from './dakao.types';
|
||||
import type { DakaoOptions } from './dakao.options';
|
||||
import { DAKAO_OPTIONS } from './dakao.options';
|
||||
|
||||
const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1';
|
||||
const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(DakaoPublisher.name);
|
||||
private replySubject = '';
|
||||
private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT;
|
||||
private source = COMMAND_SOURCE_DEFAULT;
|
||||
|
||||
constructor(
|
||||
private readonly natsService: NatsService,
|
||||
private readonly secretService: SecretService,
|
||||
@Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const replyOverride = await this.secretService
|
||||
.get<string>('DAKAO_REPLY_SUBJECT_PREFIX')
|
||||
.catch(() => undefined);
|
||||
const sendOverride = await this.secretService
|
||||
.get<string>('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT')
|
||||
.catch(() => undefined);
|
||||
const sourceOverride = await this.secretService
|
||||
.get<string>('DAKAO_COMMAND_SOURCE')
|
||||
.catch(() => undefined);
|
||||
|
||||
const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`;
|
||||
this.replySubject = `${replyPrefix}.${this.options.instanceId}`;
|
||||
this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT;
|
||||
this.source = sourceOverride || COMMAND_SOURCE_DEFAULT;
|
||||
|
||||
this.natsService.subscribe<DakaoResultEnvelope>(
|
||||
this.replySubject,
|
||||
(data) => this.handleReply(data),
|
||||
);
|
||||
this.logger.log(
|
||||
`Dakao reply subscriber ready on subject="${this.replySubject}"`,
|
||||
);
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
// NatsService 가 subscription 정리한다.
|
||||
}
|
||||
|
||||
public async sendMessage(params: {
|
||||
chatroomId: string;
|
||||
segments: DakaoSegment[];
|
||||
correlationId?: string;
|
||||
}): Promise<void> {
|
||||
const payload: DakaoSendMessagePayload = {
|
||||
chatroomId: params.chatroomId,
|
||||
segments: this.normalizeSegments(params.segments),
|
||||
};
|
||||
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
|
||||
schema: 'dakao.command.v1',
|
||||
id: randomUUID(),
|
||||
type: 'chat.send-message',
|
||||
source: this.source,
|
||||
correlationId: params.correlationId,
|
||||
replySubject: this.replySubject,
|
||||
payload,
|
||||
};
|
||||
await this.natsService.publish(this.sendMessageSubject, envelope);
|
||||
}
|
||||
|
||||
private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] {
|
||||
const normalized: DakaoSegment[] = [];
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.kind === 'text') {
|
||||
if (segment.text.length > 0) normalized.push(segment);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment.kind === 'mention') {
|
||||
const userId = segment.userId.trim();
|
||||
const displayText = segment.displayText.trim();
|
||||
|
||||
if (this.isPositiveIntegerString(userId) && displayText.length > 0) {
|
||||
normalized.push({ kind: 'mention', userId, displayText });
|
||||
continue;
|
||||
}
|
||||
|
||||
const fallbackText = this.renderMentionFallback(displayText, userId);
|
||||
this.logger.warn(
|
||||
`Dakao mention downgraded to text because userId/displayText is invalid: userId="${userId || '-'}" displayText="${displayText || '-'}"`,
|
||||
);
|
||||
normalized.push({ kind: 'text', text: fallbackText });
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = segment.id.trim();
|
||||
const altText = segment.altText.trim();
|
||||
if (
|
||||
id.length > 0 &&
|
||||
altText.length > 0 &&
|
||||
!/[()@]/.test(altText)
|
||||
) {
|
||||
normalized.push({ kind: 'emoticon', id, altText });
|
||||
continue;
|
||||
}
|
||||
|
||||
this.logger.warn(
|
||||
`Dakao emoticon downgraded to text because id/altText is invalid: id="${id || '-'}" altText="${altText || '-'}"`,
|
||||
);
|
||||
normalized.push({ kind: 'text', text: `(${altText || '이모티콘'})` });
|
||||
}
|
||||
|
||||
return normalized.length > 0
|
||||
? normalized
|
||||
: [{ kind: 'text', text: '명령 처리 결과를 보낼 수 없습니다.' }];
|
||||
}
|
||||
|
||||
private isPositiveIntegerString(value: string): boolean {
|
||||
return /^[1-9]\d*$/.test(value);
|
||||
}
|
||||
|
||||
private renderMentionFallback(displayText: string, userId: string): string {
|
||||
const label = displayText || userId || '사용자';
|
||||
return label.startsWith('@') ? label : `@${label}`;
|
||||
}
|
||||
|
||||
private handleReply(reply: DakaoResultEnvelope): void {
|
||||
if (reply.status === 'succeeded') {
|
||||
this.logger.log(
|
||||
`Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.warn(
|
||||
`Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { CommandParseError, parseCommand } from './parsers/command.parser';
|
||||
import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
|
||||
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 { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
|
||||
const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoSubscriber implements OnModuleInit {
|
||||
private readonly logger = new Logger(DakaoSubscriber.name);
|
||||
private inboundSubject = INBOUND_SUBJECT_DEFAULT;
|
||||
private botUserId: string | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly natsService: NatsService,
|
||||
private readonly secretService: SecretService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
private readonly publisher: DakaoPublisher,
|
||||
private readonly idempotency: IdempotencyCache,
|
||||
private readonly accountRegisterHandler: AccountRegisterHandler,
|
||||
private readonly matchListHandler: MatchListHandler,
|
||||
private readonly matchJoinHandler: MatchJoinHandler,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const subjectOverride = await this.secretService
|
||||
.get<string>('DAKAO_INBOUND_SUBJECT')
|
||||
.catch(() => undefined);
|
||||
this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT;
|
||||
|
||||
this.botUserId = await this.secretService
|
||||
.get<string>('DAKAO_BOT_USER_ID')
|
||||
.catch(() => undefined);
|
||||
|
||||
this.natsService.subscribe<DakaoInboundEvent>(
|
||||
this.inboundSubject,
|
||||
(event) => this.handleEvent(event),
|
||||
);
|
||||
this.logger.log(
|
||||
`Dakao inbound subscriber ready on subject="${this.inboundSubject}"`,
|
||||
);
|
||||
}
|
||||
|
||||
private async handleEvent(event: DakaoInboundEvent): Promise<void> {
|
||||
if (!this.validate(event)) return;
|
||||
|
||||
if (this.botUserId && event.userId === this.botUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const logIdKey = this.deriveLogIdKey(event);
|
||||
if (logIdKey && this.idempotency.has(logIdKey)) {
|
||||
return;
|
||||
}
|
||||
if (logIdKey) this.idempotency.remember(logIdKey);
|
||||
|
||||
let communityId: mongoose.Types.ObjectId;
|
||||
try {
|
||||
communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId(
|
||||
event.projectId,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
if (err.code === 'invalid_project_id') {
|
||||
this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`);
|
||||
return;
|
||||
}
|
||||
if (err.code === 'community_not_found') {
|
||||
// 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만.
|
||||
this.logger.warn(`Unknown dakao projectId: ${event.projectId}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
let segments: DakaoSegment[];
|
||||
const senderNickname = this.resolveSenderNickname(event);
|
||||
const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
try {
|
||||
const command = parseCommand(event.origin.chatLog.message);
|
||||
|
||||
switch (command.kind) {
|
||||
case 'match-list':
|
||||
segments = await this.matchListHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
});
|
||||
break;
|
||||
case 'account-register':
|
||||
segments = await this.accountRegisterHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
gameName: command.gameName,
|
||||
tagLine: command.tagLine,
|
||||
});
|
||||
break;
|
||||
case 'match-join':
|
||||
segments = await this.matchJoinHandler.handle({
|
||||
communityId,
|
||||
matchId: command.matchId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
gameName: command.gameName,
|
||||
tagLine: command.tagLine,
|
||||
positions: command.positions.positions,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
await this.publisher.sendMessage({
|
||||
chatroomId: event.chatroomId,
|
||||
segments,
|
||||
correlationId,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof CommandParseError) {
|
||||
// not_a_command 는 명령이 아닌 일반 메시지 → 무시.
|
||||
if (err.code === 'not_a_command') return;
|
||||
await this.publisher.sendMessage({
|
||||
chatroomId: event.chatroomId,
|
||||
segments: this.parseErrorReply(event, senderNickname, err),
|
||||
correlationId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.logger.error(
|
||||
`Unhandled dakao event error: ${(err as Error)?.stack ?? err}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private validate(event: unknown): event is DakaoInboundEvent {
|
||||
if (!event || typeof event !== 'object') return false;
|
||||
const e = event as Partial<DakaoInboundEvent>;
|
||||
if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false;
|
||||
if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0)
|
||||
return false;
|
||||
if (typeof e.nickname !== 'string') return false;
|
||||
if (typeof e.userId !== 'string' || e.userId.length === 0) return false;
|
||||
if (!e.origin || typeof e.origin !== 'object') return false;
|
||||
const chatLog = (e.origin as { chatLog?: unknown }).chatLog;
|
||||
if (!chatLog || typeof chatLog !== 'object') return false;
|
||||
if (typeof (chatLog as { message?: unknown }).message !== 'string')
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
|
||||
const serialized = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
return serialized ? `${event.projectId}:${serialized}` : null;
|
||||
}
|
||||
|
||||
private serializeDakaoLong(value: DakaoLong | string | undefined): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (!value || typeof value !== 'object') return '';
|
||||
const high = BigInt(value.high ?? 0);
|
||||
const low = BigInt.asUintN(32, BigInt(value.low ?? 0));
|
||||
const combined = (high << 32n) | low;
|
||||
return value.unsigned
|
||||
? BigInt.asUintN(64, combined).toString()
|
||||
: BigInt.asIntN(64, combined).toString();
|
||||
}
|
||||
|
||||
private resolveSenderNickname(event: DakaoInboundEvent): string {
|
||||
const primary = event.nickname?.trim();
|
||||
if (primary) return primary;
|
||||
const fallback = event.origin.authorNickname?.trim();
|
||||
return fallback ?? '';
|
||||
}
|
||||
|
||||
private parseErrorReply(
|
||||
event: DakaoInboundEvent,
|
||||
senderNickname: string,
|
||||
err: CommandParseError,
|
||||
): DakaoSegment[] {
|
||||
const head: DakaoSegment[] = [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: event.userId,
|
||||
displayText: senderNickname,
|
||||
},
|
||||
];
|
||||
const text = ((): string => {
|
||||
switch (err.code) {
|
||||
case 'unknown_command':
|
||||
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
case 'usage':
|
||||
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
case 'invalid_match_id':
|
||||
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
|
||||
case 'invalid_riot_id':
|
||||
return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`;
|
||||
case 'invalid_position':
|
||||
return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿) 사용.`;
|
||||
default:
|
||||
return ` 명령을 처리할 수 없습니다.`;
|
||||
}
|
||||
})();
|
||||
return [...head, { kind: 'text', text }];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// dakao NATS contracts
|
||||
// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트
|
||||
// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령
|
||||
// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과
|
||||
|
||||
// ===== Inbound =====
|
||||
export interface DakaoLong {
|
||||
high?: number;
|
||||
low?: number;
|
||||
unsigned?: boolean;
|
||||
}
|
||||
|
||||
export interface DakaoOriginChatLog {
|
||||
logId: DakaoLong | string;
|
||||
chatId: DakaoLong | string;
|
||||
authorId: DakaoLong | string;
|
||||
type: number;
|
||||
sendAt: number;
|
||||
message: string;
|
||||
prevId?: DakaoLong | string;
|
||||
msgId?: number;
|
||||
revision?: number;
|
||||
scope?: number;
|
||||
}
|
||||
|
||||
export interface DakaoOrigin {
|
||||
chatId: DakaoLong | string;
|
||||
logId: DakaoLong | string;
|
||||
authorNickname?: string;
|
||||
chatLog: DakaoOriginChatLog;
|
||||
noSeen?: boolean;
|
||||
notiRead?: boolean;
|
||||
li?: number;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export interface DakaoInboundEvent {
|
||||
projectId: string;
|
||||
chatroomId: string;
|
||||
nickname: string;
|
||||
userId: string;
|
||||
origin: DakaoOrigin;
|
||||
}
|
||||
|
||||
// ===== Outbound: chat.send-message =====
|
||||
export interface DakaoTextSegment {
|
||||
kind: 'text';
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface DakaoMentionSegment {
|
||||
kind: 'mention';
|
||||
userId: string;
|
||||
displayText: string;
|
||||
}
|
||||
|
||||
export interface DakaoEmoticonSegment {
|
||||
kind: 'emoticon';
|
||||
id: string;
|
||||
altText: string;
|
||||
}
|
||||
|
||||
export type DakaoSegment =
|
||||
| DakaoTextSegment
|
||||
| DakaoMentionSegment
|
||||
| DakaoEmoticonSegment;
|
||||
|
||||
export interface DakaoSendMessagePayload {
|
||||
chatroomId: string;
|
||||
segments: DakaoSegment[];
|
||||
attachment?: string | Record<string, unknown>;
|
||||
type?: number;
|
||||
noSeen?: boolean;
|
||||
scope?: number;
|
||||
silence?: boolean;
|
||||
}
|
||||
|
||||
export interface DakaoCommandEnvelope<TPayload> {
|
||||
schema: 'dakao.command.v1';
|
||||
id: string;
|
||||
type: string;
|
||||
source: string;
|
||||
correlationId?: string;
|
||||
replySubject?: string;
|
||||
payload: TPayload;
|
||||
}
|
||||
|
||||
// ===== Reply =====
|
||||
export interface DakaoResultEnvelope {
|
||||
schema: 'dakao.result.v1';
|
||||
id: string;
|
||||
type: string;
|
||||
status: 'succeeded' | 'failed';
|
||||
handledAt: string;
|
||||
correlationId?: string;
|
||||
result?: Record<string, unknown>;
|
||||
error?: {
|
||||
code: string;
|
||||
message: string;
|
||||
retryable: boolean;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
import { AccountRegisterHandler } from './account-register.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeHandler(dakaoUserService?: Partial<DakaoUserService>) {
|
||||
return new AccountRegisterHandler({
|
||||
registerPrimaryRiotAccount: jest.fn(),
|
||||
...dakaoUserService,
|
||||
} as unknown as DakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
};
|
||||
|
||||
describe('AccountRegisterHandler', () => {
|
||||
it('translates already-registered Riot account errors', async () => {
|
||||
const handler = makeHandler({
|
||||
registerPrimaryRiotAccount: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new DakaoUserError(
|
||||
'riot_account_already_registered',
|
||||
'기존소환사#KR1',
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('이미 등록된 라이엇 계정'),
|
||||
}),
|
||||
]);
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('기존소환사#KR1'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
interface AccountRegisterHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
senderUserId: string;
|
||||
senderNickname: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AccountRegisterHandler {
|
||||
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
||||
|
||||
public async handle(
|
||||
params: AccountRegisterHandlerParams,
|
||||
): Promise<DakaoSegment[]> {
|
||||
try {
|
||||
const resolved = await this.dakaoUserService.registerPrimaryRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: params.gameName,
|
||||
tagLine: params.tagLine,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 계정 등록 완료` +
|
||||
`\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
return this.errorReply(params, this.translateUserError(err));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private errorReply(
|
||||
params: AccountRegisterHandlerParams,
|
||||
message: string,
|
||||
): DakaoSegment[] {
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ` ${message}` },
|
||||
];
|
||||
}
|
||||
|
||||
private translateUserError(err: DakaoUserError): string {
|
||||
switch (err.code) {
|
||||
case 'invalid_project_id':
|
||||
return '커뮤니티 식별자가 올바르지 않습니다.';
|
||||
case 'community_not_found':
|
||||
return '연결된 커뮤니티를 찾을 수 없습니다.';
|
||||
case 'riot_account_not_found':
|
||||
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_already_registered':
|
||||
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}). 변경이 필요하면 운영자에게 문의해주세요.`;
|
||||
case 'riot_account_conflict':
|
||||
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_lookup_failed':
|
||||
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
import { MatchJoinHandler } from './match-join.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
function makeHandler(overrides?: {
|
||||
matchService?: Partial<MatchService>;
|
||||
dakaoUserService?: Partial<DakaoUserService>;
|
||||
}): MatchJoinHandler {
|
||||
const matchService = {
|
||||
join: jest.fn(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
resolveRiotAccount: jest.fn(),
|
||||
...overrides?.dakaoUserService,
|
||||
} as unknown as DakaoUserService;
|
||||
return new MatchJoinHandler(matchService, dakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
positions: ['MID', 'TOP'] as const,
|
||||
};
|
||||
|
||||
describe('MatchJoinHandler', () => {
|
||||
it('rejects invalid match id without touching services', async () => {
|
||||
const handler = makeHandler();
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'not-an-id',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('유효하지 않은 내전 ID'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('replies with success and uses input position priority', async () => {
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}, {}, {}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const resolveRiotAccount = jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||
});
|
||||
const handler = makeHandler({
|
||||
matchService: { join } as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(resolveRiotAccount).toHaveBeenCalledWith({
|
||||
communityId: baseParams.communityId,
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
expect(join).toHaveBeenCalledWith({
|
||||
matchId: expect.any(mongoose.Types.ObjectId),
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'TOP', priority: 2 },
|
||||
],
|
||||
riotPuuid: 'puuid-1',
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('신청 완료 (3/10)'),
|
||||
});
|
||||
});
|
||||
|
||||
it('translates riot_account_not_found errors', async () => {
|
||||
const handler = makeHandler({
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new DakaoUserError('riot_account_not_found', '프리리#KR1'),
|
||||
),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('라이엇 계정을 찾을 수 없습니다'),
|
||||
});
|
||||
});
|
||||
|
||||
it('translates match BadRequest into korean', async () => {
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
join: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new BadRequestException('Match is full.')),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'p', gameName: 'g', tagLine: 't' },
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('정원이 가득'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { Position, PositionPreference } from '../../global/database/schema';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
interface JoinHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: string;
|
||||
senderUserId: string; // kakaoTalkId
|
||||
senderNickname: string; // kakaoTalkNickname
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchJoinHandler {
|
||||
constructor(
|
||||
private readonly matchService: MatchService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
) {}
|
||||
|
||||
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
|
||||
if (!mongoose.isValidObjectId(params.matchId)) {
|
||||
return this.errorReply(params, '유효하지 않은 내전 ID 입니다.');
|
||||
}
|
||||
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
|
||||
|
||||
let resolved;
|
||||
try {
|
||||
resolved = await this.dakaoUserService.resolveRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: params.gameName,
|
||||
tagLine: params.tagLine,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
return this.errorReply(params, this.translateUserError(err));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const preferredPositions: PositionPreference[] = params.positions.map(
|
||||
(position, index) => ({ position, priority: index + 1 }),
|
||||
);
|
||||
|
||||
try {
|
||||
const match = await this.matchService.join({
|
||||
matchId: matchObjectId,
|
||||
userId: resolved.user._id,
|
||||
preferredPositions,
|
||||
riotPuuid: resolved.riotAccount.puuid,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
|
||||
`\n내전: ${match.title}` +
|
||||
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
|
||||
`\n포지션: ${params.positions.join(', ')}`,
|
||||
},
|
||||
];
|
||||
} 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: JoinHandlerParams,
|
||||
message: string,
|
||||
): DakaoSegment[] {
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ` ${message}` },
|
||||
];
|
||||
}
|
||||
|
||||
private translateUserError(err: DakaoUserError): string {
|
||||
switch (err.code) {
|
||||
case 'invalid_project_id':
|
||||
return '커뮤니티 식별자가 올바르지 않습니다.';
|
||||
case 'community_not_found':
|
||||
return '연결된 커뮤니티를 찾을 수 없습니다.';
|
||||
case 'riot_account_not_found':
|
||||
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_already_registered':
|
||||
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_conflict':
|
||||
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
|
||||
case 'riot_account_lookup_failed':
|
||||
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
|
||||
}
|
||||
}
|
||||
|
||||
private translateBadRequest(raw: string): string {
|
||||
if (raw.includes('different communities'))
|
||||
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
|
||||
if (raw.includes('not recruiting')) return '모집 중인 내전이 아닙니다.';
|
||||
if (raw.includes('full')) return '정원이 가득 찼습니다.';
|
||||
if (raw.includes('already joined')) return '이미 신청한 내전입니다.';
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
|
||||
@Injectable()
|
||||
export class MatchListHandler {
|
||||
constructor(private readonly matchService: MatchService) {}
|
||||
|
||||
public async handle(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
senderUserId: string;
|
||||
senderNickname: string;
|
||||
}): Promise<DakaoSegment[]> {
|
||||
const matches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
if (matches.length === 0) {
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ' 모집 중인 내전이 없습니다.' },
|
||||
];
|
||||
}
|
||||
|
||||
const lines = matches.map((m, i) => {
|
||||
const id = (m._id as mongoose.Types.ObjectId).toString();
|
||||
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 [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <ID> <닉네임>#<태그> <포지션1>,<포지션2>`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function formatScheduledAt(date: Date): string {
|
||||
// YYYY-MM-DD 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 hh = String(kst.getUTCHours()).padStart(2, '0');
|
||||
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
||||
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
const TTL_MS = 5 * 60 * 1000;
|
||||
const MAX_ENTRIES = 5000;
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyCache {
|
||||
private readonly entries = new Map<string, number>();
|
||||
|
||||
public has(key: string): boolean {
|
||||
const expiresAt = this.entries.get(key);
|
||||
if (expiresAt === undefined) return false;
|
||||
if (expiresAt < Date.now()) {
|
||||
this.entries.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public remember(key: string): void {
|
||||
this.evictExpired();
|
||||
if (this.entries.size >= MAX_ENTRIES) {
|
||||
const oldestKey = this.entries.keys().next().value;
|
||||
if (oldestKey !== undefined) this.entries.delete(oldestKey);
|
||||
}
|
||||
this.entries.set(key, Date.now() + TTL_MS);
|
||||
}
|
||||
|
||||
private evictExpired(): void {
|
||||
const now = Date.now();
|
||||
for (const [key, expiresAt] of this.entries) {
|
||||
if (expiresAt < now) this.entries.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { CommandParseError, parseCommand } from './command.parser';
|
||||
|
||||
describe('parseCommand', () => {
|
||||
it('parses match-list command (목록)', () => {
|
||||
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
|
||||
});
|
||||
|
||||
it('parses match-list command (리스트)', () => {
|
||||
expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' });
|
||||
});
|
||||
|
||||
it('parses match-join command with simple riot id', () => {
|
||||
const result = parseCommand(
|
||||
'!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑',
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
if (result.kind === 'match-join') {
|
||||
expect(result.positions.positions).toEqual(['MID', 'TOP']);
|
||||
}
|
||||
});
|
||||
|
||||
it('handles riot game name with spaces', () => {
|
||||
const result = parseCommand(
|
||||
'!내전 신청 69b63bc96da18dfdb218ee8c hello world#KR1 미드,서폿',
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
gameName: 'hello world',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes hidden unicode differences in riot id', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
const result = parseCommand(
|
||||
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses account register command', () => {
|
||||
expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({
|
||||
kind: 'account-register',
|
||||
gameName: 'hello world',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes account register riot id', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
expect(
|
||||
parseCommand(`!내전 계정등록 ${decomposedGameName}\u200B#KR1\uFEFF`),
|
||||
).toEqual({
|
||||
kind: 'account-register',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws not_a_command for non-prefix messages', () => {
|
||||
expect(() => parseCommand('안녕하세요')).toThrow(/not_a_command/);
|
||||
});
|
||||
|
||||
it('throws unknown_command for unrecognized subcommands', () => {
|
||||
expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/);
|
||||
});
|
||||
|
||||
it('throws invalid_match_id for non-objectid match', () => {
|
||||
expect(() =>
|
||||
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'),
|
||||
).toThrow(/invalid_match_id/);
|
||||
});
|
||||
|
||||
it('throws invalid_riot_id when # missing', () => {
|
||||
expect(() =>
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
|
||||
).toThrow(/invalid_riot_id/);
|
||||
});
|
||||
|
||||
it('throws invalid_position for too few positions', () => {
|
||||
expect(() => {
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드');
|
||||
}).toThrow(CommandParseError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { ParsedPositions, parsePositionList } from './position.parser';
|
||||
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||
|
||||
export type DakaoCommand =
|
||||
| { kind: 'match-list' }
|
||||
| {
|
||||
kind: 'account-register';
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
}
|
||||
| {
|
||||
kind: 'match-join';
|
||||
matchId: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
positions: ParsedPositions;
|
||||
};
|
||||
|
||||
export class CommandParseError extends Error {
|
||||
constructor(
|
||||
public readonly code:
|
||||
| 'not_a_command'
|
||||
| 'unknown_command'
|
||||
| 'usage'
|
||||
| 'invalid_riot_id'
|
||||
| 'invalid_position'
|
||||
| 'invalid_match_id',
|
||||
public readonly detail?: string,
|
||||
) {
|
||||
super(`Command parse error: ${code}${detail ? ` (${detail})` : ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
const COMMAND_PREFIX = '!내전';
|
||||
|
||||
export function parseCommand(rawMessage: string): DakaoCommand {
|
||||
const message = rawMessage.trim();
|
||||
if (!message.startsWith(COMMAND_PREFIX)) {
|
||||
throw new CommandParseError('not_a_command');
|
||||
}
|
||||
|
||||
const rest = message.slice(COMMAND_PREFIX.length).trim();
|
||||
if (rest.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
const firstSpace = rest.search(/\s/);
|
||||
const subCommand = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
|
||||
const args = firstSpace === -1 ? '' : rest.slice(firstSpace + 1).trim();
|
||||
|
||||
switch (subCommand) {
|
||||
case '목록':
|
||||
case '리스트':
|
||||
return { kind: 'match-list' };
|
||||
case '신청':
|
||||
return parseJoinArgs(args);
|
||||
case '계정등록':
|
||||
return parseAccountRegisterArgs(args);
|
||||
default:
|
||||
throw new CommandParseError('unknown_command', subCommand);
|
||||
}
|
||||
}
|
||||
|
||||
function parseAccountRegisterArgs(args: string): DakaoCommand {
|
||||
if (args.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
const hashIndex = args.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === args.length - 1) {
|
||||
throw new CommandParseError('invalid_riot_id', args);
|
||||
}
|
||||
|
||||
const gameName = normalizeRiotIdPart(args.slice(0, hashIndex));
|
||||
const tagLine = normalizeRiotIdPart(args.slice(hashIndex + 1));
|
||||
if (gameName.length === 0 || tagLine.length === 0) {
|
||||
throw new CommandParseError('invalid_riot_id', args);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'account-register',
|
||||
gameName,
|
||||
tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJoinArgs(args: string): DakaoCommand {
|
||||
if (args.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId.
|
||||
// 형식: <matchId> <gameName...>#<tagLine> <pos1>,<pos2>...
|
||||
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
|
||||
const lastSpace = args.lastIndexOf(' ');
|
||||
if (lastSpace === -1) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
const positionPart = args.slice(lastSpace + 1).trim();
|
||||
const head = args.slice(0, lastSpace).trim();
|
||||
if (positionPart.length === 0 || head.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
const headSpace = head.indexOf(' ');
|
||||
if (headSpace === -1) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
const matchId = head.slice(0, headSpace).trim();
|
||||
const riotId = head.slice(headSpace + 1).trim();
|
||||
|
||||
if (!isObjectIdHex(matchId)) {
|
||||
throw new CommandParseError('invalid_match_id', matchId);
|
||||
}
|
||||
|
||||
const hashIndex = riotId.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === riotId.length - 1) {
|
||||
throw new CommandParseError('invalid_riot_id', riotId);
|
||||
}
|
||||
const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex));
|
||||
const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1));
|
||||
if (gameName.length === 0 || tagLine.length === 0) {
|
||||
throw new CommandParseError('invalid_riot_id', riotId);
|
||||
}
|
||||
|
||||
let positions: ParsedPositions;
|
||||
try {
|
||||
positions = parsePositionList(positionPart);
|
||||
} catch (err) {
|
||||
throw new CommandParseError(
|
||||
'invalid_position',
|
||||
(err as Error)?.message ?? positionPart,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchId,
|
||||
gameName,
|
||||
tagLine,
|
||||
positions,
|
||||
};
|
||||
}
|
||||
|
||||
function isObjectIdHex(value: string): boolean {
|
||||
return /^[a-f0-9]{24}$/i.test(value);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { parsePositionList, PositionParseError } from './position.parser';
|
||||
|
||||
describe('parsePositionList', () => {
|
||||
it('parses two korean positions in priority order', () => {
|
||||
const result = parsePositionList('미드,탑');
|
||||
expect(result.positions).toEqual(['MID', 'TOP']);
|
||||
});
|
||||
|
||||
it('parses english aliases case-insensitively', () => {
|
||||
const result = parsePositionList('JGL, sup');
|
||||
expect(result.positions).toEqual(['JGL', 'SUP']);
|
||||
});
|
||||
|
||||
it('accepts up to 5 distinct positions', () => {
|
||||
const result = parsePositionList('탑,정글,미드,원딜,서폿');
|
||||
expect(result.positions).toEqual(['TOP', 'JGL', 'MID', 'ADC', 'SUP']);
|
||||
});
|
||||
|
||||
it('rejects when fewer than 2 positions', () => {
|
||||
expect(() => parsePositionList('미드')).toThrow(PositionParseError);
|
||||
expect(() => parsePositionList('미드')).toThrow(/too_few/);
|
||||
});
|
||||
|
||||
it('rejects when more than 5 positions', () => {
|
||||
expect(() => parsePositionList('탑,정글,미드,원딜,서폿,바텀')).toThrow(
|
||||
/too_many/,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects duplicates after alias normalization', () => {
|
||||
expect(() => parsePositionList('미드,mid')).toThrow(/duplicate/);
|
||||
});
|
||||
|
||||
it('rejects unknown tokens', () => {
|
||||
expect(() => parsePositionList('미드,캐리')).toThrow(/unknown/);
|
||||
});
|
||||
|
||||
it('rejects empty input', () => {
|
||||
expect(() => parsePositionList('')).toThrow(/empty/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { Position } from '../../global/database/schema';
|
||||
|
||||
const POSITION_ALIASES: Record<string, Position> = {
|
||||
// TOP
|
||||
top: 'TOP',
|
||||
탑: 'TOP',
|
||||
top레인: 'TOP',
|
||||
// JUNGLE
|
||||
jgl: 'JGL',
|
||||
jungle: 'JGL',
|
||||
jng: 'JGL',
|
||||
jg: 'JGL',
|
||||
정글: 'JGL',
|
||||
정글러: 'JGL',
|
||||
// MID
|
||||
mid: 'MID',
|
||||
middle: 'MID',
|
||||
미드: 'MID',
|
||||
// ADC (BOTTOM)
|
||||
adc: 'ADC',
|
||||
ad: 'ADC',
|
||||
bot: 'ADC',
|
||||
bottom: 'ADC',
|
||||
원딜: 'ADC',
|
||||
바텀: 'ADC',
|
||||
// SUP
|
||||
sup: 'SUP',
|
||||
supp: 'SUP',
|
||||
support: 'SUP',
|
||||
서폿: 'SUP',
|
||||
서포터: 'SUP',
|
||||
};
|
||||
|
||||
export interface ParsedPositions {
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
export class PositionParseError extends Error {
|
||||
constructor(
|
||||
public readonly reason:
|
||||
| 'too_few'
|
||||
| 'too_many'
|
||||
| 'duplicate'
|
||||
| 'unknown'
|
||||
| 'empty',
|
||||
public readonly token?: string,
|
||||
) {
|
||||
super(`Position parse error: ${reason}${token ? ` (${token})` : ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function parsePositionList(input: string): ParsedPositions {
|
||||
const trimmed = input.trim();
|
||||
if (trimmed.length === 0) {
|
||||
throw new PositionParseError('empty');
|
||||
}
|
||||
|
||||
const tokens = trimmed
|
||||
.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
|
||||
if (tokens.length < 2) {
|
||||
throw new PositionParseError('too_few');
|
||||
}
|
||||
if (tokens.length > 5) {
|
||||
throw new PositionParseError('too_many');
|
||||
}
|
||||
|
||||
const positions: Position[] = [];
|
||||
const seen = new Set<Position>();
|
||||
|
||||
for (const token of tokens) {
|
||||
const key = token.toLowerCase().replace(/\s+/g, '');
|
||||
const mapped = POSITION_ALIASES[key];
|
||||
if (!mapped) {
|
||||
throw new PositionParseError('unknown', token);
|
||||
}
|
||||
if (seen.has(mapped)) {
|
||||
throw new PositionParseError('duplicate', token);
|
||||
}
|
||||
seen.add(mapped);
|
||||
positions.push(mapped);
|
||||
}
|
||||
|
||||
return { positions };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
const ZERO_WIDTH_CHARACTERS = /[\u200B-\u200D\uFEFF]/g;
|
||||
|
||||
export function normalizeRiotIdPart(value: string): string {
|
||||
return value.replace(ZERO_WIDTH_CHARACTERS, '').trim().normalize('NFC');
|
||||
}
|
||||
|
||||
export function formatCodePoints(value: string): string {
|
||||
return Array.from(value)
|
||||
.map((char) => {
|
||||
const codePoint = char.codePointAt(0);
|
||||
return `U+${codePoint?.toString(16).toUpperCase().padStart(4, '0')}`;
|
||||
})
|
||||
.join(' ');
|
||||
}
|
||||
Reference in new issue
Block a user