feat(api): handle Dakao registrations
This commit is contained in:
1 parent
404f7713b9
commit
3b2ac601a0
8 files changed
+2383
No files matched your search
@@ -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,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,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;
|
||||
});
|
||||
Reference in new issue
Block a user