Merge pull request 'feat(dakao): transfer existing users to new KakaoTalk IDs' (#12) from release/88 into main
Reviewed-on: #12
This commit was merged in pull request #12.
This commit is contained in:
commit
384d460ad6
10 files changed
+432
-1
No files matched your search
@@ -0,0 +1,122 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RiotAccountService } from '../riot/riot-account.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { DakaoUserService } from './dakao-user.service';
|
||||
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const params = {
|
||||
communityId,
|
||||
kakaoTalkId: 'new-id',
|
||||
previousNickname: '예전 닉',
|
||||
};
|
||||
|
||||
function setup() {
|
||||
const user = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
kakaoTalkId: 'old-id',
|
||||
kakaoTalkNickname: '예전 닉',
|
||||
riotAccounts: [{ puuid: 'puuid', gameName: '소환사', tagLine: 'KR1' }],
|
||||
role: 'member',
|
||||
};
|
||||
const find = jest.fn().mockReturnValue({
|
||||
limit: jest
|
||||
.fn()
|
||||
.mockReturnValue({ exec: jest.fn().mockResolvedValue([user]) }),
|
||||
});
|
||||
const findOne = jest
|
||||
.fn()
|
||||
.mockReturnValue({ exec: jest.fn().mockResolvedValue(null) });
|
||||
const update = jest
|
||||
.fn()
|
||||
.mockImplementation(async () => ({ ...user, kakaoTalkId: 'new-id' }));
|
||||
const findOneAndUpdate = jest.fn().mockReturnValue({ exec: update });
|
||||
const service = new DakaoUserService(
|
||||
{
|
||||
getModel: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ find, findOne, findOneAndUpdate }),
|
||||
} as unknown as ConnectionService,
|
||||
{} as RiotAccountService,
|
||||
{} as RiotAccountEnrichmentService,
|
||||
);
|
||||
return { service, user, find, findOne, findOneAndUpdate, update };
|
||||
}
|
||||
|
||||
describe('DakaoUserService.transferKakaoTalkId', () => {
|
||||
it('selects registered users by exact nickname in the current community and changes only the ID', async () => {
|
||||
const { service, user, find, findOneAndUpdate } = setup();
|
||||
expect(await service.transferKakaoTalkId(params)).toBe('transferred');
|
||||
expect(find).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
kakaoTalkNickname: '예전 닉',
|
||||
'riotAccounts.0': { $exists: true },
|
||||
});
|
||||
expect(findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{
|
||||
_id: user._id,
|
||||
communityId,
|
||||
kakaoTalkId: 'old-id',
|
||||
kakaoTalkNickname: '예전 닉',
|
||||
'riotAccounts.0': { $exists: true },
|
||||
},
|
||||
{ $set: { kakaoTalkId: 'new-id' } },
|
||||
{ returnDocument: 'after' },
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not-found', 0],
|
||||
['ambiguous', 2],
|
||||
] as const)('returns %s without mutation', async (status, count) => {
|
||||
const { service, user, find, findOneAndUpdate } = setup();
|
||||
find.mockReturnValue({
|
||||
limit: () => ({
|
||||
exec: async () => Array.from({ length: count }, () => user),
|
||||
}),
|
||||
});
|
||||
expect(await service.transferKakaoTalkId(params)).toBe(status);
|
||||
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not mutate an already linked user', async () => {
|
||||
const { service, user, findOneAndUpdate } = setup();
|
||||
user.kakaoTalkId = 'new-id';
|
||||
expect(await service.transferKakaoTalkId(params)).toBe('already-linked');
|
||||
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses an ID occupied by another user', async () => {
|
||||
const { service, findOne, findOneAndUpdate } = setup();
|
||||
findOne.mockReturnValue({
|
||||
exec: async () => ({ _id: new mongoose.Types.ObjectId() }),
|
||||
});
|
||||
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
|
||||
expect(findOne).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
kakaoTalkId: 'new-id',
|
||||
});
|
||||
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a concurrent change instead of overwriting it', async () => {
|
||||
const { service, update } = setup();
|
||||
update.mockResolvedValue(null);
|
||||
expect(await service.transferKakaoTalkId(params)).toBe('changed');
|
||||
});
|
||||
|
||||
it('handles a concurrent ID collision', async () => {
|
||||
const { service, update } = setup();
|
||||
update.mockRejectedValue({ code: 11000 });
|
||||
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
|
||||
});
|
||||
|
||||
it('propagates unexpected database failures for retry', async () => {
|
||||
const { service, update } = setup();
|
||||
update.mockRejectedValue(new Error('database unavailable'));
|
||||
await expect(service.transferKakaoTalkId(params)).rejects.toThrow(
|
||||
'database unavailable',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -60,6 +60,14 @@ interface ResolvedRiotIdentity {
|
||||
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
|
||||
|
||||
export type KakaoDataTransferResult =
|
||||
| 'transferred'
|
||||
| 'already-linked'
|
||||
| 'not-found'
|
||||
| 'ambiguous'
|
||||
| 'id-conflict'
|
||||
| 'changed';
|
||||
|
||||
@Injectable()
|
||||
export class DakaoUserService {
|
||||
private readonly logger = new Logger(DakaoUserService.name);
|
||||
@@ -127,6 +135,44 @@ export class DakaoUserService {
|
||||
}).exec();
|
||||
}
|
||||
|
||||
public async transferKakaoTalkId(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
kakaoTalkId: string;
|
||||
previousNickname: string;
|
||||
}): Promise<KakaoDataTransferResult> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const targetFilter = {
|
||||
communityId: params.communityId,
|
||||
kakaoTalkNickname: params.previousNickname,
|
||||
'riotAccounts.0': { $exists: true },
|
||||
};
|
||||
const candidates = await UserModel.find(targetFilter).limit(2).exec();
|
||||
if (candidates.length === 0) return 'not-found';
|
||||
if (candidates.length > 1) return 'ambiguous';
|
||||
|
||||
const user = candidates[0];
|
||||
if (user.kakaoTalkId === params.kakaoTalkId) return 'already-linked';
|
||||
const occupied = await this.findUserByKakaoTalkId(params);
|
||||
if (occupied) return 'id-conflict';
|
||||
|
||||
try {
|
||||
// Compare the previous ID so concurrent transfers cannot overwrite one another.
|
||||
const updated = await UserModel.findOneAndUpdate(
|
||||
{
|
||||
...targetFilter,
|
||||
_id: user._id,
|
||||
kakaoTalkId: user.kakaoTalkId ?? null,
|
||||
},
|
||||
{ $set: { kakaoTalkId: params.kakaoTalkId } },
|
||||
{ returnDocument: 'after' },
|
||||
).exec();
|
||||
return updated ? 'transferred' : 'changed';
|
||||
} catch (error) {
|
||||
if ((error as { code?: number })?.code === 11000) return 'id-conflict';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async resolveRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { DakaoUserService } from './dakao-user.service';
|
||||
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
|
||||
import { DakaoUrlShortenerService } from './dakao-url-shortener.service';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { DataTransferHandler } from './handlers/data-transfer.handler';
|
||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
@@ -35,6 +36,7 @@ import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.h
|
||||
DakaoUserService,
|
||||
DakaoUrlShortenerService,
|
||||
AccountRegisterHandler,
|
||||
DataTransferHandler,
|
||||
MatchListHandler,
|
||||
MatchJoinHandler,
|
||||
MatchCancelHandler,
|
||||
|
||||
@@ -16,6 +16,7 @@ function makeSubscriber(): DakaoSubscriber {
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -39,6 +40,48 @@ const event = {
|
||||
} satisfies DakaoInboundEvent;
|
||||
|
||||
describe('DakaoSubscriber', () => {
|
||||
it('routes data transfer with the current sender ID and publishes its reply', async () => {
|
||||
const subscriber = makeSubscriber();
|
||||
const segments = [{ kind: 'text', text: ' 데이터 이관 완료' }];
|
||||
const handle = jest.fn().mockResolvedValue(segments);
|
||||
const sendMessage = jest.fn();
|
||||
const markProcessed = jest.fn();
|
||||
Object.assign(subscriber, {
|
||||
dakaoUserService: {
|
||||
resolveCommunityIdByDakaoProjectId: async () => event.projectId,
|
||||
},
|
||||
dataTransferHandler: { handle },
|
||||
publisher: { sendMessage },
|
||||
inbox: { claim: async () => ({ status: 'claimed' }), markProcessed },
|
||||
});
|
||||
await (
|
||||
subscriber as unknown as {
|
||||
handleEvent: (input: DakaoInboundEvent) => Promise<void>;
|
||||
}
|
||||
).handleEvent({
|
||||
...event,
|
||||
origin: {
|
||||
...event.origin,
|
||||
chatLog: {
|
||||
...event.origin.chatLog,
|
||||
message: '!내전 데이터이관 예전 닉',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(handle).toHaveBeenCalledWith({
|
||||
communityId: event.projectId,
|
||||
senderUserId: '12345',
|
||||
senderNickname: '프리리',
|
||||
previousNickname: '예전 닉',
|
||||
});
|
||||
expect(sendMessage).toHaveBeenCalledWith({
|
||||
chatroomId: 'chatroom-1',
|
||||
segments,
|
||||
correlationId: 'log-1',
|
||||
});
|
||||
expect(markProcessed).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders usage help with star emoticon command lines', () => {
|
||||
const subscriber = makeSubscriber() as unknown as {
|
||||
parseErrorReply: (
|
||||
@@ -74,8 +117,10 @@ describe('DakaoSubscriber', () => {
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{
|
||||
kind: 'text',
|
||||
text: ' !내전 대표계정변경 소환사이름#태그',
|
||||
text: ' !내전 대표계정변경 소환사이름#태그\u3000\n',
|
||||
},
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{ kind: 'text', text: ' !내전 데이터이관 예전닉네임' },
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||
import { DataTransferHandler } from './handlers/data-transfer.handler';
|
||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
@@ -27,6 +28,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
'!내전 계정등록 소환사이름#태그',
|
||||
'!내전 선호포지션등록 포지션1,포지션2',
|
||||
'!내전 대표계정변경 소환사이름#태그',
|
||||
'!내전 데이터이관 예전닉네임',
|
||||
];
|
||||
|
||||
constructor(
|
||||
@@ -42,6 +44,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
private readonly matchCancelHandler: MatchCancelHandler,
|
||||
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
||||
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
||||
private readonly dataTransferHandler: DataTransferHandler,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
@@ -119,6 +122,14 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
const command = parseCommand(event.origin.chatLog.message);
|
||||
|
||||
switch (command.kind) {
|
||||
case 'data-transfer':
|
||||
segments = await this.dataTransferHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname,
|
||||
previousNickname: command.previousNickname,
|
||||
});
|
||||
break;
|
||||
case 'match-list':
|
||||
segments = await this.matchListHandler.handle({
|
||||
communityId,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
DakaoUserService,
|
||||
KakaoDataTransferResult,
|
||||
} from '../dakao-user.service';
|
||||
import { DataTransferHandler } from './data-transfer.handler';
|
||||
|
||||
const params = {
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
senderUserId: 'new-id',
|
||||
senderNickname: '현재 닉',
|
||||
previousNickname: '예전 닉',
|
||||
};
|
||||
|
||||
describe('DataTransferHandler', () => {
|
||||
it.each<[KakaoDataTransferResult, string]>([
|
||||
['transferred', '데이터 이관 완료'],
|
||||
['already-linked', '이미 현재 카카오톡 계정에 연결'],
|
||||
['not-found', '찾을 수 없습니다'],
|
||||
['ambiguous', '여러 명'],
|
||||
['id-conflict', '이미 다른 사용자'],
|
||||
['changed', '변경되었습니다'],
|
||||
])('replies to the sender for %s', async (result, message) => {
|
||||
const transferKakaoTalkId = jest.fn().mockResolvedValue(result);
|
||||
const handler = new DataTransferHandler({
|
||||
transferKakaoTalkId,
|
||||
} as unknown as DakaoUserService);
|
||||
expect(await handler.handle(params)).toEqual([
|
||||
{ kind: 'mention', userId: 'new-id', displayText: '현재 닉' },
|
||||
{ kind: 'text', text: expect.stringContaining(message) },
|
||||
]);
|
||||
expect(transferKakaoTalkId).toHaveBeenCalledWith({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: 'new-id',
|
||||
previousNickname: '예전 닉',
|
||||
});
|
||||
});
|
||||
|
||||
it('propagates unexpected failures', async () => {
|
||||
const handler = new DataTransferHandler({
|
||||
transferKakaoTalkId: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new Error('database unavailable')),
|
||||
} as unknown as DakaoUserService);
|
||||
await expect(handler.handle(params)).rejects.toThrow(
|
||||
'database unavailable',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
DakaoUserService,
|
||||
KakaoDataTransferResult,
|
||||
} from '../dakao-user.service';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
|
||||
const RESULT_MESSAGES: Record<KakaoDataTransferResult, string> = {
|
||||
transferred:
|
||||
'데이터 이관 완료. 기존 라이엇 계정과 내전 기록이 현재 카카오톡 계정에 연결되었습니다.',
|
||||
'already-linked': '이미 현재 카카오톡 계정에 연결된 사용자입니다.',
|
||||
'not-found':
|
||||
'해당 예전 닉네임으로 라이엇 계정이 등록된 사용자를 찾을 수 없습니다.',
|
||||
ambiguous:
|
||||
'같은 예전 닉네임으로 등록된 사용자가 여러 명입니다. 운영자에게 문의해주세요.',
|
||||
'id-conflict':
|
||||
'현재 카카오톡 계정에 이미 다른 사용자가 등록되어 있습니다. 운영자에게 문의해주세요.',
|
||||
changed: '이관 중 사용자 정보가 변경되었습니다. 다시 시도해주세요.',
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class DataTransferHandler {
|
||||
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
||||
|
||||
public async handle(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
senderUserId: string;
|
||||
senderNickname: string;
|
||||
previousNickname: string;
|
||||
}): Promise<DakaoSegment[]> {
|
||||
const result = await this.dakaoUserService.transferKakaoTalkId({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
previousNickname: params.previousNickname,
|
||||
});
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{ kind: 'text', text: ` ${RESULT_MESSAGES[result]}` },
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,19 @@
|
||||
import { CommandParseError, parseCommand } from './command.parser';
|
||||
|
||||
describe('parseCommand', () => {
|
||||
it('parses data transfer with the complete previous nickname', () => {
|
||||
expect(parseCommand(' !내전 데이터이관 예전 닉.* ')).toEqual({
|
||||
kind: 'data-transfer',
|
||||
previousNickname: '예전 닉.*',
|
||||
});
|
||||
});
|
||||
|
||||
it('requires a previous nickname for data transfer', () => {
|
||||
expect(() => parseCommand('!내전 데이터이관 ')).toThrow(
|
||||
new CommandParseError('usage'),
|
||||
);
|
||||
});
|
||||
|
||||
it('parses match-list command (목록)', () => {
|
||||
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import { normalizeRiotIdPart } from '../riot-id.util';
|
||||
|
||||
export type DakaoCommand =
|
||||
| { kind: 'match-list' }
|
||||
| { kind: 'data-transfer'; previousNickname: string }
|
||||
| {
|
||||
kind: 'account-register';
|
||||
gameName: string;
|
||||
@@ -75,6 +76,9 @@ export function parseCommand(rawMessage: string): DakaoCommand {
|
||||
return parseCancelArgs(args);
|
||||
case '계정등록':
|
||||
return parseAccountRegisterArgs(args);
|
||||
case '데이터이관':
|
||||
if (!args) throw new CommandParseError('usage');
|
||||
return { kind: 'data-transfer', previousNickname: args };
|
||||
case '대표계정변경':
|
||||
return parsePrimaryAccountChangeArgs(args);
|
||||
case '선호포지션등록':
|
||||
|
||||
Reference in new issue
Block a user