This commit is contained in:
dahyeon committed 2026-04-28 08:38:47 -07:00
1 parent 4475a2d86b
commit a076bca587
10 files changed
+2726 -62

No files matched your search

@@ -0,0 +1,90 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { RiotAccount, UserDocument } from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotAccountService } from '../riot/riot-account.service';
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeQuery<T>(value: T) {
return {
exec: jest.fn().mockResolvedValue(value),
};
}
function makeService(params: {
user: Partial<UserDocument>;
riotAccountService?: Partial<RiotAccountService>;
enrichmentService?: Partial<RiotAccountEnrichmentService>;
}) {
const findOneAndUpdate = jest
.fn()
.mockReturnValue(makeQuery(params.user as UserDocument));
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findOneAndUpdate }),
} as unknown as ConnectionService;
const riotAccountService = {
getByRiotId: jest.fn(),
...params.riotAccountService,
} as unknown as RiotAccountService;
const enrichmentService = {
enrichRiotAccount: jest.fn(),
...params.enrichmentService,
} as unknown as RiotAccountEnrichmentService;
return {
service: new DakaoUserService(
connectionService,
riotAccountService,
enrichmentService,
),
connectionService,
findOneAndUpdate,
riotAccountService,
enrichmentService,
};
}
describe('DakaoUserService', () => {
it('rejects account registration when the user already has a Riot account', async () => {
const save = jest.fn().mockResolvedValue(undefined);
const existingAccount = {
puuid: 'puuid-1',
gameName: '기존소환사',
tagLine: 'KR1',
isPrimary: true,
} as RiotAccount;
const {
service,
connectionService,
riotAccountService,
enrichmentService,
} = makeService({
user: {
_id: objectId('222222222222222222222222'),
riotAccounts: [existingAccount],
save,
} as Partial<UserDocument>,
});
await expect(
service.registerPrimaryRiotAccount({
communityId: objectId('111111111111111111111111'),
kakaoTalkId: 'kakao-user-1',
kakaoTalkNickname: '프리리',
gameName: '새소환사',
tagLine: 'KR2',
}),
).rejects.toMatchObject({
code: 'riot_account_already_registered',
detail: '기존소환사#KR1',
} satisfies Partial<DakaoUserError>);
expect(connectionService.getModel).toHaveBeenCalledTimes(1);
expect(connectionService.getModel).toHaveBeenCalledWith('user');
expect(riotAccountService.getByRiotId).not.toHaveBeenCalled();
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
expect(save).not.toHaveBeenCalled();
});
});
@@ -19,6 +19,7 @@ export class DakaoUserError extends Error {
| '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,
@@ -174,70 +175,28 @@ export class DakaoUserService {
context: ResolveContext,
): Promise<ResolveResult> {
const user = await this.upsertUser(context);
const existingPrimary = user.riotAccounts.find(
(account) => account.isPrimary,
);
const existingAccount = existingPrimary ?? user.riotAccounts[0];
if (existingAccount) {
throw new DakaoUserError(
'riot_account_already_registered',
`${existingAccount.gameName}#${existingAccount.tagLine}`,
);
}
const routing = await this.resolveRiotRouting(context.communityId);
const { requestedGameName, requestedTagLine, dto } =
await this.lookupRiotIdentity(context, routing);
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
let targetIndex = user.riotAccounts.findIndex(
(account) => account.puuid === dto.puuid,
);
if (targetIndex === -1) {
targetIndex = user.riotAccounts.findIndex(
(account) =>
account.gameName.toLowerCase() === requestedGameName.toLowerCase() &&
account.tagLine.toLowerCase() === requestedTagLine.toLowerCase(),
);
}
if (targetIndex >= 0) {
const target = user.riotAccounts[targetIndex];
const puuidChanged = target.puuid !== dto.puuid;
target.puuid = dto.puuid;
target.gameName = nextGameName;
target.tagLine = nextTagLine;
if (puuidChanged) this.clearRiotCache(target);
user.riotAccounts.forEach((account, index) => {
account.isPrimary = index === targetIndex;
});
await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine);
return this.enrichAttachedAccount({
user,
riotAccount: target,
platform: routing.platform,
region: routing.region,
});
}
user.riotAccounts.forEach((account) => {
account.isPrimary = false;
});
user.riotAccounts.push({
return this.attachRiotAccount({
user,
puuid: dto.puuid,
gameName: nextGameName,
tagLine: nextTagLine,
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
isPrimary: true,
tiers: [],
tierHistory: [],
matchIds: [],
championMasteries: [],
championRecords: {},
} as unknown as RiotAccount);
await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine);
const attached = user.riotAccounts.find(
(account) => account.puuid === dto.puuid,
);
if (!attached) {
throw new DakaoUserError('riot_account_lookup_failed', 'attach failed');
}
return this.enrichAttachedAccount({
user,
riotAccount: attached,
platform: routing.platform,
region: routing.region,
});
@@ -0,0 +1,49 @@
import mongoose from 'mongoose';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
import { AccountRegisterHandler } from './account-register.handler';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeHandler(dakaoUserService?: Partial<DakaoUserService>) {
return new AccountRegisterHandler({
registerPrimaryRiotAccount: jest.fn(),
...dakaoUserService,
} as unknown as DakaoUserService);
}
const baseParams = {
communityId: objectId('111111111111111111111111'),
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
};
describe('AccountRegisterHandler', () => {
it('translates already-registered Riot account errors', async () => {
const handler = makeHandler({
registerPrimaryRiotAccount: jest
.fn()
.mockRejectedValue(
new DakaoUserError(
'riot_account_already_registered',
'기존소환사#KR1',
),
),
});
const segments = await handler.handle(baseParams);
expect(segments).toEqual([
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
expect.objectContaining({
kind: 'text',
text: expect.stringContaining('이미 등록된 라이엇 계정'),
}),
]);
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('기존소환사#KR1'),
});
});
});
@@ -70,6 +70,8 @@ export class AccountRegisterHandler {
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':
@@ -108,6 +108,8 @@ export class MatchJoinHandler {
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':
+16 -7
View File
@@ -550,7 +550,9 @@ export default function UserHistoryPage() {
profile?.tiers[0];
const internalPages = internalHistoryQuery.data?.pages ?? [];
const internalFirstPage = internalPages[0];
const summary = isInternalQueue ? internalFirstPage?.summary : summaryQuery.data;
const summary = isInternalQueue
? internalFirstPage?.summary
: summaryQuery.data;
const matches = isInternalQueue
? internalPages.flatMap((page) => page.matches)
: (recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? []);
@@ -643,7 +645,11 @@ export default function UserHistoryPage() {
queryKey: ["user-recent-matches", DEFAULT_COMMUNITY_ID, userId ?? null],
}),
queryClient.invalidateQueries({
queryKey: ["user-internal-history", DEFAULT_COMMUNITY_ID, userId ?? null],
queryKey: [
"user-internal-history",
DEFAULT_COMMUNITY_ID,
userId ?? null,
],
}),
]);
}
@@ -652,11 +658,13 @@ export default function UserHistoryPage() {
if (!userId) return;
if (isInternalQueue) {
setRefreshResult(null);
setRefreshNotice(
"내전 기록은 토너먼트 결과 수집 데이터를 다시 조회합니다. Riot API 갱신 큐는 사용하지 않습니다.",
);
setRefreshNotice("과거의 토너먼트 결과 수집 데이터를 다시 조회합니다.");
void queryClient.invalidateQueries({
queryKey: ["user-internal-history", DEFAULT_COMMUNITY_ID, userId ?? null],
queryKey: [
"user-internal-history",
DEFAULT_COMMUNITY_ID,
userId ?? null,
],
});
return;
}
@@ -757,7 +765,8 @@ export default function UserHistoryPage() {
{isInternalQueue ? (
<>
{/* 내전 탭은 토너먼트 결과 DB를 조회합니다. */}
Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다.
{/* Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다. */}
내전 기록이 확인되지 않을 경우 버튼을 눌러 갱신 (테스트)
</>
) : (
<>