This commit is contained in:
dahyeon committed 2026-05-02 05:34:47 -07:00
1 parent a5654c02a2
commit 3fa8fffcec
4 files changed
+159 -58

No files matched your search

@@ -3,7 +3,7 @@ import { ConnectionService } from '../global/database/connection.service';
import { RiotAccount, UserDocument } from '../global/database/schema'; import { RiotAccount, UserDocument } from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotAccountService } from '../riot/riot-account.service'; import { RiotAccountService } from '../riot/riot-account.service';
import { DakaoUserError, DakaoUserService } from './dakao-user.service'; import { DakaoUserService } from './dakao-user.service';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
@@ -15,14 +15,24 @@ function makeQuery<T>(value: T) {
function makeService(params: { function makeService(params: {
user: Partial<UserDocument>; user: Partial<UserDocument>;
community?: Record<string, unknown> | null;
riotAccountService?: Partial<RiotAccountService>; riotAccountService?: Partial<RiotAccountService>;
enrichmentService?: Partial<RiotAccountEnrichmentService>; enrichmentService?: Partial<RiotAccountEnrichmentService>;
}) { }) {
const findOneAndUpdate = jest const findOneAndUpdate = jest
.fn() .fn()
.mockReturnValue(makeQuery(params.user as UserDocument)); .mockReturnValue(makeQuery(params.user as UserDocument));
const findById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(makeQuery(params.community ?? {})),
}),
});
const connectionService = { const connectionService = {
getModel: jest.fn().mockResolvedValue({ findOneAndUpdate }), 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; } as unknown as ConnectionService;
const riotAccountService = { const riotAccountService = {
getByRiotId: jest.fn(), getByRiotId: jest.fn(),
@@ -41,13 +51,14 @@ function makeService(params: {
), ),
connectionService, connectionService,
findOneAndUpdate, findOneAndUpdate,
findById,
riotAccountService, riotAccountService,
enrichmentService, enrichmentService,
}; };
} }
describe('DakaoUserService', () => { describe('DakaoUserService', () => {
it('rejects account registration when the user already has a Riot account', async () => { it('registers an additional Riot account when the user already has one', async () => {
const save = jest.fn().mockResolvedValue(undefined); const save = jest.fn().mockResolvedValue(undefined);
const existingAccount = { const existingAccount = {
puuid: 'puuid-1', puuid: 'puuid-1',
@@ -66,25 +77,95 @@ describe('DakaoUserService', () => {
riotAccounts: [existingAccount], riotAccounts: [existingAccount],
save, save,
} as Partial<UserDocument>, } as Partial<UserDocument>,
riotAccountService: {
getByRiotId: jest.fn().mockResolvedValue({
puuid: 'puuid-2',
gameName: '새소환사',
tagLine: 'KR2',
}),
},
enrichmentService: {
enrichRiotAccount: jest.fn().mockResolvedValue({ account: null }),
},
}); });
await expect( const result = await service.registerRiotAccount({
service.registerPrimaryRiotAccount({ communityId: objectId('111111111111111111111111'),
communityId: objectId('111111111111111111111111'), kakaoTalkId: 'kakao-user-1',
kakaoTalkId: 'kakao-user-1', kakaoTalkNickname: '프리리',
kakaoTalkNickname: '프리리', gameName: '새소환사',
gameName: '새소환사', tagLine: 'KR2',
tagLine: 'KR2', });
}),
).rejects.toMatchObject({
code: 'riot_account_already_registered',
detail: '기존소환사#KR1',
} satisfies Partial<DakaoUserError>);
expect(connectionService.getModel).toHaveBeenCalledTimes(1); 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('user');
expect(riotAccountService.getByRiotId).not.toHaveBeenCalled(); 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(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
expect(save).not.toHaveBeenCalled(); expect(save).toHaveBeenCalled();
}); });
}); });
@@ -129,6 +129,8 @@ export class DakaoUserService {
const routing = await this.resolveRiotRouting(context.communityId); const routing = await this.resolveRiotRouting(context.communityId);
const { requestedGameName, requestedTagLine, dto } = const { requestedGameName, requestedTagLine, dto } =
await this.lookupRiotIdentity(context, routing); await this.lookupRiotIdentity(context, routing);
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
const existing = user.riotAccounts.find( const existing = user.riotAccounts.find(
(a) => (a) =>
@@ -142,8 +144,6 @@ export class DakaoUserService {
} }
if (existing) { if (existing) {
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
if (existing.puuid !== dto.puuid) { if (existing.puuid !== dto.puuid) {
this.logger.warn( this.logger.warn(
`Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`, `Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`,
@@ -172,37 +172,21 @@ export class DakaoUserService {
return { user, riotAccount: existing }; return { user, riotAccount: existing };
} }
return this.attachRiotAccount({ const existingByPuuid = user.riotAccounts.find(
user, (account) => account.puuid === dto.puuid,
puuid: dto.puuid,
gameName: dto.gameName ?? requestedGameName,
tagLine: dto.tagLine ?? requestedTagLine,
platform: routing.platform,
region: routing.region,
});
}
public async registerPrimaryRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
const user = await this.upsertUser(context);
const existingPrimary = user.riotAccounts.find(
(account) => account.isPrimary,
); );
const existingAccount = existingPrimary ?? user.riotAccounts[0]; if (existingByPuuid) {
if (existingAccount) { if (
throw new DakaoUserError( existingByPuuid.gameName !== nextGameName ||
'riot_account_already_registered', existingByPuuid.tagLine !== nextTagLine
`${existingAccount.gameName}#${existingAccount.tagLine}`, ) {
); existingByPuuid.gameName = nextGameName;
existingByPuuid.tagLine = nextTagLine;
await user.save();
}
return { user, riotAccount: existingByPuuid };
} }
const routing = await this.resolveRiotRouting(context.communityId);
const { requestedGameName, requestedTagLine, dto } =
await this.lookupRiotIdentity(context, routing);
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
return this.attachRiotAccount({ return this.attachRiotAccount({
user, user,
puuid: dto.puuid, puuid: dto.puuid,
@@ -213,6 +197,18 @@ export class DakaoUserService {
}); });
} }
public async registerRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
return this.resolveRiotAccount(context);
}
public async registerPrimaryRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
return this.registerRiotAccount(context);
}
private async lookupRiotIdentity( private async lookupRiotIdentity(
context: ResolveContext, context: ResolveContext,
routing: RiotRouting, routing: RiotRouting,
@@ -6,7 +6,7 @@ const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeHandler(dakaoUserService?: Partial<DakaoUserService>) { function makeHandler(dakaoUserService?: Partial<DakaoUserService>) {
return new AccountRegisterHandler({ return new AccountRegisterHandler({
registerPrimaryRiotAccount: jest.fn(), registerRiotAccount: jest.fn(),
...dakaoUserService, ...dakaoUserService,
} as unknown as DakaoUserService); } as unknown as DakaoUserService);
} }
@@ -20,15 +20,39 @@ const baseParams = {
}; };
describe('AccountRegisterHandler', () => { describe('AccountRegisterHandler', () => {
it('translates already-registered Riot account errors', async () => { it('registers a Riot account through DakaoUserService', async () => {
const registerRiotAccount = jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { gameName: '프리리', tagLine: 'KR1' },
});
const handler = makeHandler({ const handler = makeHandler({
registerPrimaryRiotAccount: jest 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() .fn()
.mockRejectedValue( .mockRejectedValue(
new DakaoUserError( new DakaoUserError('riot_account_conflict', '기존소환사#KR1'),
'riot_account_already_registered',
'기존소환사#KR1',
),
), ),
}); });
@@ -38,7 +62,7 @@ describe('AccountRegisterHandler', () => {
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
expect.objectContaining({ expect.objectContaining({
kind: 'text', kind: 'text',
text: expect.stringContaining('이미 등록된 라이엇 계정'), text: expect.stringContaining('이미 다른 사용자가 등록한 라이엇 계정'),
}), }),
]); ]);
expect(segments[1]).toMatchObject({ expect(segments[1]).toMatchObject({
@@ -19,7 +19,7 @@ export class AccountRegisterHandler {
params: AccountRegisterHandlerParams, params: AccountRegisterHandlerParams,
): Promise<DakaoSegment[]> { ): Promise<DakaoSegment[]> {
try { try {
const resolved = await this.dakaoUserService.registerPrimaryRiotAccount({ const resolved = await this.dakaoUserService.registerRiotAccount({
communityId: params.communityId, communityId: params.communityId,
kakaoTalkId: params.senderUserId, kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname, kakaoTalkNickname: params.senderNickname,
@@ -37,7 +37,7 @@ export class AccountRegisterHandler {
kind: 'text', kind: 'text',
text: text:
` 계정 등록 완료` + ` 계정 등록 완료` +
`\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, `\n등록 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
}, },
]; ];
} catch (err) { } catch (err) {