feat(api): add Dakao commands
This commit is contained in:
1 parent
57e3c68ea8
commit
efa133a1a2
29 files changed
+5335
No files matched your search
@@ -0,0 +1,171 @@
|
||||
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 { 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>;
|
||||
community?: Record<string, unknown> | null;
|
||||
riotAccountService?: Partial<RiotAccountService>;
|
||||
enrichmentService?: Partial<RiotAccountEnrichmentService>;
|
||||
}) {
|
||||
const findOneAndUpdate = jest
|
||||
.fn()
|
||||
.mockReturnValue(makeQuery(params.user as UserDocument));
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue(makeQuery(params.community ?? {})),
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'user') return { findOneAndUpdate };
|
||||
if (name === 'community') return { findById };
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} 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,
|
||||
findById,
|
||||
riotAccountService,
|
||||
enrichmentService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('DakaoUserService', () => {
|
||||
it('registers an additional Riot account when the user already has one', 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>,
|
||||
riotAccountService: {
|
||||
getByRiotId: jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-2',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
}),
|
||||
},
|
||||
enrichmentService: {
|
||||
enrichRiotAccount: jest.fn().mockResolvedValue({ account: null }),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.registerRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
});
|
||||
|
||||
expect(result.riotAccount).toMatchObject({
|
||||
puuid: 'puuid-2',
|
||||
gameName: '새소환사',
|
||||
tagLine: 'KR2',
|
||||
isPrimary: false,
|
||||
});
|
||||
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({
|
||||
puuid: 'puuid-1',
|
||||
isPrimary: true,
|
||||
});
|
||||
expect(result.user.riotAccounts).toHaveLength(2);
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('user');
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('community');
|
||||
expect(riotAccountService.getByRiotId).toHaveBeenCalledWith(
|
||||
'새소환사',
|
||||
'KR2',
|
||||
{
|
||||
region: 'asia',
|
||||
},
|
||||
);
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: expect.any(mongoose.Types.ObjectId),
|
||||
puuid: 'puuid-2',
|
||||
options: { force: true, platform: 'kr', region: 'asia' },
|
||||
}),
|
||||
);
|
||||
expect(save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reuses an already attached Riot account by puuid', async () => {
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
const existingAccount = {
|
||||
puuid: 'puuid-1',
|
||||
gameName: '기존소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
} as RiotAccount;
|
||||
const { service, enrichmentService } = makeService({
|
||||
user: {
|
||||
_id: objectId('222222222222222222222222'),
|
||||
riotAccounts: [existingAccount],
|
||||
save,
|
||||
} as Partial<UserDocument>,
|
||||
riotAccountService: {
|
||||
getByRiotId: jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-1',
|
||||
gameName: '바뀐소환사',
|
||||
tagLine: 'KR1',
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.registerRiotAccount({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '바뀐소환사',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
|
||||
expect(result.user.riotAccounts).toHaveLength(1);
|
||||
expect(result.riotAccount).toMatchObject({
|
||||
puuid: 'puuid-1',
|
||||
gameName: '바뀐소환사',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
});
|
||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||
expect(save).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,428 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose, { isValidObjectId } from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
Position,
|
||||
PositionPreference,
|
||||
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 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> {
|
||||
const user = await this.upsertUser(context);
|
||||
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;
|
||||
|
||||
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) {
|
||||
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 };
|
||||
}
|
||||
|
||||
const existingByPuuid = user.riotAccounts.find(
|
||||
(account) => account.puuid === dto.puuid,
|
||||
);
|
||||
if (existingByPuuid) {
|
||||
if (
|
||||
existingByPuuid.gameName !== nextGameName ||
|
||||
existingByPuuid.tagLine !== nextTagLine
|
||||
) {
|
||||
existingByPuuid.gameName = nextGameName;
|
||||
existingByPuuid.tagLine = nextTagLine;
|
||||
await user.save();
|
||||
}
|
||||
return { user, riotAccount: existingByPuuid };
|
||||
}
|
||||
|
||||
return this.attachRiotAccount({
|
||||
user,
|
||||
puuid: dto.puuid,
|
||||
gameName: nextGameName,
|
||||
tagLine: nextTagLine,
|
||||
platform: routing.platform,
|
||||
region: routing.region,
|
||||
});
|
||||
}
|
||||
|
||||
public async registerRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
return this.resolveRiotAccount(context);
|
||||
}
|
||||
|
||||
public async registerPrimaryRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
return this.registerRiotAccount(context);
|
||||
}
|
||||
|
||||
public async registerPreferredPositions(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
kakaoTalkNickname: string;
|
||||
positions: Position[];
|
||||
}): Promise<UserDocument> {
|
||||
const user = await this.upsertUser({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.kakaoTalkId,
|
||||
kakaoTalkNickname: params.kakaoTalkNickname,
|
||||
});
|
||||
user.preferredPositions = this.toPositionPreferences(params.positions);
|
||||
await user.save();
|
||||
return user;
|
||||
}
|
||||
|
||||
private toPositionPreferences(positions: Position[]): PositionPreference[] {
|
||||
return positions.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
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,37 @@
|
||||
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 { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, MatchModule],
|
||||
providers: [
|
||||
{
|
||||
provide: DAKAO_OPTIONS,
|
||||
useFactory: createDefaultDakaoOptions,
|
||||
},
|
||||
DakaoPublisher,
|
||||
DakaoSubscriber,
|
||||
DakaoUserService,
|
||||
IdempotencyCache,
|
||||
AccountRegisterHandler,
|
||||
MatchListHandler,
|
||||
MatchJoinHandler,
|
||||
MatchCancelHandler,
|
||||
PreferredPositionRegisterHandler,
|
||||
],
|
||||
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,230 @@
|
||||
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 { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.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,
|
||||
private readonly matchCancelHandler: MatchCancelHandler,
|
||||
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
||||
) {}
|
||||
|
||||
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,
|
||||
matchAndRiotId: command.matchAndRiotId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
positions: command.positions?.positions,
|
||||
});
|
||||
break;
|
||||
case 'preferred-position-register':
|
||||
segments = await this.preferredPositionRegisterHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
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({
|
||||
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 ` 알 수 없는 명령어입니다. 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`;
|
||||
case 'usage':
|
||||
return ` 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션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,73 @@
|
||||
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({
|
||||
registerRiotAccount: jest.fn(),
|
||||
...dakaoUserService,
|
||||
} as unknown as DakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
};
|
||||
|
||||
describe('AccountRegisterHandler', () => {
|
||||
it('registers a Riot account through DakaoUserService', async () => {
|
||||
const registerRiotAccount = jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { gameName: '프리리', tagLine: 'KR1' },
|
||||
});
|
||||
const handler = makeHandler({
|
||||
registerRiotAccount,
|
||||
});
|
||||
|
||||
const segments = await handler.handle(baseParams);
|
||||
|
||||
expect(registerRiotAccount).toHaveBeenCalledWith({
|
||||
communityId: baseParams.communityId,
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('등록 계정: 프리리#KR1'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('translates Riot account conflict errors', async () => {
|
||||
const handler = makeHandler({
|
||||
registerRiotAccount: jest
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new DakaoUserError('riot_account_conflict', '기존소환사#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.registerRiotAccount({
|
||||
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,168 @@
|
||||
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(),
|
||||
list: 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 unknown match reference without cancelling', async () => {
|
||||
const cancelJoin = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
cancelJoin,
|
||||
list: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'not-an-id',
|
||||
});
|
||||
|
||||
expect(cancelJoin).not.toHaveBeenCalled();
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('모집 중인 내전이 없습니다'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
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('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({
|
||||
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,126 @@
|
||||
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';
|
||||
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||
|
||||
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[]> {
|
||||
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
});
|
||||
if (!user) {
|
||||
return this.errorReply(
|
||||
params,
|
||||
'먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.',
|
||||
);
|
||||
}
|
||||
|
||||
const matchTarget = await this.resolveCancelTarget(params);
|
||||
if (typeof matchTarget === 'string') {
|
||||
return this.errorReply(params, matchTarget);
|
||||
}
|
||||
|
||||
try {
|
||||
const match = await this.matchService.cancelJoin({
|
||||
matchId: matchTarget,
|
||||
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 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,
|
||||
): 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
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(),
|
||||
list: jest.fn(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
resolveRiotAccount: jest.fn(),
|
||||
findUserByKakaoTalkId: jest.fn(),
|
||||
...overrides?.dakaoUserService,
|
||||
} as unknown as DakaoUserService;
|
||||
return new MatchJoinHandler(matchService, dakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
positions: ['MID', 'TOP'] as const,
|
||||
};
|
||||
|
||||
describe('MatchJoinHandler', () => {
|
||||
it('rejects missing match reference when multiple matches are recruiting', async () => {
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: objectId('333333333333333333333333'), title: '저녁 내전' },
|
||||
{ _id: objectId('444444444444444444444444'), title: '심야 내전' },
|
||||
]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: '프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
expect(resolveRiotAccount).not.toHaveBeenCalled();
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('코드 또는 제목'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
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('uses the only recruiting match when match reference is omitted', 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: '저녁 내전' }]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||
user: { _id: objectId('222222222222222222222222') },
|
||||
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: '프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(join).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
}),
|
||||
);
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('신청 완료 (1/10)'),
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves a unique recruiting match by title prefix', 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: '저녁 내전' },
|
||||
{ _id: objectId('444444444444444444444444'), title: '심야 내전' },
|
||||
]),
|
||||
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: '저녁 프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(join).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
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('uses registered account and preferred positions for abbreviated join', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const userId = objectId('222222222222222222222222');
|
||||
const join = jest.fn().mockResolvedValue({
|
||||
title: '저녁 내전',
|
||||
participants: [{}],
|
||||
maxParticipants: 10,
|
||||
});
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: userId,
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'JGL', priority: 2 },
|
||||
],
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: 'AB12',
|
||||
positions: undefined,
|
||||
});
|
||||
|
||||
expect(resolveRiotAccount).not.toHaveBeenCalled();
|
||||
expect(join).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
userId,
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'JGL', priority: 2 },
|
||||
],
|
||||
riotPuuid: 'puuid-1',
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('계정: 프리리#KR1'),
|
||||
});
|
||||
});
|
||||
|
||||
it('asks abbreviated join users to register missing preferred positions', async () => {
|
||||
const matchId = objectId('333333333333333333333333');
|
||||
const join = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||
]),
|
||||
join,
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||
_id: objectId('222222222222222222222222'),
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
preferredPositions: [],
|
||||
}),
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: 'AB12',
|
||||
positions: undefined,
|
||||
});
|
||||
|
||||
expect(join).not.toHaveBeenCalled();
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('선호포지션등록'),
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects ambiguous title prefixes', async () => {
|
||||
const resolveRiotAccount = jest.fn();
|
||||
const handler = makeHandler({
|
||||
matchService: {
|
||||
list: jest.fn().mockResolvedValue([
|
||||
{ _id: objectId('333333333333333333333333'), title: '저녁 내전 A' },
|
||||
{ _id: objectId('444444444444444444444444'), title: '저녁 내전 B' },
|
||||
]),
|
||||
} as Partial<MatchService>,
|
||||
dakaoUserService: {
|
||||
resolveRiotAccount,
|
||||
} as Partial<DakaoUserService>,
|
||||
});
|
||||
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchAndRiotId: '저녁 프리리#KR1',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
|
||||
expect(resolveRiotAccount).not.toHaveBeenCalled();
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('여러 개와 겹칩니다'),
|
||||
});
|
||||
});
|
||||
|
||||
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,352 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import {
|
||||
MatchDocument,
|
||||
Position,
|
||||
PositionPreference,
|
||||
RiotAccount,
|
||||
UserDocument,
|
||||
} from '../../global/database/schema';
|
||||
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;
|
||||
matchAndRiotId: string;
|
||||
senderUserId: string; // kakaoTalkId
|
||||
senderNickname: string; // kakaoTalkNickname
|
||||
positions?: Position[];
|
||||
}
|
||||
|
||||
interface ResolvedJoinTarget {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchJoinHandler {
|
||||
constructor(
|
||||
private readonly matchService: MatchService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
) {}
|
||||
|
||||
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
|
||||
const joinTarget = await this.resolveJoinTarget(params);
|
||||
if (typeof joinTarget === 'string') {
|
||||
return this.errorReply(params, joinTarget);
|
||||
}
|
||||
|
||||
let resolved:
|
||||
| { user: UserDocument; riotAccount: RiotAccount }
|
||||
| string;
|
||||
try {
|
||||
resolved =
|
||||
joinTarget.gameName && joinTarget.tagLine
|
||||
? await this.dakaoUserService.resolveRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: joinTarget.gameName,
|
||||
tagLine: joinTarget.tagLine,
|
||||
})
|
||||
: await this.resolveRegisteredRiotAccount(params);
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
return this.errorReply(params, this.translateUserError(err));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (typeof resolved === 'string') {
|
||||
return this.errorReply(params, resolved);
|
||||
}
|
||||
|
||||
const preferredPositions = this.resolvePreferredPositions(
|
||||
params.positions,
|
||||
resolved.user.preferredPositions,
|
||||
);
|
||||
if (typeof preferredPositions === 'string') {
|
||||
return this.errorReply(params, preferredPositions);
|
||||
}
|
||||
|
||||
try {
|
||||
const match = await this.matchService.join({
|
||||
matchId: joinTarget.matchId,
|
||||
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포지션: ${preferredPositions
|
||||
.map((entry) => entry.position)
|
||||
.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 async resolveJoinTarget(
|
||||
params: JoinHandlerParams,
|
||||
): Promise<ResolvedJoinTarget | string> {
|
||||
if (!params.matchAndRiotId.includes('#')) {
|
||||
return this.resolveJoinTargetWithoutRiotId(params);
|
||||
}
|
||||
|
||||
const riotId = this.parseRiotId(params.matchAndRiotId);
|
||||
if (typeof riotId === 'string') return riotId;
|
||||
|
||||
const objectIdMatch = riotId.gameNameWithOptionalMatchRef.match(
|
||||
/^([a-f0-9]{24})(?:\s+(.+))?$/i,
|
||||
);
|
||||
if (objectIdMatch) {
|
||||
const gameName = normalizeRiotIdPart(objectIdMatch[2] ?? '');
|
||||
if (!gameName) {
|
||||
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
|
||||
}
|
||||
return {
|
||||
matchId: new mongoose.Types.ObjectId(objectIdMatch[1]),
|
||||
gameName,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
const recruitingMatches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 50,
|
||||
});
|
||||
if (recruitingMatches.length === 0) {
|
||||
return '모집 중인 내전이 없습니다.';
|
||||
}
|
||||
|
||||
const titleTarget = this.resolveTitleTarget(
|
||||
riotId.gameNameWithOptionalMatchRef,
|
||||
recruitingMatches,
|
||||
);
|
||||
if (titleTarget.kind === 'matched') {
|
||||
return {
|
||||
matchId: titleTarget.match._id,
|
||||
gameName: titleTarget.gameName,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
if (titleTarget.kind === 'ambiguous') {
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
|
||||
if (recruitingMatches.length === 1) {
|
||||
return {
|
||||
matchId: recruitingMatches[0]._id,
|
||||
gameName: riotId.gameNameWithOptionalMatchRef,
|
||||
tagLine: riotId.tagLine,
|
||||
};
|
||||
}
|
||||
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private async resolveJoinTargetWithoutRiotId(
|
||||
params: JoinHandlerParams,
|
||||
): Promise<ResolvedJoinTarget | string> {
|
||||
const reference = params.matchAndRiotId.trim();
|
||||
if (/^[a-f0-9]{24}$/i.test(reference)) {
|
||||
return {
|
||||
matchId: new mongoose.Types.ObjectId(reference),
|
||||
};
|
||||
}
|
||||
|
||||
const recruitingMatches = await this.matchService.list({
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
limit: 50,
|
||||
});
|
||||
if (recruitingMatches.length === 0) {
|
||||
return '모집 중인 내전이 없습니다.';
|
||||
}
|
||||
|
||||
if (!reference) {
|
||||
if (recruitingMatches.length === 1) {
|
||||
return { matchId: recruitingMatches[0]._id };
|
||||
}
|
||||
return '모집 중인 내전이 여러 개입니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
const result = resolveRecruitingMatchReference(
|
||||
reference,
|
||||
recruitingMatches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return { matchId: result.match._id };
|
||||
}
|
||||
if (result.kind === 'ambiguous') {
|
||||
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||
}
|
||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
|
||||
}
|
||||
|
||||
private parseRiotId(
|
||||
value: string,
|
||||
): { gameNameWithOptionalMatchRef: string; tagLine: string } | string {
|
||||
const hashIndex = value.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === value.length - 1) {
|
||||
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
|
||||
}
|
||||
|
||||
const gameNameWithOptionalMatchRef = normalizeRiotIdPart(
|
||||
value.slice(0, hashIndex),
|
||||
);
|
||||
const tagLine = normalizeRiotIdPart(value.slice(hashIndex + 1));
|
||||
if (!gameNameWithOptionalMatchRef || !tagLine) {
|
||||
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
|
||||
}
|
||||
return { gameNameWithOptionalMatchRef, tagLine };
|
||||
}
|
||||
|
||||
private resolveTitleTarget(
|
||||
value: string,
|
||||
matches: MatchDocument[],
|
||||
):
|
||||
| { kind: 'matched'; match: MatchDocument; gameName: string }
|
||||
| { kind: 'ambiguous'; titles: string[] }
|
||||
| { kind: 'not-found' } {
|
||||
let ambiguousTitles: string[] | null = null;
|
||||
|
||||
for (const splitAt of splitPositionsFromRight(value)) {
|
||||
const matchTitlePrefix = value.slice(0, splitAt).trim();
|
||||
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
||||
if (!matchTitlePrefix || !gameName) continue;
|
||||
|
||||
const result = resolveRecruitingMatchReference(
|
||||
matchTitlePrefix,
|
||||
matches,
|
||||
);
|
||||
if (result.kind === 'matched') {
|
||||
return { kind: 'matched', match: result.match, gameName };
|
||||
}
|
||||
if (result.kind === 'ambiguous') {
|
||||
ambiguousTitles = result.titles;
|
||||
}
|
||||
}
|
||||
|
||||
return ambiguousTitles
|
||||
? { kind: 'ambiguous', titles: ambiguousTitles }
|
||||
: { kind: 'not-found' };
|
||||
}
|
||||
|
||||
private async resolveRegisteredRiotAccount(
|
||||
params: JoinHandlerParams,
|
||||
): Promise<{ user: UserDocument; riotAccount: RiotAccount } | string> {
|
||||
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
});
|
||||
if (!user) {
|
||||
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
|
||||
}
|
||||
|
||||
const riotAccount =
|
||||
user.riotAccounts.find((account) => account.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
if (!riotAccount) {
|
||||
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
|
||||
}
|
||||
|
||||
return { user, riotAccount };
|
||||
}
|
||||
|
||||
private resolvePreferredPositions(
|
||||
inputPositions: Position[] | undefined,
|
||||
registeredPositions: PositionPreference[],
|
||||
): PositionPreference[] | string {
|
||||
if (inputPositions?.length) {
|
||||
return inputPositions.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
const preferredPositions = [...(registeredPositions ?? [])]
|
||||
.sort((left, right) => left.priority - right.priority)
|
||||
.filter((entry) => entry.position);
|
||||
if (preferredPositions.length < 2) {
|
||||
return '선호포지션을 입력하거나 !내전 선호포지션등록 미드,정글 로 먼저 등록해주세요.';
|
||||
}
|
||||
|
||||
return preferredPositions;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
function splitPositionsFromRight(value: string): number[] {
|
||||
const positions: number[] = [];
|
||||
for (let index = value.length - 1; index >= 0; index -= 1) {
|
||||
if (/\s/.test(value[index])) positions.push(index);
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
@@ -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:'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
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 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 코드: ${m.shortCode}`;
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n선호포지션등록: !내전 선호포지션등록 미드,정글\n신청: !내전 신청 <코드> [닉네임#태그] [포지션1,포지션2]\n취소: !내전 취소 <코드>\n계정/선호포지션을 등록해두면 !내전 신청 <코드> 로 신청할 수 있습니다.`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function formatScheduledAt(date: Date): string {
|
||||
// M/D HH:mm (KST 표기)
|
||||
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
||||
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 `${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();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
import { PreferredPositionRegisterHandler } from './preferred-position-register.handler';
|
||||
|
||||
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||
|
||||
describe('PreferredPositionRegisterHandler', () => {
|
||||
it('registers preferred positions for abbreviated joins', async () => {
|
||||
const registerPreferredPositions = jest.fn().mockResolvedValue({
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'JGL', priority: 2 },
|
||||
],
|
||||
});
|
||||
const handler = new PreferredPositionRegisterHandler({
|
||||
registerPreferredPositions,
|
||||
} as unknown as DakaoUserService);
|
||||
|
||||
const segments = await handler.handle({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
positions: ['MID', 'JGL'],
|
||||
});
|
||||
|
||||
expect(registerPreferredPositions).toHaveBeenCalledWith({
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
kakaoTalkId: 'kakao-user-1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
positions: ['MID', 'JGL'],
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('선호 포지션 등록 완료'),
|
||||
});
|
||||
expect(segments[1]).toMatchObject({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('!내전 신청 <내전코드>'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { Position } from '../../global/database/schema';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
const POSITION_LABELS: Record<Position, string> = {
|
||||
TOP: '탑',
|
||||
JGL: '정글',
|
||||
MID: '미드',
|
||||
ADC: '원딜',
|
||||
SUP: '서포터',
|
||||
};
|
||||
|
||||
interface PreferredPositionRegisterHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
senderUserId: string;
|
||||
senderNickname: string;
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PreferredPositionRegisterHandler {
|
||||
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
||||
|
||||
public async handle(
|
||||
params: PreferredPositionRegisterHandlerParams,
|
||||
): Promise<DakaoSegment[]> {
|
||||
const user = await this.dakaoUserService.registerPreferredPositions({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
positions: params.positions,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text:
|
||||
` 선호 포지션 등록 완료` +
|
||||
`\n포지션: ${user.preferredPositions
|
||||
.sort((left, right) => left.priority - right.priority)
|
||||
.map((entry) => POSITION_LABELS[entry.position])
|
||||
.join(', ')}` +
|
||||
`\n이제 !내전 신청 <내전코드> 로 간단히 신청할 수 있습니다.`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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,166 @@
|
||||
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-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',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#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',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c hello world#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses hidden unicode differences in riot id input', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
const result = parseCommand(
|
||||
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: `69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1`,
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-join command without explicit match id', () => {
|
||||
const result = parseCommand('!내전 신청 프리리#KR1 미드,탑');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '프리리#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-join command with title prefix', () => {
|
||||
const result = parseCommand('!내전 신청 저녁 프리리#KR1 미드,탑');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '저녁 프리리#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses abbreviated match-join command with only match code', () => {
|
||||
expect(parseCommand('!내전 신청 cab1')).toEqual({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: 'cab1',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses match-join command with registered account and explicit positions', () => {
|
||||
const result = parseCommand('!내전 신청 cab1 미드,서포터');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: 'cab1',
|
||||
});
|
||||
if (result.kind === 'match-join') {
|
||||
expect(result.positions?.positions).toEqual(['MID', 'SUP']);
|
||||
}
|
||||
});
|
||||
|
||||
it('parses preferred position registration command', () => {
|
||||
const result = parseCommand('!내전 선호포지션등록 미드,SPT');
|
||||
expect(result).toMatchObject({
|
||||
kind: 'preferred-position-register',
|
||||
});
|
||||
if (result.kind === 'preferred-position-register') {
|
||||
expect(result.positions.positions).toEqual(['MID', 'SUP']);
|
||||
}
|
||||
});
|
||||
|
||||
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 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',
|
||||
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('allows non-objectid join match reference for title matching', () => {
|
||||
expect(
|
||||
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'),
|
||||
).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: 'not-an-id 프리리#KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('allows match-join without riot id for registered-account flow', () => {
|
||||
expect(
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 미드,탑'),
|
||||
).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '69b63bc96da18dfdb218ee8c',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws invalid_position for too few positions', () => {
|
||||
expect(() => {
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드');
|
||||
}).toThrow(CommandParseError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import {
|
||||
ParsedPositions,
|
||||
isPositionAlias,
|
||||
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';
|
||||
matchAndRiotId: string;
|
||||
positions?: ParsedPositions;
|
||||
}
|
||||
| {
|
||||
kind: 'match-cancel';
|
||||
matchId: string;
|
||||
}
|
||||
| {
|
||||
kind: 'preferred-position-register';
|
||||
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 '리스트':
|
||||
case '일정':
|
||||
return { kind: 'match-list' };
|
||||
case '신청':
|
||||
return parseJoinArgs(args);
|
||||
case '취소':
|
||||
case '참가취소':
|
||||
return parseCancelArgs(args);
|
||||
case '계정등록':
|
||||
return parseAccountRegisterArgs(args);
|
||||
case '선호포지션등록':
|
||||
case '포지션등록':
|
||||
return parsePreferredPositionRegisterArgs(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 parseCancelArgs(args: string): DakaoCommand {
|
||||
const matchId = args.trim();
|
||||
if (matchId.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-cancel',
|
||||
matchId,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJoinArgs(args: string): DakaoCommand {
|
||||
const trimmed = args.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return { kind: 'match-join', matchAndRiotId: '' };
|
||||
}
|
||||
|
||||
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞은 내전 식별자(선택)와 라이엇 ID.
|
||||
// 형식: [<matchId|title...>] <gameName...>#<tagLine> <pos1>,<pos2>...
|
||||
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
|
||||
const lastSpace = trimmed.lastIndexOf(' ');
|
||||
if (lastSpace === -1) {
|
||||
const singlePartPositions = tryParseTrailingPositions(trimmed);
|
||||
if (singlePartPositions) {
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: '',
|
||||
positions: singlePartPositions,
|
||||
};
|
||||
}
|
||||
return { kind: 'match-join', matchAndRiotId: trimmed };
|
||||
}
|
||||
|
||||
const trailingPart = trimmed.slice(lastSpace + 1).trim();
|
||||
const matchAndRiotId = trimmed.slice(0, lastSpace).trim();
|
||||
const positions = tryParseTrailingPositions(trailingPart);
|
||||
if (positions) {
|
||||
if (!matchAndRiotId) throw new CommandParseError('usage');
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchAndRiotId,
|
||||
positions,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchAndRiotId: trimmed,
|
||||
};
|
||||
}
|
||||
|
||||
function parsePreferredPositionRegisterArgs(args: string): DakaoCommand {
|
||||
if (args.trim().length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'preferred-position-register',
|
||||
positions: parsePositionsOrThrow(args),
|
||||
};
|
||||
}
|
||||
|
||||
function tryParseTrailingPositions(input: string): ParsedPositions | undefined {
|
||||
if (!input.includes(',') && !isPositionAlias(input)) return undefined;
|
||||
return parsePositionsOrThrow(input);
|
||||
}
|
||||
|
||||
function parsePositionsOrThrow(input: string): ParsedPositions {
|
||||
try {
|
||||
return parsePositionList(input);
|
||||
} catch (err) {
|
||||
throw new CommandParseError(
|
||||
'invalid_position',
|
||||
(err as Error)?.message ?? input,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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, SPT');
|
||||
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,97 @@
|
||||
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',
|
||||
spt: 'SUP',
|
||||
sp: '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 = normalizePositionAlias(token);
|
||||
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 };
|
||||
}
|
||||
|
||||
export function isPositionAlias(input: string): boolean {
|
||||
return Boolean(POSITION_ALIASES[normalizePositionAlias(input)]);
|
||||
}
|
||||
|
||||
function normalizePositionAlias(input: string): string {
|
||||
return input.toLowerCase().replace(/\s+/g, '');
|
||||
}
|
||||
@@ -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(' ');
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import 'reflect-metadata';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConnectionService } from './modules/global/database/connection.service';
|
||||
import { SecretModule } from './modules/global/secret/secret.module';
|
||||
import { MatchService } from './modules/match/match.service';
|
||||
import { DakaoUserService } from './modules/dakao/dakao-user.service';
|
||||
import { parsePositionList } from './modules/dakao/parsers/position.parser';
|
||||
import { normalizeRiotIdPart } from './modules/dakao/riot-id.util';
|
||||
import { RiotAccountEnrichmentService } from './modules/riot/riot-account-enrichment.service';
|
||||
import { RiotAccountService } from './modules/riot/riot-account.service';
|
||||
import { RiotChampionMasteryService } from './modules/riot/riot-champion-mastery.service';
|
||||
import { RiotClientService } from './modules/riot/riot.client.service';
|
||||
import { RiotLeagueService } from './modules/riot/riot-league.service';
|
||||
import { RiotSummonerService } from './modules/riot/riot-summoner.service';
|
||||
|
||||
process.env.NODE_ENV ??= 'dev';
|
||||
|
||||
const DEFAULT_INPUT = {
|
||||
projectId: '69985467365c75936c355318',
|
||||
matchId: '69ebe0adf627c11be2f020bb',
|
||||
senderId: '6657856481076543434',
|
||||
nickname: '집밖은 위험해/92/여/P',
|
||||
riotId: '집밖은 위험해#SOS',
|
||||
positions: 'SUP,MID',
|
||||
};
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: [
|
||||
resolve(__dirname, '../../project.env'),
|
||||
resolve(process.cwd(), 'apps/project.env'),
|
||||
resolve(process.cwd(), 'project.env'),
|
||||
],
|
||||
}),
|
||||
SecretModule,
|
||||
],
|
||||
providers: [
|
||||
ConnectionService,
|
||||
RiotClientService,
|
||||
RiotAccountService,
|
||||
RiotSummonerService,
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
DakaoUserService,
|
||||
MatchService,
|
||||
],
|
||||
})
|
||||
class SeedDakaoParticipantModule {}
|
||||
|
||||
async function loadMachineEnvFile() {
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||
if (!homeDir) return;
|
||||
|
||||
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||
|
||||
try {
|
||||
const file = await readFile(machineEnvFile, 'utf8');
|
||||
for (const rawLine of file.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
|
||||
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (!matched) continue;
|
||||
|
||||
const [, key, rawValue] = matched;
|
||||
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||
}
|
||||
} catch {
|
||||
// 로컬 machine env 파일이 없으면 무시한다.
|
||||
}
|
||||
}
|
||||
|
||||
function readInput() {
|
||||
const riotId = process.env.DAKAO_SEED_RIOT_ID ?? DEFAULT_INPUT.riotId;
|
||||
const hashIndex = riotId.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === riotId.length - 1) {
|
||||
throw new Error(`Invalid Riot ID: ${riotId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
projectId: process.env.DAKAO_SEED_PROJECT_ID ?? DEFAULT_INPUT.projectId,
|
||||
matchId: process.env.DAKAO_SEED_MATCH_ID ?? DEFAULT_INPUT.matchId,
|
||||
senderId: process.env.DAKAO_SEED_SENDER_ID ?? DEFAULT_INPUT.senderId,
|
||||
nickname: process.env.DAKAO_SEED_NICKNAME ?? DEFAULT_INPUT.nickname,
|
||||
gameName: normalizeRiotIdPart(riotId.slice(0, hashIndex)),
|
||||
tagLine: normalizeRiotIdPart(riotId.slice(hashIndex + 1)),
|
||||
positions: parsePositionList(
|
||||
process.env.DAKAO_SEED_POSITIONS ?? DEFAULT_INPUT.positions,
|
||||
).positions,
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureCommunityDakaoProjectId(params: {
|
||||
connectionService: ConnectionService;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
projectId: mongoose.Types.ObjectId;
|
||||
}): Promise<mongoose.Types.ObjectId> {
|
||||
const MatchModel = await params.connectionService.getModel('match');
|
||||
const CommunityModel = await params.connectionService.getModel('community');
|
||||
const match = await MatchModel.findById(params.matchId).exec();
|
||||
if (!match) {
|
||||
throw new Error(`Match not found: ${params.matchId.toString()}`);
|
||||
}
|
||||
|
||||
const community = await CommunityModel.findById(match.communityId).exec();
|
||||
if (!community) {
|
||||
throw new Error(`Community not found: ${match.communityId.toString()}`);
|
||||
}
|
||||
|
||||
if (community.dakaoProjectId?.equals(params.projectId)) {
|
||||
return community._id;
|
||||
}
|
||||
if (community.dakaoProjectId) {
|
||||
throw new Error(
|
||||
`Community already has a different dakaoProjectId: ${community.dakaoProjectId.toString()}`,
|
||||
);
|
||||
}
|
||||
|
||||
const conflictingCommunity = await CommunityModel.findOne({
|
||||
_id: { $ne: community._id },
|
||||
dakaoProjectId: params.projectId,
|
||||
}).exec();
|
||||
if (conflictingCommunity) {
|
||||
throw new Error(
|
||||
`dakaoProjectId already belongs to another community: ${conflictingCommunity._id.toString()}`,
|
||||
);
|
||||
}
|
||||
|
||||
community.dakaoProjectId = params.projectId;
|
||||
await community.save();
|
||||
return community._id;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await loadMachineEnvFile();
|
||||
|
||||
const input = readInput();
|
||||
if (!mongoose.isValidObjectId(input.projectId)) {
|
||||
throw new Error(`Invalid projectId: ${input.projectId}`);
|
||||
}
|
||||
if (!mongoose.isValidObjectId(input.matchId)) {
|
||||
throw new Error(`Invalid matchId: ${input.matchId}`);
|
||||
}
|
||||
|
||||
const app = await NestFactory.createApplicationContext(
|
||||
SeedDakaoParticipantModule,
|
||||
{ logger: ['error', 'warn', 'log'] },
|
||||
);
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const dakaoUserService = app.get(DakaoUserService);
|
||||
const matchService = app.get(MatchService);
|
||||
const MatchModel = await connectionService.getModel('match');
|
||||
|
||||
const matchId = new mongoose.Types.ObjectId(input.matchId);
|
||||
const projectId = new mongoose.Types.ObjectId(input.projectId);
|
||||
const communityId = await ensureCommunityDakaoProjectId({
|
||||
connectionService,
|
||||
matchId,
|
||||
projectId,
|
||||
});
|
||||
|
||||
const resolved = await dakaoUserService.resolveRiotAccount({
|
||||
communityId,
|
||||
kakaoTalkId: input.senderId,
|
||||
kakaoTalkNickname: input.nickname,
|
||||
gameName: input.gameName,
|
||||
tagLine: input.tagLine,
|
||||
});
|
||||
|
||||
const existing = await MatchModel.findOne({
|
||||
_id: matchId,
|
||||
'participants.userId': resolved.user._id,
|
||||
}).exec();
|
||||
if (existing) {
|
||||
console.log('[seed:dakao-participant] Participant already exists.');
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
communityId: communityId.toString(),
|
||||
matchId: matchId.toString(),
|
||||
userId: resolved.user._id.toString(),
|
||||
puuid: resolved.riotAccount.puuid,
|
||||
riotId: `${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const preferredPositions = input.positions.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
|
||||
const match = await matchService.join({
|
||||
matchId,
|
||||
userId: resolved.user._id,
|
||||
riotPuuid: resolved.riotAccount.puuid,
|
||||
preferredPositions,
|
||||
});
|
||||
|
||||
console.log('[seed:dakao-participant] Participant added.');
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
communityId: communityId.toString(),
|
||||
matchId: match._id.toString(),
|
||||
userId: resolved.user._id.toString(),
|
||||
kakaoTalkId: input.senderId,
|
||||
kakaoTalkNickname: input.nickname,
|
||||
puuid: resolved.riotAccount.puuid,
|
||||
riotId: `${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
|
||||
preferredPositions,
|
||||
participantCount: match.participants.length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
console.error('\n[seed:dakao-participant] Failed.\n');
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,406 @@
|
||||
/**
|
||||
* Add or update one lolympus user manually from Kakao + Riot identity.
|
||||
*
|
||||
* This is for the last few users that need manual handling.
|
||||
*
|
||||
* Install:
|
||||
* npm install mongodb
|
||||
*
|
||||
* Dry-run with Riot API enrichment:
|
||||
* MONGODB_URI="mongodb://..." \
|
||||
* RIOT_API_KEY="RGAPI-..." \
|
||||
* KAKAO_TALK_ID="7448687768283723562" \
|
||||
* KAKAO_TALK_NICKNAME="탑은죄악이다/95/남/G" \
|
||||
* RIOT_ID="탑은죄악이다#망나니" \
|
||||
* PREFERRED_POSITIONS="TOP,JGL" \
|
||||
* node add-manual-dakao-riot-user.js
|
||||
*
|
||||
* Write:
|
||||
* DRY_RUN=false MONGODB_URI="..." RIOT_API_KEY="..." ... node add-manual-dakao-riot-user.js
|
||||
*
|
||||
* Fallback without Riot API:
|
||||
* PUUID="..." RIOT_ID="..." node add-manual-dakao-riot-user.js
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
const { MongoClient, ObjectId } = require("mongodb");
|
||||
|
||||
const CONFIG = {
|
||||
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
||||
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
|
||||
COMMUNITY_ID: new ObjectId(
|
||||
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
||||
),
|
||||
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
|
||||
RIOT_REGION: process.env.RIOT_REGION ?? "asia",
|
||||
RIOT_PLATFORM: process.env.RIOT_PLATFORM ?? "kr",
|
||||
MASTERY_COUNT: Number(process.env.MASTERY_COUNT ?? 10),
|
||||
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
|
||||
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
|
||||
DRY_RUN: process.env.DRY_RUN !== "false",
|
||||
FAIL_ON_CONFLICT: process.env.FAIL_ON_CONFLICT !== "false",
|
||||
};
|
||||
|
||||
const INPUT = {
|
||||
kakaoTalkId: process.env.KAKAO_TALK_ID ?? "",
|
||||
kakaoTalkNickname: process.env.KAKAO_TALK_NICKNAME ?? "",
|
||||
riotId: process.env.RIOT_ID ?? "",
|
||||
puuid: process.env.PUUID ?? "",
|
||||
preferredPositions: process.env.PREFERRED_POSITIONS ?? "",
|
||||
role: process.env.ROLE ?? "member",
|
||||
isActivated: process.env.IS_ACTIVATED !== "false",
|
||||
};
|
||||
|
||||
function normalizeString(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function splitRiotId(riotId) {
|
||||
const value = normalizeString(riotId);
|
||||
const hashIndex = value.lastIndexOf("#");
|
||||
if (hashIndex <= 0 || hashIndex === value.length - 1) {
|
||||
throw new Error(`Invalid RIOT_ID. Expected "gameName#tagLine": ${riotId}`);
|
||||
}
|
||||
return {
|
||||
gameName: value.slice(0, hashIndex).trim(),
|
||||
tagLine: value.slice(hashIndex + 1).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePositions(value) {
|
||||
const allowed = new Set(["TOP", "JGL", "MID", "ADC", "SUP"]);
|
||||
return normalizeString(value)
|
||||
.split(",")
|
||||
.map((position) => normalizeString(position).toUpperCase())
|
||||
.filter((position) => allowed.has(position))
|
||||
.map((position, index) => ({ position, priority: index + 1 }));
|
||||
}
|
||||
|
||||
function removeUndefined(value) {
|
||||
if (Array.isArray(value)) return value.map(removeUndefined);
|
||||
if (
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
!(value instanceof Date) &&
|
||||
!(value instanceof ObjectId)
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([, entryValue]) => entryValue !== undefined)
|
||||
.map(([key, entryValue]) => [key, removeUndefined(entryValue)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function maskConfig() {
|
||||
return {
|
||||
...CONFIG,
|
||||
MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"),
|
||||
RIOT_API_KEY: CONFIG.RIOT_API_KEY ? "***" : "",
|
||||
};
|
||||
}
|
||||
|
||||
function requireInput() {
|
||||
const missing = [];
|
||||
if (!normalizeString(INPUT.kakaoTalkId)) missing.push("KAKAO_TALK_ID");
|
||||
if (!normalizeString(INPUT.kakaoTalkNickname)) {
|
||||
missing.push("KAKAO_TALK_NICKNAME");
|
||||
}
|
||||
if (!normalizeString(INPUT.riotId)) missing.push("RIOT_ID");
|
||||
if (!CONFIG.RIOT_API_KEY && !normalizeString(INPUT.puuid)) {
|
||||
missing.push("RIOT_API_KEY or PUUID");
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing required env: ${missing.join(", ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRiotJson({ host, path, query }) {
|
||||
if (!CONFIG.RIOT_API_KEY) return null;
|
||||
|
||||
const url = new URL(`https://${host}${path}`);
|
||||
for (const [key, value] of Object.entries(query ?? {})) {
|
||||
if (value !== undefined && value !== null) {
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
const response = await fetch(url, {
|
||||
headers: { "X-Riot-Token": CONFIG.RIOT_API_KEY },
|
||||
});
|
||||
|
||||
if (response.status === 429) {
|
||||
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
|
||||
await sleep(Math.max(1, retryAfterSeconds) * 1000);
|
||||
continue;
|
||||
}
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => "");
|
||||
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAccountByRiotId({ gameName, tagLine }) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_REGION}.api.riotgames.com`,
|
||||
path: `/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchSummonerByPuuid(puuid) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
|
||||
path: `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchLeagueEntriesByPuuid(puuid) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
|
||||
path: `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchChampionMasteriesByPuuid(puuid) {
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
|
||||
path: `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
|
||||
query: { count: CONFIG.MASTERY_COUNT },
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchRecentMatchIdsByPuuid(puuid) {
|
||||
if (!CONFIG.FETCH_RECENT_MATCH_IDS) return [];
|
||||
return fetchRiotJson({
|
||||
host: `${CONFIG.RIOT_REGION}.api.riotgames.com`,
|
||||
path: `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`,
|
||||
query: { start: 0, count: CONFIG.RECENT_MATCH_COUNT },
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchRiotData({ riotId }) {
|
||||
const fallback = splitRiotId(riotId);
|
||||
const account =
|
||||
(await fetchAccountByRiotId(fallback)) ?? {
|
||||
...fallback,
|
||||
puuid: normalizeString(INPUT.puuid),
|
||||
};
|
||||
if (!account?.puuid) {
|
||||
throw new Error(`Riot account not found and PUUID was not provided: ${riotId}`);
|
||||
}
|
||||
|
||||
const [summoner, leagueEntries, championMasteries, matchIds] =
|
||||
await Promise.all([
|
||||
fetchSummonerByPuuid(account.puuid).catch(() => null),
|
||||
fetchLeagueEntriesByPuuid(account.puuid).catch(() => []),
|
||||
fetchChampionMasteriesByPuuid(account.puuid).catch(() => []),
|
||||
fetchRecentMatchIdsByPuuid(account.puuid).catch(() => []),
|
||||
]);
|
||||
|
||||
return {
|
||||
account: {
|
||||
puuid: account.puuid,
|
||||
gameName: normalizeString(account.gameName) || fallback.gameName,
|
||||
tagLine: normalizeString(account.tagLine) || fallback.tagLine,
|
||||
},
|
||||
summoner,
|
||||
leagueEntries: Array.isArray(leagueEntries) ? leagueEntries : [],
|
||||
championMasteries: Array.isArray(championMasteries)
|
||||
? championMasteries
|
||||
: [],
|
||||
matchIds: Array.isArray(matchIds) ? matchIds : [],
|
||||
};
|
||||
}
|
||||
|
||||
function toTierInfo(entry, fetchedAt) {
|
||||
return {
|
||||
leagueId: entry.leagueId,
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
puuid: entry.puuid,
|
||||
leaguePoints: entry.leaguePoints ?? 0,
|
||||
wins: entry.wins ?? 0,
|
||||
losses: entry.losses ?? 0,
|
||||
veteran: entry.veteran,
|
||||
inactive: entry.inactive,
|
||||
freshBlood: entry.freshBlood,
|
||||
hotStreak: entry.hotStreak,
|
||||
miniSeries: entry.miniSeries,
|
||||
fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toTierHistory(entry, recordedAt) {
|
||||
return {
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints ?? 0,
|
||||
wins: entry.wins ?? 0,
|
||||
losses: entry.losses ?? 0,
|
||||
recordedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toChampionMastery(entry) {
|
||||
return {
|
||||
puuid: entry.puuid,
|
||||
championId: entry.championId,
|
||||
championLevel: entry.championLevel,
|
||||
championPoints: entry.championPoints,
|
||||
lastPlayTime: entry.lastPlayTime,
|
||||
championPointsSinceLastLevel: entry.championPointsSinceLastLevel,
|
||||
championPointsUntilNextLevel: entry.championPointsUntilNextLevel,
|
||||
markRequiredForNextLevel: entry.markRequiredForNextLevel,
|
||||
tokensEarned: entry.tokensEarned,
|
||||
championSeasonMilestone: entry.championSeasonMilestone,
|
||||
milestoneGrades: entry.milestoneGrades,
|
||||
nextSeasonMilestone: entry.nextSeasonMilestone,
|
||||
};
|
||||
}
|
||||
|
||||
function buildRiotAccount(riotData, now) {
|
||||
return removeUndefined({
|
||||
puuid: riotData.account.puuid,
|
||||
gameName: riotData.account.gameName,
|
||||
tagLine: riotData.account.tagLine,
|
||||
profileIconId: riotData.summoner?.profileIconId ?? 0,
|
||||
revisionDate: riotData.summoner?.revisionDate ?? 0,
|
||||
summonerLevel: riotData.summoner?.summonerLevel ?? 0,
|
||||
isPrimary: true,
|
||||
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
|
||||
tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)),
|
||||
matchIds: riotData.matchIds,
|
||||
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
|
||||
championMasteries: riotData.championMasteries
|
||||
.slice(0, CONFIG.MASTERY_COUNT)
|
||||
.map(toChampionMastery),
|
||||
championMasteriesFetchedAt:
|
||||
riotData.championMasteries.length > 0 ? now : undefined,
|
||||
championRecords: {},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
function mergeRiotAccount(existingAccounts, nextAccount) {
|
||||
const merged = (existingAccounts ?? [])
|
||||
.filter(
|
||||
(account) =>
|
||||
account.puuid !== nextAccount.puuid &&
|
||||
!(
|
||||
normalizeString(account.gameName).toLowerCase() ===
|
||||
normalizeString(nextAccount.gameName).toLowerCase() &&
|
||||
normalizeString(account.tagLine).toLowerCase() ===
|
||||
normalizeString(nextAccount.tagLine).toLowerCase()
|
||||
),
|
||||
)
|
||||
.map((account) => ({ ...account, isPrimary: false }));
|
||||
return [nextAccount, ...merged];
|
||||
}
|
||||
|
||||
async function buildPlan(User) {
|
||||
const now = new Date();
|
||||
const riotData = await fetchRiotData({ riotId: INPUT.riotId });
|
||||
const account = buildRiotAccount(riotData, now);
|
||||
|
||||
const conflict = await User.findOne({
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
kakaoTalkId: { $ne: INPUT.kakaoTalkId },
|
||||
"riotAccounts.puuid": account.puuid,
|
||||
});
|
||||
if (conflict && CONFIG.FAIL_ON_CONFLICT) {
|
||||
throw new Error(
|
||||
`Riot puuid conflict. existingUserId=${conflict._id.toString()} existingKakaoTalkId=${conflict.kakaoTalkId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const filter = {
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
kakaoTalkId: INPUT.kakaoTalkId,
|
||||
};
|
||||
const existing = await User.findOne(filter);
|
||||
const doc = removeUndefined({
|
||||
_id: existing?._id ?? new ObjectId(),
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
role: INPUT.role,
|
||||
kakaoTalkId: INPUT.kakaoTalkId,
|
||||
kakaoTalkNickname: INPUT.kakaoTalkNickname,
|
||||
riotAccounts: mergeRiotAccount(existing?.riotAccounts, account),
|
||||
preferredPositions: normalizePositions(INPUT.preferredPositions),
|
||||
isActivated: INPUT.isActivated,
|
||||
createdAt: existing?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
return {
|
||||
mode: existing ? "update" : "insert",
|
||||
filter,
|
||||
doc,
|
||||
conflict: conflict
|
||||
? {
|
||||
existingUserId: conflict._id,
|
||||
existingKakaoTalkId: conflict.kakaoTalkId,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function applyPlan(User, plan) {
|
||||
if (CONFIG.DRY_RUN) return { dryRun: true, plan };
|
||||
|
||||
if (plan.mode === "update") {
|
||||
const { _id, createdAt, ...setDoc } = plan.doc;
|
||||
await User.updateOne({ _id: plan.doc._id }, { $set: setDoc });
|
||||
return { updated: 1, inserted: 0, userId: plan.doc._id };
|
||||
}
|
||||
|
||||
await User.insertOne(plan.doc);
|
||||
return { updated: 0, inserted: 1, userId: plan.doc._id };
|
||||
}
|
||||
|
||||
async function run() {
|
||||
requireInput();
|
||||
const client = new MongoClient(CONFIG.MONGODB_URI);
|
||||
await client.connect();
|
||||
|
||||
try {
|
||||
const db = client.db(CONFIG.LOLYMPUS_DB_NAME);
|
||||
const User = db.collection("user");
|
||||
const plan = await buildPlan(User);
|
||||
const result = await applyPlan(User, plan);
|
||||
|
||||
return {
|
||||
config: maskConfig(),
|
||||
input: {
|
||||
...INPUT,
|
||||
puuid: INPUT.puuid ? "***provided***" : "",
|
||||
},
|
||||
result,
|
||||
};
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
run()
|
||||
.then((result) => {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
/**
|
||||
* Apply already-saved Dakao user bootstrap data into lolympus-test.user.
|
||||
*
|
||||
* This script does NOT call Riot API.
|
||||
*
|
||||
* It reads saved documents from one of:
|
||||
* 1. lolympus-test.DakaoUserBootstrapRun
|
||||
* 2. lolympus-test.DakaoUserBootstrapCandidate
|
||||
*
|
||||
* It only applies users that already have a valid Riot identity:
|
||||
* - dryRunUsers[].doc.riotAccounts[0].puuid, or
|
||||
* - candidate.riotApiResult.puuid, or
|
||||
* - candidate.matchedRiotAccount.puuid
|
||||
*
|
||||
* Install:
|
||||
* npm install mongodb
|
||||
*
|
||||
* Dry-run latest saved run:
|
||||
* MONGODB_URI="mongodb://..." node apply-saved-dakao-riot-users.js
|
||||
*
|
||||
* Dry-run specific saved run:
|
||||
* MONGODB_URI="mongodb://..." SOURCE=run RUN_ID="..." node apply-saved-dakao-riot-users.js
|
||||
*
|
||||
* Dry-run from candidate collection:
|
||||
* MONGODB_URI="mongodb://..." SOURCE=candidate node apply-saved-dakao-riot-users.js
|
||||
*
|
||||
* Write:
|
||||
* DRY_RUN=false MONGODB_URI="mongodb://..." node apply-saved-dakao-riot-users.js
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
const { MongoClient, ObjectId } = require("mongodb");
|
||||
|
||||
const CONFIG = {
|
||||
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
||||
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
|
||||
COMMUNITY_ID: new ObjectId(
|
||||
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
||||
),
|
||||
RUNS_COLLECTION_NAME:
|
||||
process.env.RUNS_COLLECTION_NAME ?? "DakaoUserBootstrapRun",
|
||||
CANDIDATES_COLLECTION_NAME:
|
||||
process.env.CANDIDATES_COLLECTION_NAME ?? "DakaoUserBootstrapCandidate",
|
||||
SOURCE: process.env.SOURCE ?? "run", // run | candidate
|
||||
RUN_ID: process.env.RUN_ID ?? "",
|
||||
DRY_RUN: process.env.DRY_RUN !== "false",
|
||||
FORCE_REAPPLY_RUN: process.env.FORCE_REAPPLY_RUN === "true",
|
||||
};
|
||||
|
||||
function normalizeString(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function toObjectId(value, fieldName) {
|
||||
if (value instanceof ObjectId) return value;
|
||||
if (typeof value === "string" && ObjectId.isValid(value)) {
|
||||
return new ObjectId(value);
|
||||
}
|
||||
throw new Error(`Invalid ObjectId for ${fieldName}: ${value}`);
|
||||
}
|
||||
|
||||
function removeUndefined(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(removeUndefined);
|
||||
}
|
||||
if (
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
!(value instanceof Date) &&
|
||||
!(value instanceof ObjectId)
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([, entryValue]) => entryValue !== undefined)
|
||||
.map(([key, entryValue]) => [key, removeUndefined(entryValue)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function maskConfig() {
|
||||
return {
|
||||
...CONFIG,
|
||||
MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"),
|
||||
};
|
||||
}
|
||||
|
||||
function hasValidRiotAccount(account) {
|
||||
return Boolean(
|
||||
normalizeString(account?.puuid) &&
|
||||
normalizeString(account?.gameName) &&
|
||||
normalizeString(account?.tagLine),
|
||||
);
|
||||
}
|
||||
|
||||
function ensureRiotAccountShape(account, now) {
|
||||
return removeUndefined({
|
||||
puuid: normalizeString(account.puuid),
|
||||
gameName: normalizeString(account.gameName),
|
||||
tagLine: normalizeString(account.tagLine),
|
||||
profileIconId: account.profileIconId ?? 0,
|
||||
revisionDate: account.revisionDate ?? 0,
|
||||
summonerLevel: account.summonerLevel ?? 0,
|
||||
isPrimary: true,
|
||||
tiers: Array.isArray(account.tiers) ? account.tiers : [],
|
||||
tierHistory: Array.isArray(account.tierHistory) ? account.tierHistory : [],
|
||||
matchIds: Array.isArray(account.matchIds) ? account.matchIds : [],
|
||||
matchIdsFetchedAt: account.matchIdsFetchedAt,
|
||||
lastRefreshRequestedAt: account.lastRefreshRequestedAt,
|
||||
recentStatsSummary: account.recentStatsSummary,
|
||||
recentStatsFetchedAt: account.recentStatsFetchedAt,
|
||||
championMasteries: Array.isArray(account.championMasteries)
|
||||
? account.championMasteries
|
||||
: [],
|
||||
championMasteriesFetchedAt: account.championMasteriesFetchedAt,
|
||||
championRecords: account.championRecords ?? {},
|
||||
championRecordsFetchedAt: account.championRecordsFetchedAt,
|
||||
createdAt: account.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
function mergeRiotAccount(existingAccounts, nextAccount) {
|
||||
const merged = (existingAccounts ?? [])
|
||||
.filter(
|
||||
(account) =>
|
||||
account.puuid !== nextAccount.puuid &&
|
||||
!(
|
||||
normalizeString(account.gameName).toLowerCase() ===
|
||||
normalizeString(nextAccount.gameName).toLowerCase() &&
|
||||
normalizeString(account.tagLine).toLowerCase() ===
|
||||
normalizeString(nextAccount.tagLine).toLowerCase()
|
||||
),
|
||||
)
|
||||
.map((account) => ({ ...account, isPrimary: false }));
|
||||
|
||||
return [nextAccount, ...merged];
|
||||
}
|
||||
|
||||
function buildPlanFromDryRunUser(planned, now) {
|
||||
const doc = planned.doc ?? {};
|
||||
const primary = doc.riotAccounts?.[0];
|
||||
if (!hasValidRiotAccount(primary)) return null;
|
||||
|
||||
return {
|
||||
source: "dryRunUsers",
|
||||
originalMode: planned.mode,
|
||||
filter: {
|
||||
communityId: toObjectId(
|
||||
planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID,
|
||||
"planned.communityId",
|
||||
),
|
||||
kakaoTalkId: normalizeString(planned.filter?.kakaoTalkId ?? doc.kakaoTalkId),
|
||||
},
|
||||
doc: removeUndefined({
|
||||
_id:
|
||||
doc._id && ObjectId.isValid(String(doc._id))
|
||||
? toObjectId(doc._id, "planned.doc._id")
|
||||
: new ObjectId(),
|
||||
communityId: toObjectId(doc.communityId ?? CONFIG.COMMUNITY_ID, "doc.communityId"),
|
||||
role: doc.role ?? "member",
|
||||
kakaoTalkId: normalizeString(doc.kakaoTalkId),
|
||||
kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname),
|
||||
riotAccounts: [ensureRiotAccountShape(primary, now)],
|
||||
preferredPositions: Array.isArray(doc.preferredPositions)
|
||||
? doc.preferredPositions
|
||||
: [],
|
||||
isActivated: doc.isActivated ?? true,
|
||||
createdAt: doc.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildPlanFromCandidate(candidate, now) {
|
||||
const api = candidate.riotApiResult;
|
||||
const matched = candidate.matchedRiotAccount;
|
||||
const accountSource = hasValidRiotAccount(api) ? api : matched;
|
||||
if (!hasValidRiotAccount(accountSource)) return null;
|
||||
|
||||
const account = ensureRiotAccountShape(
|
||||
{
|
||||
...matched,
|
||||
...api,
|
||||
profileIconId: candidate.riotEnrichment?.summoner?.profileIconId ?? 0,
|
||||
revisionDate: candidate.riotEnrichment?.summoner?.revisionDate ?? 0,
|
||||
summonerLevel: candidate.riotEnrichment?.summoner?.summonerLevel ?? 0,
|
||||
tiers: (candidate.riotEnrichment?.leagueEntries ?? []).map((entry) => ({
|
||||
leagueId: entry.leagueId,
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
puuid: entry.puuid,
|
||||
leaguePoints: entry.leaguePoints ?? 0,
|
||||
wins: entry.wins ?? 0,
|
||||
losses: entry.losses ?? 0,
|
||||
veteran: entry.veteran,
|
||||
inactive: entry.inactive,
|
||||
freshBlood: entry.freshBlood,
|
||||
hotStreak: entry.hotStreak,
|
||||
miniSeries: entry.miniSeries,
|
||||
fetchedAt: now,
|
||||
})),
|
||||
tierHistory: (candidate.riotEnrichment?.leagueEntries ?? []).map(
|
||||
(entry) => ({
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints ?? 0,
|
||||
wins: entry.wins ?? 0,
|
||||
losses: entry.losses ?? 0,
|
||||
recordedAt: now,
|
||||
}),
|
||||
),
|
||||
matchIds: candidate.riotEnrichment?.matchIds ?? [],
|
||||
matchIdsFetchedAt:
|
||||
candidate.riotEnrichment?.matchIds?.length > 0 ? now : undefined,
|
||||
championMasteries: candidate.riotEnrichment?.championMasteries ?? [],
|
||||
championMasteriesFetchedAt:
|
||||
candidate.riotEnrichment?.championMasteries?.length > 0
|
||||
? now
|
||||
: undefined,
|
||||
},
|
||||
now,
|
||||
);
|
||||
|
||||
return {
|
||||
source: "candidate",
|
||||
filter: {
|
||||
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
|
||||
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
|
||||
},
|
||||
doc: removeUndefined({
|
||||
_id: new ObjectId(),
|
||||
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
|
||||
role: candidate.role ?? "member",
|
||||
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
|
||||
kakaoTalkNickname: normalizeString(
|
||||
candidate.targetKakaoTalkNickname || candidate.kakaoTalkNickname,
|
||||
),
|
||||
riotAccounts: [account],
|
||||
preferredPositions: Array.isArray(candidate.preferredPositions)
|
||||
? candidate.preferredPositions
|
||||
: [],
|
||||
isActivated: candidate.isActivated ?? true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function dedupePlans(plans) {
|
||||
const byKakaoTalkId = new Map();
|
||||
for (const plan of plans) {
|
||||
if (!plan?.filter?.kakaoTalkId) continue;
|
||||
byKakaoTalkId.set(plan.filter.kakaoTalkId, plan);
|
||||
}
|
||||
return [...byKakaoTalkId.values()];
|
||||
}
|
||||
|
||||
async function loadLatestRun(Runs) {
|
||||
if (CONFIG.RUN_ID) {
|
||||
return Runs.findOne({ _id: toObjectId(CONFIG.RUN_ID, "RUN_ID") });
|
||||
}
|
||||
return Runs.findOne(
|
||||
{ communityId: CONFIG.COMMUNITY_ID },
|
||||
{ sort: { createdAt: -1 } },
|
||||
);
|
||||
}
|
||||
|
||||
async function loadPlansFromRun(lolympusDb, now) {
|
||||
const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME);
|
||||
const run = await loadLatestRun(Runs);
|
||||
if (!run) {
|
||||
throw new Error("No saved DakaoUserBootstrapRun found.");
|
||||
}
|
||||
if (run.state === "applied" && !CONFIG.FORCE_REAPPLY_RUN) {
|
||||
throw new Error(
|
||||
`Run ${run._id.toString()} is already applied. Set FORCE_REAPPLY_RUN=true to re-apply.`,
|
||||
);
|
||||
}
|
||||
|
||||
const fromDryRunUsers = (run.upsertResult?.dryRunUsers ?? [])
|
||||
.map((planned) => buildPlanFromDryRunUser(planned, now))
|
||||
.filter(Boolean);
|
||||
const fromCandidates = (run.candidates ?? [])
|
||||
.map((candidate) => buildPlanFromCandidate(candidate, now))
|
||||
.filter(Boolean);
|
||||
const plans = dedupePlans(
|
||||
fromDryRunUsers.length > 0 ? fromDryRunUsers : fromCandidates,
|
||||
);
|
||||
|
||||
return { sourceRun: run, plans };
|
||||
}
|
||||
|
||||
async function loadPlansFromCandidates(lolympusDb, now) {
|
||||
const Candidate = lolympusDb.collection(CONFIG.CANDIDATES_COLLECTION_NAME);
|
||||
const candidates = await Candidate.find({
|
||||
communityId: CONFIG.COMMUNITY_ID,
|
||||
}).toArray();
|
||||
const plans = dedupePlans(
|
||||
candidates.map((candidate) => buildPlanFromCandidate(candidate, now)).filter(Boolean),
|
||||
);
|
||||
return { sourceRun: null, plans };
|
||||
}
|
||||
|
||||
async function applyPlans(lolympusDb, plans) {
|
||||
const User = lolympusDb.collection("user");
|
||||
const result = {
|
||||
inserted: 0,
|
||||
updated: 0,
|
||||
skippedConflict: [],
|
||||
errors: [],
|
||||
dryRunUsers: [],
|
||||
};
|
||||
|
||||
for (const plan of plans) {
|
||||
try {
|
||||
const primary = plan.doc.riotAccounts?.[0];
|
||||
const conflict = await User.findOne({
|
||||
communityId: plan.doc.communityId,
|
||||
kakaoTalkId: { $ne: plan.doc.kakaoTalkId },
|
||||
"riotAccounts.puuid": primary.puuid,
|
||||
});
|
||||
if (conflict) {
|
||||
result.skippedConflict.push({
|
||||
kakaoTalkId: plan.doc.kakaoTalkId,
|
||||
riotId: `${primary.gameName}#${primary.tagLine}`,
|
||||
puuid: primary.puuid,
|
||||
existingUserId: conflict._id,
|
||||
existingKakaoTalkId: conflict.kakaoTalkId,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = await User.findOne(plan.filter);
|
||||
const nextDoc = removeUndefined({
|
||||
...plan.doc,
|
||||
_id: existing?._id ?? plan.doc._id,
|
||||
createdAt: existing?.createdAt ?? plan.doc.createdAt,
|
||||
riotAccounts: mergeRiotAccount(existing?.riotAccounts, primary),
|
||||
});
|
||||
|
||||
if (CONFIG.DRY_RUN) {
|
||||
result.dryRunUsers.push({
|
||||
mode: existing ? "update" : "insert",
|
||||
filter: plan.filter,
|
||||
doc: nextDoc,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
const { _id, createdAt, ...setDoc } = nextDoc;
|
||||
await User.updateOne({ _id: existing._id }, { $set: setDoc });
|
||||
result.updated += 1;
|
||||
} else {
|
||||
await User.insertOne(nextDoc);
|
||||
result.inserted += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
result.errors.push({
|
||||
kakaoTalkId: plan?.doc?.kakaoTalkId,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function markRunApplied(lolympusDb, sourceRun, applyResult) {
|
||||
if (!sourceRun || CONFIG.DRY_RUN) return;
|
||||
const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME);
|
||||
await Runs.updateOne(
|
||||
{ _id: sourceRun._id },
|
||||
{
|
||||
$set: {
|
||||
state: applyResult.errors.length > 0 ? "apply-partial" : "applied",
|
||||
appliedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
applyResult,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const client = new MongoClient(CONFIG.MONGODB_URI);
|
||||
await client.connect();
|
||||
|
||||
try {
|
||||
const lolympusDb = client.db(CONFIG.LOLYMPUS_DB_NAME);
|
||||
const now = new Date();
|
||||
const { sourceRun, plans } =
|
||||
CONFIG.SOURCE === "candidate"
|
||||
? await loadPlansFromCandidates(lolympusDb, now)
|
||||
: await loadPlansFromRun(lolympusDb, now);
|
||||
const applyResult = await applyPlans(lolympusDb, plans);
|
||||
await markRunApplied(lolympusDb, sourceRun, applyResult);
|
||||
|
||||
return {
|
||||
config: maskConfig(),
|
||||
source: CONFIG.SOURCE,
|
||||
sourceRunId: sourceRun?._id ?? null,
|
||||
planCount: plans.length,
|
||||
applyResult,
|
||||
};
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
run()
|
||||
.then((result) => {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user