.
This commit is contained in:
1 parent
5af2c80cd1
commit
f7ee34da4f
78 files changed
+9016
-150
No files matched your search
@@ -33,6 +33,7 @@
|
||||
"@nestjs/websockets": "^11.1.19",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"jose": "^6.2.2",
|
||||
"mongoose": "^9.4.1",
|
||||
"nats": "^2.29.3",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AllowPublicAccess } from './modules/auth/allow-public-access.decorator';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
@@ -6,6 +7,7 @@ export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
@AllowPublicAccess()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AppService } from './app.service';
|
||||
import { AuctionModule } from './modules/auction/auction.module';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
import { CommunityModule } from './modules/community/community.module';
|
||||
import { DakaoModule } from './modules/dakao/dakao.module';
|
||||
import { GlobalModule } from './modules/global/global.module';
|
||||
import { MatchModule } from './modules/match/match.module';
|
||||
import { RiotModule } from './modules/riot/riot.module';
|
||||
@@ -23,6 +24,7 @@ import { UserModule } from './modules/user/user.module';
|
||||
MatchModule,
|
||||
AuctionModule,
|
||||
UserModule,
|
||||
DakaoModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
||||
@@ -15,7 +15,7 @@ async function bootstrap() {
|
||||
app.enableCors({
|
||||
origin: isDev ? true : webOrigins,
|
||||
credentials: true,
|
||||
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
});
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
|
||||
@@ -9,17 +9,21 @@ import {
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
|
||||
|
||||
@Controller('communities/:communityId/matches/:matchId/auction')
|
||||
@UseInterceptors(UserResolverInterceptor)
|
||||
export class AuctionController {
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
|
||||
@@ -47,6 +51,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Get()
|
||||
@AllowPublicAccess()
|
||||
public async getAuction(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
@@ -55,6 +60,7 @@ export class AuctionController {
|
||||
|
||||
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
|
||||
@Post('open-bidding')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async openBidding(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@@ -63,6 +69,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('bids')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async placeBid(
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@@ -78,6 +85,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('sold')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async markSold(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@@ -90,6 +98,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('next')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async next(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
|
||||
@@ -9,8 +9,19 @@ import {
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import mongoose from 'mongoose';
|
||||
import type { JWTPayload } from 'jose';
|
||||
import { Namespace, Socket } from 'socket.io';
|
||||
import type { AuctionDocument, Position, TeamSide } from '../global/database/schema';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { IdentityService } from '../auth/identity.service';
|
||||
import { JwtService } from '../auth/jwt.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
AuctionDocument,
|
||||
IdentityDocument,
|
||||
Position,
|
||||
TeamSide,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
interface JoinAuctionPayload {
|
||||
@@ -32,7 +43,7 @@ interface SoldPayload {
|
||||
cors: {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
},
|
||||
})
|
||||
export class AuctionGateway
|
||||
@@ -44,10 +55,26 @@ export class AuctionGateway
|
||||
private readonly logger = new Logger(AuctionGateway.name);
|
||||
private readonly roomTimers = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
constructor(
|
||||
private readonly auctionService: AuctionService,
|
||||
private readonly authService: AuthService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly identityService: IdentityService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
) {}
|
||||
|
||||
public handleConnection(socket: Socket) {
|
||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||
public async handleConnection(socket: Socket) {
|
||||
try {
|
||||
await this.authenticateSocket(socket);
|
||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Auction client authentication failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
socket.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
public handleDisconnect(socket: Socket) {
|
||||
@@ -70,6 +97,7 @@ export class AuctionGateway
|
||||
socket.data.matchId = payload.matchId;
|
||||
|
||||
try {
|
||||
await this.resolveSocketUserForMatch(socket, payload.matchId);
|
||||
const auction = await this.auctionService.getByMatchId(
|
||||
new mongoose.Types.ObjectId(payload.matchId),
|
||||
);
|
||||
@@ -165,7 +193,9 @@ export class AuctionGateway
|
||||
}
|
||||
|
||||
private getSocketMatchId(socket: Socket): string | undefined {
|
||||
return typeof socket.data.matchId === 'string' ? socket.data.matchId : undefined;
|
||||
return typeof socket.data.matchId === 'string'
|
||||
? socket.data.matchId
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private resolveBidderUserId(
|
||||
@@ -173,7 +203,9 @@ export class AuctionGateway
|
||||
payloadBidderUserId?: string,
|
||||
): mongoose.Types.ObjectId | undefined {
|
||||
const candidate =
|
||||
payloadBidderUserId ?? this.readHandshakeUserId(socket);
|
||||
payloadBidderUserId ??
|
||||
(socket.data.user as UserDocument | undefined)?._id.toString() ??
|
||||
this.readHandshakeUserId(socket);
|
||||
if (!candidate || !mongoose.isValidObjectId(candidate)) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -188,6 +220,80 @@ export class AuctionGateway
|
||||
return Array.isArray(header) ? header[0] : header;
|
||||
}
|
||||
|
||||
private async authenticateSocket(socket: Socket): Promise<void> {
|
||||
const fallback = await this.authService.resolveDevUserById(
|
||||
this.readHandshakeUserId(socket),
|
||||
);
|
||||
if (fallback) {
|
||||
socket.data.user = fallback.user;
|
||||
socket.data.identity = fallback.identity;
|
||||
return;
|
||||
}
|
||||
|
||||
const token = this.readHandshakeToken(socket);
|
||||
if (!token) {
|
||||
throw new Error('Missing auction socket token.');
|
||||
}
|
||||
|
||||
const { payload } = await this.jwtService.verify(
|
||||
token,
|
||||
'MICROSOFT_ENTRAID',
|
||||
);
|
||||
socket.data.identity = await this.identityService.findOrCreateByOid({
|
||||
entraOid: this.requireStringClaim(payload, 'oid'),
|
||||
tenantId: this.stringClaim(payload.tid),
|
||||
email:
|
||||
this.stringClaim(payload.preferred_username) ??
|
||||
this.stringClaim(payload.email),
|
||||
displayName: this.stringClaim(payload.name),
|
||||
});
|
||||
}
|
||||
|
||||
private readHandshakeToken(socket: Socket): string | undefined {
|
||||
const authToken = socket.handshake.auth.token;
|
||||
if (typeof authToken === 'string' && authToken.trim()) {
|
||||
return authToken.trim().replace(/^Bearer\s+/i, '');
|
||||
}
|
||||
|
||||
const header = socket.handshake.headers.authorization;
|
||||
const authorization = Array.isArray(header) ? header[0] : header;
|
||||
if (authorization?.startsWith('Bearer ')) {
|
||||
return authorization.slice('Bearer '.length).trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async resolveSocketUserForMatch(
|
||||
socket: Socket,
|
||||
matchId: string,
|
||||
): Promise<void> {
|
||||
if (socket.data.user || !socket.data.identity) return;
|
||||
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(matchId).select({
|
||||
communityId: 1,
|
||||
});
|
||||
if (!match) return;
|
||||
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
socket.data.user = await UserModel.findOne({
|
||||
communityId: match.communityId,
|
||||
identityId: (socket.data.identity as IdentityDocument)._id,
|
||||
}).exec();
|
||||
}
|
||||
|
||||
private requireStringClaim(payload: JWTPayload, key: string): string {
|
||||
const value = payload[key];
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
throw new Error(`Token is missing ${key} claim.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private stringClaim(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
private broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
this.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||
this.syncRoomTimer(matchId, auction);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED =
|
||||
'lolympus:allow_public_access';
|
||||
|
||||
export const AllowPublicAccess = () =>
|
||||
SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { JWTHeaderParameters, JWTPayload } from 'jose';
|
||||
import type {
|
||||
IdentityDocument,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import type { IdentityProviderName } from './jwt.service';
|
||||
|
||||
declare module 'express' {
|
||||
interface Request {
|
||||
tokenPayload?: JWTPayload;
|
||||
tokenHeader?: JWTHeaderParameters;
|
||||
identityProvider?: IdentityProviderName;
|
||||
identity?: IdentityDocument;
|
||||
user?: UserDocument;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,18 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { UserDocument } from '../global/database/schema';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
declare module 'express' {
|
||||
interface Request {
|
||||
user?: UserDocument;
|
||||
}
|
||||
}
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class AuthMiddleware implements NestMiddleware {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
public async use(req: Request, _res: Response, next: NextFunction) {
|
||||
const user = await this.authService.resolveUserFromRequest(req);
|
||||
if (user) req.user = user;
|
||||
const fallback = await this.authService.resolveDevFallbackFromRequest(req);
|
||||
if (fallback) {
|
||||
req.user = fallback.user;
|
||||
req.identity = fallback.identity;
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,32 @@
|
||||
import { Global, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { AuthMiddleware } from './auth.middleware';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { AuthService } from './auth.service';
|
||||
import { IdentityResolverGuard } from './identity-resolver.guard';
|
||||
import { IdentityService } from './identity.service';
|
||||
import { JwtAuthGuard } from './jwt.guard';
|
||||
import { JwtService } from './jwt.service';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { UserResolverInterceptor } from './user-resolver.interceptor';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [AuthService, RolesGuard],
|
||||
exports: [AuthService, RolesGuard],
|
||||
providers: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
JwtAuthGuard,
|
||||
IdentityResolverGuard,
|
||||
RolesGuard,
|
||||
UserResolverInterceptor,
|
||||
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
||||
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
|
||||
],
|
||||
exports: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
RolesGuard,
|
||||
UserResolverInterceptor,
|
||||
],
|
||||
})
|
||||
export class AuthModule implements NestModule {
|
||||
public configure(consumer: MiddlewareConsumer) {
|
||||
consumer.apply(AuthMiddleware).forRoutes('*');
|
||||
}
|
||||
}
|
||||
export class AuthModule {}
|
||||
@@ -2,22 +2,61 @@ import { Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { UserDocument } from '../global/database/schema';
|
||||
import {
|
||||
IdentityDocument,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import './auth-request';
|
||||
|
||||
interface DevFallbackResult {
|
||||
user: UserDocument;
|
||||
identity?: IdentityDocument;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly secretService: SecretService,
|
||||
) {}
|
||||
|
||||
// 로그인/세션 구현 전까지는 `X-Auth-User-Id` 헤더로 유저를 식별.
|
||||
// OAuth 도입 시 이 메서드만 교체하면 됨.
|
||||
public async resolveUserFromRequest(
|
||||
public async resolveDevFallbackFromRequest(
|
||||
req: Request,
|
||||
): Promise<UserDocument | null> {
|
||||
): Promise<DevFallbackResult | null> {
|
||||
if (!(await this.isDevHeaderEnabled())) return null;
|
||||
const header = req.headers['x-auth-user-id'];
|
||||
const userId = Array.isArray(header) ? header[0] : header;
|
||||
if (!userId || !mongoose.isValidObjectId(userId)) return null;
|
||||
return this.resolveDevUserById(userId);
|
||||
}
|
||||
|
||||
public async resolveDevUserById(
|
||||
userId: unknown,
|
||||
): Promise<DevFallbackResult | null> {
|
||||
if (!(await this.isDevHeaderEnabled())) return null;
|
||||
if (typeof userId !== 'string' || !mongoose.isValidObjectId(userId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.findById(userId).exec();
|
||||
const user = await UserModel.findById(userId).exec();
|
||||
if (!user) return null;
|
||||
|
||||
const result: DevFallbackResult = { user };
|
||||
if (user.identityId) {
|
||||
const IdentityModel = await this.connectionService.getModel('identity');
|
||||
const identity = await IdentityModel.findById(user.identityId).exec();
|
||||
if (identity) result.identity = identity;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private async isDevHeaderEnabled(): Promise<boolean> {
|
||||
if (process.env.NODE_ENV === 'prod') return false;
|
||||
const value = await this.secretService.get<string>(
|
||||
'AUTH_DEV_HEADER_ENABLED',
|
||||
process.env.AUTH_DEV_HEADER_ENABLED ?? 'false',
|
||||
);
|
||||
return value === 'true';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { IdentityDocument } from '../global/database/schema';
|
||||
import './auth-request';
|
||||
|
||||
export const CurrentIdentity = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): IdentityDocument | undefined => {
|
||||
const req = ctx.switchToHttp().getRequest<Request>();
|
||||
return req.identity;
|
||||
},
|
||||
);
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { UserDocument } from '../global/database/schema';
|
||||
import './auth-request';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): UserDocument | undefined => {
|
||||
const req = ctx.switchToHttp().getRequest<{ user?: UserDocument }>();
|
||||
const req = ctx.switchToHttp().getRequest<Request>();
|
||||
return req.user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { IdentityService } from './identity.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class IdentityResolverGuard implements CanActivate {
|
||||
constructor(private readonly identityService: IdentityService) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
if (request.identity || !request.tokenPayload) return true;
|
||||
|
||||
const entraOid = stringClaim(request.tokenPayload.oid);
|
||||
if (!entraOid) {
|
||||
throw new UnauthorizedException('Token is missing oid claim.');
|
||||
}
|
||||
|
||||
request.identity = await this.identityService.findOrCreateByOid({
|
||||
entraOid,
|
||||
tenantId: stringClaim(request.tokenPayload.tid),
|
||||
email:
|
||||
stringClaim(request.tokenPayload.preferred_username) ??
|
||||
stringClaim(request.tokenPayload.email),
|
||||
displayName: stringClaim(request.tokenPayload.name),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function stringClaim(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Injectable, InternalServerErrorException } from '@nestjs/common';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { IdentityDocument } from '../global/database/schema';
|
||||
|
||||
interface IdentityInput {
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class IdentityService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async findOrCreateByOid(
|
||||
input: IdentityInput,
|
||||
): Promise<IdentityDocument> {
|
||||
const IdentityModel = await this.connectionService.getModel('identity');
|
||||
const identity = await IdentityModel.findOneAndUpdate(
|
||||
{ entraOid: input.entraOid },
|
||||
{
|
||||
$set: {
|
||||
tenantId: input.tenantId,
|
||||
email: input.email,
|
||||
displayName: input.displayName,
|
||||
lastSignInAt: new Date(),
|
||||
},
|
||||
$setOnInsert: { entraOid: input.entraOid },
|
||||
},
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||
).exec();
|
||||
|
||||
if (!identity) {
|
||||
throw new InternalServerErrorException('Failed to resolve identity.');
|
||||
}
|
||||
return identity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { decodeJwt } from 'jose';
|
||||
import type { Request } from 'express';
|
||||
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
|
||||
import { AuthService } from './auth.service';
|
||||
import { IdentityProviderName, JwtService } from './jwt.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(
|
||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
const authz = request.headers?.authorization;
|
||||
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
|
||||
|
||||
if (!authzHeader) {
|
||||
const fallback =
|
||||
await this.authService.resolveDevFallbackFromRequest(request);
|
||||
if (fallback) {
|
||||
request.user = fallback.user;
|
||||
request.identity = fallback.identity;
|
||||
return true;
|
||||
}
|
||||
if (isPublicAccessAllowed) return true;
|
||||
throw new UnauthorizedException(
|
||||
'Missing or invalid Authorization header',
|
||||
);
|
||||
}
|
||||
|
||||
if (!authzHeader.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException(
|
||||
'Missing or invalid Authorization header',
|
||||
);
|
||||
}
|
||||
|
||||
const token = authzHeader.slice('Bearer '.length).trim();
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Empty bearer token');
|
||||
}
|
||||
|
||||
const identityProvider = this.pickIdPFromToken(token);
|
||||
|
||||
try {
|
||||
const verifyResult = await this.jwtService.verify(
|
||||
token,
|
||||
identityProvider,
|
||||
);
|
||||
request.tokenPayload = verifyResult.payload;
|
||||
request.tokenHeader = verifyResult.protectedHeader;
|
||||
request.identityProvider = identityProvider;
|
||||
return true;
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : 'JWT verification failed';
|
||||
throw new UnauthorizedException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private pickIdPFromToken(token: string): IdentityProviderName {
|
||||
try {
|
||||
const { iss } = decodeJwt(token) as { iss?: string };
|
||||
if (!iss) {
|
||||
throw new Error('Token has no issuer (iss) claim');
|
||||
}
|
||||
const lower = iss.toLowerCase();
|
||||
if (lower.includes('login.microsoftonline.com')) {
|
||||
return 'MICROSOFT_ENTRAID';
|
||||
}
|
||||
throw new Error(`Unknown issuer: ${iss}`);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Unable to decode token';
|
||||
throw new UnauthorizedException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
createRemoteJWKSet,
|
||||
jwtVerify,
|
||||
JWTPayload,
|
||||
JWTVerifyGetKey,
|
||||
JWTVerifyResult,
|
||||
} from 'jose';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
|
||||
export type IdentityProviderName = 'MICROSOFT_ENTRAID';
|
||||
|
||||
interface EntraConfig {
|
||||
tenantId: string;
|
||||
audience: string;
|
||||
issuer: string;
|
||||
allowedAlgs: string[];
|
||||
jwks: JWTVerifyGetKey;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtService {
|
||||
private entraConfig?: EntraConfig;
|
||||
private readonly clockTolerance = Number(
|
||||
process.env.JWT_CLOCK_TOLERANCE || 5,
|
||||
);
|
||||
|
||||
constructor(private readonly secretService: SecretService) {}
|
||||
|
||||
public async verify(
|
||||
token: string,
|
||||
identityProvider: IdentityProviderName,
|
||||
): Promise<JWTVerifyResult<JWTPayload>> {
|
||||
if (!token) {
|
||||
throw new Error('Empty token');
|
||||
}
|
||||
|
||||
if (identityProvider !== 'MICROSOFT_ENTRAID') {
|
||||
throw new Error(`Identity provider not configured: ${identityProvider}`);
|
||||
}
|
||||
|
||||
const provider = await this.getEntraConfig();
|
||||
const result = await jwtVerify(token, provider.jwks, {
|
||||
issuer: provider.issuer,
|
||||
audience: provider.audience,
|
||||
algorithms: provider.allowedAlgs,
|
||||
clockTolerance: this.clockTolerance,
|
||||
});
|
||||
|
||||
const { payload, protectedHeader } = result;
|
||||
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
|
||||
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
||||
}
|
||||
if (payload.ver && payload.ver !== '2.0') {
|
||||
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
|
||||
}
|
||||
if (payload.tid && payload.tid !== provider.tenantId) {
|
||||
throw new Error(`Unexpected tenant: ${payload.tid}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async getEntraConfig(): Promise<EntraConfig> {
|
||||
if (this.entraConfig) return this.entraConfig;
|
||||
|
||||
await this.secretService.ready();
|
||||
const [audience, tenantId, allowedAlgsRaw] = await Promise.all([
|
||||
this.secretService.get<string>('JWT_CLAIM_AUDIENCE'),
|
||||
this.secretService.get<string>('MICROSOFT_ENTRAID_TENANT_ID'),
|
||||
this.secretService.get<string>('MICROSOFT_ENTRAID_ALLOWED_ALGS', 'RS256'),
|
||||
]);
|
||||
|
||||
const allowedAlgs = allowedAlgsRaw
|
||||
.split(',')
|
||||
.map((alg) => alg.trim())
|
||||
.filter(Boolean);
|
||||
if (allowedAlgs.length === 0) {
|
||||
allowedAlgs.push('RS256');
|
||||
}
|
||||
|
||||
const issuer = `https://login.microsoftonline.com/${tenantId}/v2.0`;
|
||||
const jwks = createRemoteJWKSet(
|
||||
new URL('https://login.microsoftonline.com/common/discovery/v2.0/keys'),
|
||||
{
|
||||
cooldownDuration: 30_000,
|
||||
timeoutDuration: 10_000,
|
||||
},
|
||||
);
|
||||
|
||||
this.entraConfig = {
|
||||
tenantId,
|
||||
audience,
|
||||
issuer,
|
||||
allowedAlgs,
|
||||
jwks,
|
||||
};
|
||||
return this.entraConfig;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { Reflector } from '@nestjs/core';
|
||||
import type { Request } from 'express';
|
||||
import { CommunityRole, UserDocument } from '../global/database/schema';
|
||||
import { ROLES_KEY } from './roles.decorator';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
@@ -23,6 +24,9 @@ export class RolesGuard implements CanActivate {
|
||||
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const user = req.user as UserDocument | undefined;
|
||||
if (!user && req.identity) {
|
||||
throw new ForbiddenException('No membership in this community.');
|
||||
}
|
||||
if (!user) throw new UnauthorizedException('Authentication required.');
|
||||
if (!requiredRoles.includes(user.role)) {
|
||||
throw new ForbiddenException('Insufficient role.');
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { Observable } from 'rxjs';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class UserResolverInterceptor implements NestInterceptor {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler,
|
||||
): Promise<Observable<unknown>> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const communityId = request.params?.communityId;
|
||||
|
||||
if (
|
||||
!request.user &&
|
||||
request.identity &&
|
||||
typeof communityId === 'string' &&
|
||||
mongoose.isValidObjectId(communityId)
|
||||
) {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findOne({
|
||||
communityId: new mongoose.Types.ObjectId(communityId),
|
||||
identityId: request.identity._id,
|
||||
}).exec();
|
||||
if (user) request.user = user;
|
||||
}
|
||||
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,54 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import '../auth/auth-request';
|
||||
import { CommunityService } from './community.service';
|
||||
import { CreateCommunityDto } from './dto/create-community.dto';
|
||||
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
|
||||
|
||||
@Controller('communities')
|
||||
@UseInterceptors(UserResolverInterceptor)
|
||||
export class CommunityController {
|
||||
constructor(private readonly communityService: CommunityService) {}
|
||||
|
||||
@Post()
|
||||
public async createCommunity(@Body() body: CreateCommunityDto) {
|
||||
return this.communityService.createCommunityWithOwner(body);
|
||||
@AllowPublicAccess()
|
||||
public async createCommunity(
|
||||
@Body() body: CreateCommunityDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
if (!req.identity && !body.owner) {
|
||||
throw new BadRequestException(
|
||||
'owner is required when not authenticated.',
|
||||
);
|
||||
}
|
||||
return this.communityService.createCommunityWithOwner({
|
||||
...body,
|
||||
identityId: req.identity?._id,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':communityId')
|
||||
@AllowPublicAccess()
|
||||
public async getCommunity(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
|
||||
@@ -14,7 +14,8 @@ import {
|
||||
export interface CreateCommunityInput {
|
||||
name: string;
|
||||
description?: string;
|
||||
owner: {
|
||||
identityId?: mongoose.Types.ObjectId;
|
||||
owner?: {
|
||||
kakaoTalkId?: string;
|
||||
kakaoTalkNickname?: string;
|
||||
discordId?: string;
|
||||
@@ -70,11 +71,12 @@ export class CommunityService {
|
||||
{
|
||||
_id: ownerUserId,
|
||||
communityId,
|
||||
identityId: input.identityId,
|
||||
role: 'owner',
|
||||
kakaoTalkId: input.owner.kakaoTalkId,
|
||||
kakaoTalkNickname: input.owner.kakaoTalkNickname,
|
||||
discordId: input.owner.discordId,
|
||||
discordNickname: input.owner.discordNickname,
|
||||
kakaoTalkId: input.owner?.kakaoTalkId,
|
||||
kakaoTalkNickname: input.owner?.kakaoTalkNickname,
|
||||
discordId: input.owner?.discordId,
|
||||
discordNickname: input.owner?.discordNickname,
|
||||
},
|
||||
],
|
||||
{ session },
|
||||
|
||||
@@ -40,7 +40,8 @@ export class CreateCommunityDto {
|
||||
@MaxLength(1024)
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@ValidateNested()
|
||||
@Type(() => CreateCommunityOwnerDto)
|
||||
owner!: CreateCommunityOwnerDto;
|
||||
owner?: CreateCommunityOwnerDto;
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose, { isValidObjectId } from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { 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_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;
|
||||
}
|
||||
|
||||
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 resolveRiotAccount(
|
||||
context: ResolveContext,
|
||||
): Promise<ResolveResult> {
|
||||
const user = await this.upsertUser(context);
|
||||
const routing = await this.resolveRiotRouting(context.communityId);
|
||||
const requestedGameName = normalizeRiotIdPart(context.gameName);
|
||||
const requestedTagLine = normalizeRiotIdPart(context.tagLine);
|
||||
this.logRiotIdNormalization(context, requestedGameName, 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}`,
|
||||
);
|
||||
}
|
||||
|
||||
let dto: { puuid: string; gameName: string | null; tagLine: string | null };
|
||||
try {
|
||||
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 ?? '-'}`,
|
||||
);
|
||||
} 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,
|
||||
);
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
const nextGameName = dto.gameName ?? requestedGameName;
|
||||
const nextTagLine = dto.tagLine ?? requestedTagLine;
|
||||
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 };
|
||||
}
|
||||
|
||||
return this.attachRiotAccount({
|
||||
user,
|
||||
puuid: dto.puuid,
|
||||
gameName: dto.gameName ?? requestedGameName,
|
||||
tagLine: dto.tagLine ?? requestedTagLine,
|
||||
platform: routing.platform,
|
||||
region: routing.region,
|
||||
});
|
||||
}
|
||||
|
||||
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,31 @@
|
||||
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 { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.handler';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, MatchModule],
|
||||
providers: [
|
||||
{
|
||||
provide: DAKAO_OPTIONS,
|
||||
useFactory: createDefaultDakaoOptions,
|
||||
},
|
||||
DakaoPublisher,
|
||||
DakaoSubscriber,
|
||||
DakaoUserService,
|
||||
IdempotencyCache,
|
||||
MatchListHandler,
|
||||
MatchJoinHandler,
|
||||
],
|
||||
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,97 @@
|
||||
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: 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 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,186 @@
|
||||
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, DakaoSegment } from './dakao.types';
|
||||
import { DakaoPublisher } from './dakao.publisher';
|
||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||
import { MatchListHandler } from './handlers/match-list.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 matchListHandler: MatchListHandler,
|
||||
private readonly matchJoinHandler: MatchJoinHandler,
|
||||
) {}
|
||||
|
||||
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[];
|
||||
try {
|
||||
const command = parseCommand(event.origin.chatLog.message);
|
||||
const correlationId = String(event.origin.chatLog.logId ?? '');
|
||||
|
||||
switch (command.kind) {
|
||||
case 'match-list':
|
||||
segments = await this.matchListHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname: event.nickname,
|
||||
});
|
||||
break;
|
||||
case 'match-join':
|
||||
segments = await this.matchJoinHandler.handle({
|
||||
communityId,
|
||||
matchId: command.matchId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname: event.nickname,
|
||||
gameName: command.gameName,
|
||||
tagLine: command.tagLine,
|
||||
positions: command.positions.positions,
|
||||
});
|
||||
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, err),
|
||||
correlationId: String(event.origin.chatLog.logId ?? ''),
|
||||
});
|
||||
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 logId = event.origin.chatLog.logId;
|
||||
if (typeof logId === 'string') return `${event.projectId}:${logId}`;
|
||||
if (logId && typeof logId === 'object') {
|
||||
const { high, low, unsigned } = logId;
|
||||
return `${event.projectId}:${high ?? ''}|${low ?? ''}|${unsigned ?? ''}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseErrorReply(
|
||||
event: DakaoInboundEvent,
|
||||
err: CommandParseError,
|
||||
): DakaoSegment[] {
|
||||
const head: DakaoSegment[] = [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: event.userId,
|
||||
displayText: event.nickname,
|
||||
},
|
||||
];
|
||||
const text = ((): string => {
|
||||
switch (err.code) {
|
||||
case 'unknown_command':
|
||||
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록 또는 !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
|
||||
case 'usage':
|
||||
return ` 사용법: !내전 목록 또는 !내전 신청 <ID> <게임명>#<태그> <포지션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,138 @@
|
||||
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(),
|
||||
...overrides?.matchService,
|
||||
} as unknown as MatchService;
|
||||
const dakaoUserService = {
|
||||
resolveRiotAccount: jest.fn(),
|
||||
...overrides?.dakaoUserService,
|
||||
} as unknown as DakaoUserService;
|
||||
return new MatchJoinHandler(matchService, dakaoUserService);
|
||||
}
|
||||
|
||||
const baseParams = {
|
||||
communityId: objectId('111111111111111111111111'),
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
senderUserId: 'kakao-user-1',
|
||||
senderNickname: '프리리',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
positions: ['MID', 'TOP'] as const,
|
||||
};
|
||||
|
||||
describe('MatchJoinHandler', () => {
|
||||
it('rejects invalid match id without touching services', async () => {
|
||||
const handler = makeHandler();
|
||||
const segments = await handler.handle({
|
||||
...baseParams,
|
||||
matchId: 'not-an-id',
|
||||
positions: [...baseParams.positions],
|
||||
});
|
||||
expect(segments).toEqual([
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('유효하지 않은 매치 ID'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
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('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,122 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchService } from '../../match/match.service';
|
||||
import { Position, PositionPreference } from '../../global/database/schema';
|
||||
import { DakaoSegment } from '../dakao.types';
|
||||
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||
|
||||
interface JoinHandlerParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: string;
|
||||
senderUserId: string; // kakaoTalkId
|
||||
senderNickname: string; // kakaoTalkNickname
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchJoinHandler {
|
||||
constructor(
|
||||
private readonly matchService: MatchService,
|
||||
private readonly dakaoUserService: DakaoUserService,
|
||||
) {}
|
||||
|
||||
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
|
||||
if (!mongoose.isValidObjectId(params.matchId)) {
|
||||
return this.errorReply(params, '유효하지 않은 매치 ID 입니다.');
|
||||
}
|
||||
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
|
||||
|
||||
let resolved;
|
||||
try {
|
||||
resolved = await this.dakaoUserService.resolveRiotAccount({
|
||||
communityId: params.communityId,
|
||||
kakaoTalkId: params.senderUserId,
|
||||
kakaoTalkNickname: params.senderNickname,
|
||||
gameName: params.gameName,
|
||||
tagLine: params.tagLine,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof DakaoUserError) {
|
||||
return this.errorReply(params, this.translateUserError(err));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const preferredPositions: PositionPreference[] = params.positions.map(
|
||||
(position, index) => ({ position, priority: index + 1 }),
|
||||
);
|
||||
|
||||
try {
|
||||
const match = await this.matchService.join({
|
||||
matchId: matchObjectId,
|
||||
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포지션: ${params.positions.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 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_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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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 lines = matches.map((m, i) => {
|
||||
const id = (m._id as mongoose.Types.ObjectId).toString();
|
||||
const filled = m.participants.length;
|
||||
const cap = m.maxParticipants;
|
||||
const time = formatScheduledAt(m.scheduledAt);
|
||||
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`;
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: params.senderUserId,
|
||||
displayText: params.senderNickname,
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n신청: !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function formatScheduledAt(date: Date): string {
|
||||
// YYYY-MM-DD HH:mm (KST 표기)
|
||||
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
||||
const yyyy = kst.getUTCFullYear();
|
||||
const mm = String(kst.getUTCMonth() + 1).padStart(2, '0');
|
||||
const dd = String(kst.getUTCDate()).padStart(2, '0');
|
||||
const hh = String(kst.getUTCHours()).padStart(2, '0');
|
||||
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
||||
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
|
||||
}
|
||||
@@ -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,76 @@
|
||||
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-join command with simple riot id', () => {
|
||||
const result = parseCommand(
|
||||
'!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑',
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
matchId: '69b63bc96da18dfdb218ee8c',
|
||||
gameName: '프리리',
|
||||
tagLine: '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',
|
||||
gameName: 'hello world',
|
||||
tagLine: 'KR1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes hidden unicode differences in riot id', () => {
|
||||
const decomposedGameName = '프리리'.normalize('NFD');
|
||||
const result = parseCommand(
|
||||
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: 'match-join',
|
||||
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('throws invalid_match_id for non-objectid match', () => {
|
||||
expect(() =>
|
||||
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'),
|
||||
).toThrow(/invalid_match_id/);
|
||||
});
|
||||
|
||||
it('throws invalid_riot_id when # missing', () => {
|
||||
expect(() =>
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
|
||||
).toThrow(/invalid_riot_id/);
|
||||
});
|
||||
|
||||
it('throws invalid_position for too few positions', () => {
|
||||
expect(() => {
|
||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드');
|
||||
}).toThrow(CommandParseError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { ParsedPositions, parsePositionList } from './position.parser';
|
||||
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||
|
||||
export type DakaoCommand =
|
||||
| { kind: 'match-list' }
|
||||
| {
|
||||
kind: 'match-join';
|
||||
matchId: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
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 '리스트':
|
||||
return { kind: 'match-list' };
|
||||
case '신청':
|
||||
return parseJoinArgs(args);
|
||||
default:
|
||||
throw new CommandParseError('unknown_command', subCommand);
|
||||
}
|
||||
}
|
||||
|
||||
function parseJoinArgs(args: string): DakaoCommand {
|
||||
if (args.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId.
|
||||
// 형식: <matchId> <gameName...>#<tagLine> <pos1>,<pos2>...
|
||||
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
|
||||
const lastSpace = args.lastIndexOf(' ');
|
||||
if (lastSpace === -1) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
const positionPart = args.slice(lastSpace + 1).trim();
|
||||
const head = args.slice(0, lastSpace).trim();
|
||||
if (positionPart.length === 0 || head.length === 0) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
|
||||
const headSpace = head.indexOf(' ');
|
||||
if (headSpace === -1) {
|
||||
throw new CommandParseError('usage');
|
||||
}
|
||||
const matchId = head.slice(0, headSpace).trim();
|
||||
const riotId = head.slice(headSpace + 1).trim();
|
||||
|
||||
if (!isObjectIdHex(matchId)) {
|
||||
throw new CommandParseError('invalid_match_id', matchId);
|
||||
}
|
||||
|
||||
const hashIndex = riotId.lastIndexOf('#');
|
||||
if (hashIndex <= 0 || hashIndex === riotId.length - 1) {
|
||||
throw new CommandParseError('invalid_riot_id', riotId);
|
||||
}
|
||||
const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex));
|
||||
const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1));
|
||||
if (gameName.length === 0 || tagLine.length === 0) {
|
||||
throw new CommandParseError('invalid_riot_id', riotId);
|
||||
}
|
||||
|
||||
let positions: ParsedPositions;
|
||||
try {
|
||||
positions = parsePositionList(positionPart);
|
||||
} catch (err) {
|
||||
throw new CommandParseError(
|
||||
'invalid_position',
|
||||
(err as Error)?.message ?? positionPart,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'match-join',
|
||||
matchId,
|
||||
gameName,
|
||||
tagLine,
|
||||
positions,
|
||||
};
|
||||
}
|
||||
|
||||
function isObjectIdHex(value: string): boolean {
|
||||
return /^[a-f0-9]{24}$/i.test(value);
|
||||
}
|
||||
@@ -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, sup');
|
||||
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,87 @@
|
||||
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',
|
||||
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 = token.toLowerCase().replace(/\s+/g, '');
|
||||
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 };
|
||||
}
|
||||
@@ -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,14 @@
|
||||
import { resolveMongoDbName } from './connection.service';
|
||||
|
||||
describe('resolveMongoDbName', () => {
|
||||
it('uses production database only for prod', () => {
|
||||
expect(resolveMongoDbName('prod')).toBe('lolympus');
|
||||
});
|
||||
|
||||
it('uses isolated databases for non-production environments', () => {
|
||||
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
|
||||
expect(resolveMongoDbName('test')).toBe('lolympus-test');
|
||||
expect(resolveMongoDbName('')).toBe('lolympus-dev');
|
||||
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,12 @@ import mongoose from 'mongoose';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
||||
|
||||
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||
if (nodeEnv === 'prod') return 'lolympus';
|
||||
if (nodeEnv === 'test') return 'lolympus-test';
|
||||
return 'lolympus-dev';
|
||||
}
|
||||
|
||||
@Injectable({ scope: Scope.DEFAULT })
|
||||
export class ConnectionService implements OnModuleInit {
|
||||
private connection: mongoose.Connection | null = null;
|
||||
@@ -18,15 +24,16 @@ export class ConnectionService implements OnModuleInit {
|
||||
const connectionString = await this.secretService.get(
|
||||
'MONGODB_CONNECTION_STRING',
|
||||
);
|
||||
const dbName = resolveMongoDbName();
|
||||
const defaultConnection = await mongoose
|
||||
.createConnection(connectionString, {
|
||||
dbName: 'lolympus',
|
||||
dbName,
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
})
|
||||
.asPromise();
|
||||
this.connection = defaultConnection;
|
||||
console.log('Default Connection이 새로 생성됨.');
|
||||
console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`);
|
||||
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import mongoose, { Schema, HydratedDocument } from 'mongoose';
|
||||
import type {
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
} from '../../riot/riot.types';
|
||||
import { ModelDefinition } from './types';
|
||||
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
@@ -46,25 +50,44 @@ export interface MongooseTimestamps {
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
// ===== Identity =====
|
||||
export interface Identity extends MongooseTimestamps {
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
lastSignInAt?: Date;
|
||||
}
|
||||
|
||||
// ===== Tier =====
|
||||
export interface TierInfo {
|
||||
leagueId?: string;
|
||||
queueType: string; // RANKED_SOLO_5x5, RANKED_FLEX_SR 등
|
||||
tier: string; // IRON, BRONZE, ..., CHALLENGER
|
||||
rank: string; // I | II | III | IV
|
||||
puuid?: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
veteran?: boolean;
|
||||
inactive?: boolean;
|
||||
freshBlood?: boolean;
|
||||
hotStreak?: boolean;
|
||||
miniSeries?: Record<string, unknown>;
|
||||
fetchedAt: Date; // Riot API로부터 조회된 시각
|
||||
}
|
||||
|
||||
export interface TierHistoryEntry {
|
||||
season: string; // e.g., 'S13', 'S14'
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank?: string;
|
||||
leaguePoints?: number;
|
||||
wins?: number;
|
||||
losses?: number;
|
||||
recordedAt: Date;
|
||||
season?: string; // e.g., 'S13', 'S14'
|
||||
peakTier?: string;
|
||||
peakRank?: string;
|
||||
fetchedAt: Date;
|
||||
}
|
||||
|
||||
// ===== RiotAccount (User 하위에 임베딩) =====
|
||||
@@ -75,10 +98,18 @@ export interface TierHistoryEntry {
|
||||
export type ChampionRecordMap = Record<string, Record<string, unknown>>;
|
||||
|
||||
export interface ChampionMasteryEntry {
|
||||
championId: string;
|
||||
championName?: string;
|
||||
level: number;
|
||||
points: number;
|
||||
puuid: string;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
championPoints: number;
|
||||
lastPlayTime?: number;
|
||||
championPointsSinceLastLevel?: number;
|
||||
championPointsUntilNextLevel?: number;
|
||||
markRequiredForNextLevel?: number;
|
||||
tokensEarned?: number;
|
||||
championSeasonMilestone?: number;
|
||||
milestoneGrades?: string[];
|
||||
nextSeasonMilestone?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface RiotRecentStatsSummary {
|
||||
@@ -128,6 +159,7 @@ export interface RiotAccount extends MongooseTimestamps {
|
||||
// ===== User =====
|
||||
export interface User extends MongooseTimestamps {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
identityId?: mongoose.Types.ObjectId;
|
||||
role: CommunityRole;
|
||||
kakaoTalkId?: string;
|
||||
kakaoTalkNickname?: string;
|
||||
@@ -142,9 +174,13 @@ export interface Community extends MongooseTimestamps {
|
||||
name: string;
|
||||
description: string;
|
||||
ownerUserId: mongoose.Types.ObjectId;
|
||||
dakaoProjectId?: mongoose.Types.ObjectId;
|
||||
riotPlatform?: RiotPlatformRoute;
|
||||
riotRegion?: RiotRegionalRoute;
|
||||
}
|
||||
|
||||
export type CommunityDocument = HydratedDocument<Community>;
|
||||
export type IdentityDocument = HydratedDocument<Identity>;
|
||||
export type UserDocument = HydratedDocument<User>;
|
||||
|
||||
// ===== RiotMatch (Riot 원본 매치 아카이브) =====
|
||||
@@ -282,12 +318,19 @@ const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
||||
|
||||
const TierInfoSubSchema = new Schema<TierInfo>(
|
||||
{
|
||||
leagueId: { type: String },
|
||||
queueType: { type: String, required: true },
|
||||
tier: { type: String, required: true },
|
||||
rank: { type: String, required: true, default: '' },
|
||||
puuid: { type: String },
|
||||
leaguePoints: { type: Number, required: true, default: 0 },
|
||||
wins: { type: Number, required: true, default: 0 },
|
||||
losses: { type: Number, required: true, default: 0 },
|
||||
veteran: { type: Boolean },
|
||||
inactive: { type: Boolean },
|
||||
freshBlood: { type: Boolean },
|
||||
hotStreak: { type: Boolean },
|
||||
miniSeries: { type: Schema.Types.Mixed },
|
||||
fetchedAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
@@ -295,23 +338,34 @@ const TierInfoSubSchema = new Schema<TierInfo>(
|
||||
|
||||
const TierHistoryEntrySubSchema = new Schema<TierHistoryEntry>(
|
||||
{
|
||||
season: { type: String, required: true },
|
||||
queueType: { type: String, required: true },
|
||||
tier: { type: String, required: true },
|
||||
rank: { type: String },
|
||||
leaguePoints: { type: Number },
|
||||
wins: { type: Number },
|
||||
losses: { type: Number },
|
||||
recordedAt: { type: Date, required: true },
|
||||
season: { type: String },
|
||||
peakTier: { type: String },
|
||||
peakRank: { type: String },
|
||||
fetchedAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const ChampionMasteryEntrySubSchema = new Schema<ChampionMasteryEntry>(
|
||||
{
|
||||
championId: { type: String, required: true },
|
||||
championName: { type: String },
|
||||
level: { type: Number, required: true, default: 0 },
|
||||
points: { type: Number, required: true, default: 0 },
|
||||
puuid: { type: String, required: true },
|
||||
championId: { type: Number, required: true },
|
||||
championLevel: { type: Number, required: true, default: 0 },
|
||||
championPoints: { type: Number, required: true, default: 0 },
|
||||
lastPlayTime: { type: Number },
|
||||
championPointsSinceLastLevel: { type: Number },
|
||||
championPointsUntilNextLevel: { type: Number },
|
||||
markRequiredForNextLevel: { type: Number },
|
||||
tokensEarned: { type: Number },
|
||||
championSeasonMilestone: { type: Number },
|
||||
milestoneGrades: { type: [String] },
|
||||
nextSeasonMilestone: { type: Schema.Types.Mixed },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -374,11 +428,31 @@ const RiotAccountSubSchema = new Schema<RiotAccount>(
|
||||
},
|
||||
);
|
||||
|
||||
export const IdentitySchema = new Schema<Identity>(
|
||||
{
|
||||
entraOid: { type: String, required: true },
|
||||
tenantId: { type: String },
|
||||
email: { type: String },
|
||||
displayName: { type: String },
|
||||
lastSignInAt: { type: Date },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'identity',
|
||||
},
|
||||
);
|
||||
|
||||
IdentitySchema.index({ entraOid: 1 }, { unique: true });
|
||||
IdentitySchema.index({ email: 1 });
|
||||
|
||||
export const CommunitySchema = new Schema<Community>(
|
||||
{
|
||||
name: { type: String, required: true },
|
||||
description: { type: String, required: true, default: '' },
|
||||
ownerUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
dakaoProjectId: { type: Schema.Types.ObjectId },
|
||||
riotPlatform: { type: String },
|
||||
riotRegion: { type: String },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
@@ -388,6 +462,7 @@ export const CommunitySchema = new Schema<Community>(
|
||||
|
||||
CommunitySchema.index({ name: 1 }, { unique: true });
|
||||
CommunitySchema.index({ ownerUserId: 1 });
|
||||
CommunitySchema.index({ dakaoProjectId: 1 }, { unique: true, sparse: true });
|
||||
|
||||
export const UserSchema = new Schema<User>(
|
||||
{
|
||||
@@ -396,6 +471,7 @@ export const UserSchema = new Schema<User>(
|
||||
ref: 'community',
|
||||
required: true,
|
||||
},
|
||||
identityId: { type: Schema.Types.ObjectId, ref: 'identity' },
|
||||
role: {
|
||||
type: String,
|
||||
enum: COMMUNITY_ROLES,
|
||||
@@ -444,6 +520,14 @@ export const UserSchema = new Schema<User>(
|
||||
|
||||
UserSchema.index({ communityId: 1 });
|
||||
UserSchema.index({ communityId: 1, role: 1 });
|
||||
UserSchema.index(
|
||||
{ communityId: 1, identityId: 1 },
|
||||
{
|
||||
unique: true,
|
||||
partialFilterExpression: { identityId: { $exists: true } },
|
||||
},
|
||||
);
|
||||
UserSchema.index({ identityId: 1 }, { sparse: true });
|
||||
UserSchema.index(
|
||||
{ communityId: 1, kakaoTalkId: 1 },
|
||||
{ unique: true, sparse: true },
|
||||
@@ -676,6 +760,7 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
);
|
||||
|
||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||
{ name: 'user', schema: UserSchema, schemaName: 'user' },
|
||||
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
|
||||
@@ -684,6 +769,7 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
];
|
||||
|
||||
export interface TournamentModelTypes {
|
||||
identity: Identity;
|
||||
community: Community;
|
||||
user: User;
|
||||
riotMatch: RiotMatch;
|
||||
|
||||
@@ -1,28 +1,49 @@
|
||||
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
} from '@nestjs/common';
|
||||
import { StringCodec } from 'nats';
|
||||
import type { NatsConnection } from 'nats';
|
||||
import type { Msg, NatsConnection, Subscription } from 'nats';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
export type NatsMessageHandler<T = unknown> = (
|
||||
data: T,
|
||||
msg: Msg,
|
||||
) => Promise<void> | void;
|
||||
|
||||
@Injectable()
|
||||
export class NatsService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(NatsService.name);
|
||||
private readonly stringCodec = StringCodec();
|
||||
private readonly subscriptions = new Set<Subscription>();
|
||||
|
||||
constructor(
|
||||
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy() {
|
||||
for (const sub of this.subscriptions) {
|
||||
try {
|
||||
sub.unsubscribe();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.subscriptions.clear();
|
||||
|
||||
try {
|
||||
// 안전 종료: drain -> closed 대기
|
||||
const closed = this.natsClient.closed();
|
||||
await this.natsClient.drain();
|
||||
const err = await closed;
|
||||
if (err) console.error('NATS closed with error:', err);
|
||||
} catch (e) {
|
||||
// drain 실패 시 강제 close
|
||||
if (err) this.logger.error(`NATS closed with error: ${err}`);
|
||||
} catch {
|
||||
try {
|
||||
await this.natsClient.close();
|
||||
} catch {}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,4 +54,64 @@ export class NatsService implements OnModuleDestroy {
|
||||
);
|
||||
await this.natsClient.flush();
|
||||
}
|
||||
|
||||
public subscribe<T = unknown>(
|
||||
subject: string,
|
||||
handler: NatsMessageHandler<T>,
|
||||
options?: { queue?: string },
|
||||
): Subscription {
|
||||
const sub = this.natsClient.subscribe(subject, {
|
||||
queue: options?.queue,
|
||||
});
|
||||
this.subscriptions.add(sub);
|
||||
void this.consumeSubscription(sub, handler);
|
||||
return sub;
|
||||
}
|
||||
|
||||
private async consumeSubscription<T>(
|
||||
sub: Subscription,
|
||||
handler: NatsMessageHandler<T>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
for await (const msg of sub) {
|
||||
await this.dispatch(msg, handler);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`NATS subscription on subject="${sub.getSubject()}" terminated: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
this.subscriptions.delete(sub);
|
||||
}
|
||||
}
|
||||
|
||||
private async dispatch<T>(
|
||||
msg: Msg,
|
||||
handler: NatsMessageHandler<T>,
|
||||
): Promise<void> {
|
||||
let data: T;
|
||||
try {
|
||||
const decoded = this.stringCodec.decode(msg.data);
|
||||
data = JSON.parse(decoded) as T;
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to decode NATS message on subject="${msg.subject}": ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await handler(data, msg);
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Handler error on subject="${msg.subject}": ${
|
||||
(err as Error)?.stack ?? err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,16 @@ export class SecretService {
|
||||
'NATS_ENDPOINT',
|
||||
'NATS_TOKEN',
|
||||
'NATS_URL',
|
||||
'DAKAO_INBOUND_SUBJECT',
|
||||
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
|
||||
'DAKAO_REPLY_SUBJECT_PREFIX',
|
||||
'DAKAO_COMMAND_SOURCE',
|
||||
'DAKAO_BOT_USER_ID',
|
||||
'DAKAO_INSTANCE_ID',
|
||||
'JWT_CLAIM_AUDIENCE',
|
||||
'MICROSOFT_ENTRAID_TENANT_ID',
|
||||
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
|
||||
'AUTH_DEV_HEADER_ENABLED',
|
||||
// 필요시 추가
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -11,11 +11,14 @@ import {
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type {
|
||||
MatchDocument,
|
||||
@@ -30,6 +33,7 @@ import {
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
@Controller('communities/:communityId/matches')
|
||||
@UseInterceptors(UserResolverInterceptor)
|
||||
export class MatchController {
|
||||
constructor(private readonly matchService: MatchService) {}
|
||||
|
||||
@@ -61,6 +65,7 @@ export class MatchController {
|
||||
|
||||
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
|
||||
@Get()
|
||||
@AllowPublicAccess()
|
||||
public async listMatches(
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
@@ -81,6 +86,7 @@ export class MatchController {
|
||||
}
|
||||
|
||||
@Get(':matchId')
|
||||
@AllowPublicAccess()
|
||||
public async getMatch(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
@@ -117,6 +123,7 @@ export class MatchController {
|
||||
|
||||
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
|
||||
@Post(':matchId/participants')
|
||||
@AllowPublicAccess()
|
||||
public async joinMatch(
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
|
||||
@@ -35,6 +35,8 @@ interface JoinMatchParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
preferredPositions: PositionPreference[];
|
||||
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
|
||||
riotPuuid?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -119,22 +121,22 @@ export class MatchService {
|
||||
if (match.participants.length >= match.maxParticipants) {
|
||||
throw new BadRequestException('Match is full.');
|
||||
}
|
||||
const alreadyIn = match.participants.some((p) =>
|
||||
p.userId.equals(user._id),
|
||||
);
|
||||
const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
|
||||
if (alreadyIn) {
|
||||
throw new BadRequestException('User already joined this match.');
|
||||
}
|
||||
|
||||
const primaryRiot = user.riotAccounts.find((a) => a.isPrimary);
|
||||
const primaryTier = this.selectParticipantTier(primaryRiot?.tiers ?? []);
|
||||
const selectedRiot = params.riotPuuid
|
||||
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
|
||||
: user.riotAccounts.find((a) => a.isPrimary);
|
||||
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
|
||||
match.participants.push({
|
||||
userId: user._id,
|
||||
puuid: primaryRiot?.puuid,
|
||||
gameName: primaryRiot?.gameName,
|
||||
tagLine: primaryRiot?.tagLine,
|
||||
profileIconId: primaryRiot?.profileIconId,
|
||||
tier: primaryTier,
|
||||
puuid: selectedRiot?.puuid,
|
||||
gameName: selectedRiot?.gameName,
|
||||
tagLine: selectedRiot?.tagLine,
|
||||
profileIconId: selectedRiot?.profileIconId,
|
||||
tier: selectedTier,
|
||||
preferredPositions: params.preferredPositions,
|
||||
joinedAt: new Date(),
|
||||
});
|
||||
@@ -148,12 +150,19 @@ export class MatchService {
|
||||
if (!tier) return undefined;
|
||||
|
||||
return {
|
||||
leagueId: tier.leagueId,
|
||||
queueType: tier.queueType,
|
||||
tier: tier.tier,
|
||||
rank: tier.rank,
|
||||
puuid: tier.puuid,
|
||||
leaguePoints: tier.leaguePoints,
|
||||
wins: tier.wins,
|
||||
losses: tier.losses,
|
||||
veteran: tier.veteran,
|
||||
inactive: tier.inactive,
|
||||
freshBlood: tier.freshBlood,
|
||||
hotStreak: tier.hotStreak,
|
||||
miniSeries: tier.miniSeries,
|
||||
fetchedAt: tier.fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotApiError } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
|
||||
interface FakeAccount {
|
||||
puuid: string;
|
||||
profileIconId: number;
|
||||
revisionDate: number;
|
||||
summonerLevel: number;
|
||||
tiers: Array<{
|
||||
leagueId: string;
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank: string;
|
||||
puuid: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
fetchedAt: Date;
|
||||
}>;
|
||||
tierHistory: Array<{
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank?: string;
|
||||
leaguePoints?: number;
|
||||
wins?: number;
|
||||
losses?: number;
|
||||
recordedAt: Date;
|
||||
}>;
|
||||
championMasteries: Array<{
|
||||
puuid: string;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
championPoints: number;
|
||||
}>;
|
||||
championMasteriesFetchedAt?: Date;
|
||||
championRecords: Record<string, unknown>;
|
||||
championRecordsFetchedAt?: Date;
|
||||
}
|
||||
|
||||
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
|
||||
return {
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 0,
|
||||
revisionDate: 0,
|
||||
summonerLevel: 0,
|
||||
tiers: [],
|
||||
tierHistory: [],
|
||||
championMasteries: [],
|
||||
championRecords: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeUser(account: FakeAccount) {
|
||||
const _id = new mongoose.Types.ObjectId();
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
return {
|
||||
_id,
|
||||
riotAccounts: [account],
|
||||
save,
|
||||
};
|
||||
}
|
||||
|
||||
function makeService(overrides?: {
|
||||
user?: any;
|
||||
account?: Partial<RiotAccountService>;
|
||||
summoner?: Partial<RiotSummonerService>;
|
||||
league?: Partial<RiotLeagueService>;
|
||||
mastery?: Partial<RiotChampionMasteryService>;
|
||||
}) {
|
||||
const user = overrides?.user;
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
exec: () => Promise.resolve(user ?? null),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ findById }),
|
||||
} as unknown as ConnectionService;
|
||||
|
||||
const summonerService = {
|
||||
getByPuuid: jest.fn(),
|
||||
...overrides?.summoner,
|
||||
} as unknown as RiotSummonerService;
|
||||
const accountService = {
|
||||
getRegionByPuuid: jest.fn(),
|
||||
...overrides?.account,
|
||||
} as unknown as RiotAccountService;
|
||||
const leagueService = {
|
||||
getEntriesByPuuid: jest.fn(),
|
||||
...overrides?.league,
|
||||
} as unknown as RiotLeagueService;
|
||||
const masteryService = {
|
||||
getTopByPuuid: jest.fn(),
|
||||
...overrides?.mastery,
|
||||
} as unknown as RiotChampionMasteryService;
|
||||
|
||||
const service = new RiotAccountEnrichmentService(
|
||||
connectionService,
|
||||
accountService,
|
||||
summonerService,
|
||||
leagueService,
|
||||
masteryService,
|
||||
);
|
||||
return {
|
||||
service,
|
||||
user,
|
||||
accountService,
|
||||
summonerService,
|
||||
leagueService,
|
||||
masteryService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('RiotAccountEnrichmentService', () => {
|
||||
it('returns failed for unknown user', async () => {
|
||||
const { service } = makeService();
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: new mongoose.Types.ObjectId(),
|
||||
puuid: 'puuid-1',
|
||||
});
|
||||
expect(result.summoner).toBe('failed');
|
||||
expect(result.account).toBeNull();
|
||||
});
|
||||
|
||||
it('fills summoner / league / mastery on first attach (force)', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
const { service, summonerService, leagueService, masteryService } =
|
||||
makeService({
|
||||
user,
|
||||
summoner: {
|
||||
getByPuuid: jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 588,
|
||||
revisionDate: 1776977597000,
|
||||
summonerLevel: 529,
|
||||
}),
|
||||
} as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 75,
|
||||
wins: 160,
|
||||
losses: 148,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
championId: 7,
|
||||
championLevel: 70,
|
||||
championPoints: 742560,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
|
||||
expect(result.summoner).toBe('updated');
|
||||
expect(result.league).toBe('updated');
|
||||
expect(result.masteries).toBe('updated');
|
||||
expect(account.profileIconId).toBe(588);
|
||||
expect(account.summonerLevel).toBe(529);
|
||||
expect(account.tiers).toHaveLength(1);
|
||||
expect(account.tiers[0]).toMatchObject({
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 75,
|
||||
});
|
||||
expect(account.tierHistory).toHaveLength(1);
|
||||
expect(account.tierHistory[0]).toMatchObject({
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
leaguePoints: 75,
|
||||
wins: 160,
|
||||
losses: 148,
|
||||
});
|
||||
expect(account.championMasteries).toEqual([
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
championId: 7,
|
||||
championLevel: 70,
|
||||
championPoints: 742560,
|
||||
},
|
||||
]);
|
||||
expect(account.championRecords).toEqual({});
|
||||
expect(user.save).toHaveBeenCalledTimes(1);
|
||||
expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
count: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it('skips fresh data when within TTL and not forced', async () => {
|
||||
const recent = new Date(Date.now() - 60_000);
|
||||
const account = makeAccount({
|
||||
profileIconId: 1,
|
||||
revisionDate: Date.now() - 60_000,
|
||||
summonerLevel: 100,
|
||||
tiers: [
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 1,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
fetchedAt: recent,
|
||||
},
|
||||
],
|
||||
championMasteriesFetchedAt: recent,
|
||||
});
|
||||
const user = makeUser(account);
|
||||
const summoner = jest.fn();
|
||||
const league = jest.fn();
|
||||
const mastery = jest.fn();
|
||||
const { service } = makeService({
|
||||
user,
|
||||
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: league,
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: mastery,
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
});
|
||||
|
||||
expect(result.summoner).toBe('fresh');
|
||||
expect(result.league).toBe('fresh');
|
||||
expect(result.masteries).toBe('fresh');
|
||||
expect(summoner).not.toHaveBeenCalled();
|
||||
expect(league).not.toHaveBeenCalled();
|
||||
expect(mastery).not.toHaveBeenCalled();
|
||||
expect(user.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('records failed for individual failing fetches but updates the rest', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
summoner: {
|
||||
getByPuuid: jest.fn().mockRejectedValue(new Error('boom')),
|
||||
} as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
expect(result.summoner).toBe('failed');
|
||||
expect(result.league).toBe('updated');
|
||||
expect(result.masteries).toBe('updated');
|
||||
expect(user.save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retries summoner lookup with region/by-puuid platform on 404', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
const summoner = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new RiotApiError('not found', 404, 'url'))
|
||||
.mockResolvedValueOnce({
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 100,
|
||||
revisionDate: 1776977597000,
|
||||
summonerLevel: 30,
|
||||
});
|
||||
const region = jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-1',
|
||||
game: 'lol',
|
||||
region: 'jp1',
|
||||
});
|
||||
const league = jest.fn().mockResolvedValue([]);
|
||||
const mastery = jest.fn().mockResolvedValue([]);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
account: { getRegionByPuuid: region } as Partial<RiotAccountService>,
|
||||
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: league,
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: mastery,
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true, platform: 'kr' },
|
||||
});
|
||||
|
||||
expect(result.summoner).toBe('updated');
|
||||
expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' });
|
||||
expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', {
|
||||
platform: 'jp1',
|
||||
});
|
||||
expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' });
|
||||
expect(mastery).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'jp1',
|
||||
count: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it('deduplicates concurrent enrichment for the same user and puuid', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
let resolveSummoner: (value: unknown) => void;
|
||||
const summonerPromise = new Promise((resolve) => {
|
||||
resolveSummoner = resolve;
|
||||
});
|
||||
const summoner = jest.fn().mockReturnValue(summonerPromise);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const first = service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
const second = service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
|
||||
resolveSummoner!({
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 100,
|
||||
revisionDate: 1776977597000,
|
||||
summonerLevel: 30,
|
||||
});
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(summoner).toHaveBeenCalledTimes(1);
|
||||
expect(user.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,329 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
ChampionMasteryEntry,
|
||||
RiotAccount,
|
||||
TierInfo,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotApiError } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
import {
|
||||
RiotChampionMasteryDto,
|
||||
RiotLeagueEntryDto,
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
RiotSummonerDto,
|
||||
} from './riot.types';
|
||||
|
||||
const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
|
||||
const MASTERY_LIMIT = 10;
|
||||
|
||||
const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h
|
||||
const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
|
||||
export interface EnrichOptions {
|
||||
platform?: RiotPlatformRoute;
|
||||
region?: RiotRegionalRoute;
|
||||
force?: boolean;
|
||||
summonerTtlMs?: number;
|
||||
leagueTtlMs?: number;
|
||||
masteryTtlMs?: number;
|
||||
}
|
||||
|
||||
export interface EnrichResult {
|
||||
summoner: 'updated' | 'fresh' | 'failed';
|
||||
league: 'updated' | 'fresh' | 'failed';
|
||||
masteries: 'updated' | 'fresh' | 'failed';
|
||||
account: RiotAccount | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotAccountEnrichmentService {
|
||||
private readonly logger = new Logger(RiotAccountEnrichmentService.name);
|
||||
private readonly inFlight = new Map<string, Promise<EnrichResult>>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly accountService: RiotAccountService,
|
||||
private readonly summonerService: RiotSummonerService,
|
||||
private readonly leagueService: RiotLeagueService,
|
||||
private readonly masteryService: RiotChampionMasteryService,
|
||||
) {}
|
||||
|
||||
public async enrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
options?: EnrichOptions;
|
||||
}): Promise<EnrichResult> {
|
||||
const key = `${params.userId.toString()}:${params.puuid}`;
|
||||
const existing = this.inFlight.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
const promise = this.doEnrichRiotAccount(params).finally(() => {
|
||||
this.inFlight.delete(key);
|
||||
});
|
||||
this.inFlight.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async doEnrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
options?: EnrichOptions;
|
||||
}): Promise<EnrichResult> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findById(params.userId).exec();
|
||||
if (!user) {
|
||||
return {
|
||||
summoner: 'failed',
|
||||
league: 'failed',
|
||||
masteries: 'failed',
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
|
||||
if (!account) {
|
||||
return {
|
||||
summoner: 'failed',
|
||||
league: 'failed',
|
||||
masteries: 'failed',
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
|
||||
const opts = params.options ?? {};
|
||||
const platform = opts.platform ?? DEFAULT_PLATFORM;
|
||||
const region = opts.region ?? DEFAULT_REGION;
|
||||
const now = Date.now();
|
||||
|
||||
const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS;
|
||||
const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS;
|
||||
const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS;
|
||||
const force = opts.force === true;
|
||||
|
||||
const summonerStale =
|
||||
force ||
|
||||
account.revisionDate === 0 ||
|
||||
now - account.revisionDate > summonerTtl;
|
||||
const leagueStale =
|
||||
force ||
|
||||
account.tiers.length === 0 ||
|
||||
this.tiersOldestAt(account.tiers) < now - leagueTtl;
|
||||
const masteryStale =
|
||||
force ||
|
||||
!account.championMasteriesFetchedAt ||
|
||||
now - account.championMasteriesFetchedAt.getTime() > masteryTtl;
|
||||
|
||||
const summonerOutcome = summonerStale
|
||||
? await this.fetchSummonerSafe(params.puuid, platform, region)
|
||||
: { status: 'fresh' as const, dto: null, platform };
|
||||
const effectivePlatform = summonerOutcome.platform ?? platform;
|
||||
|
||||
const [leagueOutcome, masteryOutcome] = await Promise.all([
|
||||
leagueStale
|
||||
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
masteryStale
|
||||
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
]);
|
||||
|
||||
if (summonerOutcome.status === 'updated' && summonerOutcome.dto) {
|
||||
this.applySummoner(account, summonerOutcome.dto);
|
||||
}
|
||||
if (leagueOutcome.status === 'updated' && leagueOutcome.dto) {
|
||||
this.applyLeagueEntries(account, leagueOutcome.dto);
|
||||
}
|
||||
if (masteryOutcome.status === 'updated' && masteryOutcome.dto) {
|
||||
this.applyMasteries(account, masteryOutcome.dto);
|
||||
}
|
||||
|
||||
if (
|
||||
summonerOutcome.status === 'updated' ||
|
||||
leagueOutcome.status === 'updated' ||
|
||||
masteryOutcome.status === 'updated'
|
||||
) {
|
||||
await user.save();
|
||||
}
|
||||
|
||||
return {
|
||||
summoner: summonerOutcome.status,
|
||||
league: leagueOutcome.status,
|
||||
masteries: masteryOutcome.status,
|
||||
account,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchSummonerSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
region: RiotRegionalRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute }
|
||||
| { status: 'failed'; dto: null; platform: RiotPlatformRoute }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.summonerService.getByPuuid(puuid, { platform });
|
||||
return { status: 'updated', dto, platform };
|
||||
} catch (err) {
|
||||
if (err instanceof RiotApiError && err.status === 404) {
|
||||
try {
|
||||
const regionDto = await this.accountService.getRegionByPuuid(puuid, {
|
||||
region,
|
||||
});
|
||||
if (regionDto.region !== platform) {
|
||||
this.logger.warn(
|
||||
`Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`,
|
||||
);
|
||||
}
|
||||
const dto = await this.summonerService.getByPuuid(puuid, {
|
||||
platform: regionDto.region,
|
||||
});
|
||||
return { status: 'updated', dto, platform: regionDto.region };
|
||||
} catch (fallbackErr) {
|
||||
this.logger.warn(
|
||||
`Summoner fallback fetch failed for ${puuid}: ${
|
||||
(fallbackErr as Error)?.message ?? fallbackErr
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null, platform };
|
||||
}
|
||||
}
|
||||
this.logger.warn(
|
||||
`Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`,
|
||||
);
|
||||
return { status: 'failed', dto: null, platform };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchLeagueSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotLeagueEntryDto[] }
|
||||
| { status: 'failed'; dto: null }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.leagueService.getEntriesByPuuid(puuid, {
|
||||
platform,
|
||||
});
|
||||
return { status: 'updated', dto };
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`League entries fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchMasteriesSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotChampionMasteryDto[] }
|
||||
| { status: 'failed'; dto: null }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.masteryService.getTopByPuuid(puuid, {
|
||||
platform,
|
||||
count: MASTERY_LIMIT,
|
||||
});
|
||||
return { status: 'updated', dto };
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Champion masteries fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null };
|
||||
}
|
||||
}
|
||||
|
||||
private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void {
|
||||
account.profileIconId = dto.profileIconId;
|
||||
account.revisionDate = dto.revisionDate;
|
||||
account.summonerLevel = dto.summonerLevel;
|
||||
}
|
||||
|
||||
private applyLeagueEntries(
|
||||
account: RiotAccount,
|
||||
entries: RiotLeagueEntryDto[],
|
||||
): void {
|
||||
const fetchedAt = new Date();
|
||||
this.appendTierHistoryIfChanged(account, entries, fetchedAt);
|
||||
const next: TierInfo[] = entries.map((e) => ({
|
||||
leagueId: e.leagueId,
|
||||
queueType: e.queueType,
|
||||
tier: e.tier,
|
||||
rank: e.rank,
|
||||
puuid: e.puuid,
|
||||
leaguePoints: e.leaguePoints,
|
||||
wins: e.wins,
|
||||
losses: e.losses,
|
||||
veteran: e.veteran,
|
||||
inactive: e.inactive,
|
||||
freshBlood: e.freshBlood,
|
||||
hotStreak: e.hotStreak,
|
||||
miniSeries: e.miniSeries,
|
||||
fetchedAt,
|
||||
}));
|
||||
account.tiers = next;
|
||||
}
|
||||
|
||||
private appendTierHistoryIfChanged(
|
||||
account: RiotAccount,
|
||||
entries: RiotLeagueEntryDto[],
|
||||
recordedAt: Date,
|
||||
): void {
|
||||
for (const entry of entries) {
|
||||
const last = [...account.tierHistory]
|
||||
.reverse()
|
||||
.find((history) => history.queueType === entry.queueType);
|
||||
const changed =
|
||||
!last ||
|
||||
last.tier !== entry.tier ||
|
||||
(last.rank ?? '') !== (entry.rank ?? '');
|
||||
if (!changed) continue;
|
||||
|
||||
account.tierHistory.push({
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints,
|
||||
wins: entry.wins,
|
||||
losses: entry.losses,
|
||||
recordedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private applyMasteries(
|
||||
account: RiotAccount,
|
||||
masteries: RiotChampionMasteryDto[],
|
||||
): void {
|
||||
const summary: ChampionMasteryEntry[] = masteries
|
||||
.slice(0, MASTERY_LIMIT)
|
||||
.map((m) => ({ ...m }));
|
||||
account.championMasteries = summary;
|
||||
account.championMasteriesFetchedAt = new Date();
|
||||
}
|
||||
|
||||
private tiersOldestAt(tiers: TierInfo[]): number {
|
||||
if (tiers.length === 0) return 0;
|
||||
let oldest = Infinity;
|
||||
for (const t of tiers) {
|
||||
const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0;
|
||||
if (at < oldest) oldest = at;
|
||||
}
|
||||
return oldest === Infinity ? 0 : oldest;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import {
|
||||
RIOT_PLATFORM_ROUTES,
|
||||
RiotAccountDto,
|
||||
RiotAccountLookupOptions,
|
||||
RiotAccountRegionDto,
|
||||
} from './riot.types';
|
||||
|
||||
@Injectable()
|
||||
@@ -37,6 +39,20 @@ export class RiotAccountService {
|
||||
parseRiotAccountDto,
|
||||
);
|
||||
}
|
||||
|
||||
public async getRegionByPuuid(
|
||||
puuid: string,
|
||||
options: RiotAccountLookupOptions = {},
|
||||
): Promise<RiotAccountRegionDto> {
|
||||
return this.riotClientService.get<RiotAccountRegionDto>(
|
||||
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
{
|
||||
region: options.region ?? 'asia',
|
||||
signal: options.signal,
|
||||
},
|
||||
parseRiotAccountRegionDto,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function parseRiotAccountDto(value: unknown): RiotAccountDto {
|
||||
@@ -67,6 +83,38 @@ function parseRiotAccountDto(value: unknown): RiotAccountDto {
|
||||
};
|
||||
}
|
||||
|
||||
function parseRiotAccountRegionDto(value: unknown): RiotAccountRegionDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError('Riot account region response must be an object.');
|
||||
}
|
||||
|
||||
const puuid = value.puuid;
|
||||
const game = value.game;
|
||||
const region = value.region;
|
||||
|
||||
if (!isNonEmptyString(puuid)) {
|
||||
throw new TypeError(
|
||||
'Riot account region response is missing a valid puuid.',
|
||||
);
|
||||
}
|
||||
if (!isNonEmptyString(game)) {
|
||||
throw new TypeError(
|
||||
'Riot account region response is missing a valid game.',
|
||||
);
|
||||
}
|
||||
const platformRegion = region as (typeof RIOT_PLATFORM_ROUTES)[number];
|
||||
if (
|
||||
!isNonEmptyString(region) ||
|
||||
!RIOT_PLATFORM_ROUTES.includes(platformRegion)
|
||||
) {
|
||||
throw new TypeError(
|
||||
'Riot account region response is missing a valid region.',
|
||||
);
|
||||
}
|
||||
|
||||
return { puuid, game, region: platformRegion };
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import {
|
||||
RiotChampionMasteryDto,
|
||||
RiotPlatformLookupOptions,
|
||||
} from './riot.types';
|
||||
|
||||
interface MasteriesByPuuidOptions extends RiotPlatformLookupOptions {
|
||||
count?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_TOP_MASTERY_COUNT = 10;
|
||||
const MAX_TOP_MASTERY_COUNT = 10;
|
||||
|
||||
@Injectable()
|
||||
export class RiotChampionMasteryService {
|
||||
constructor(private readonly riotClientService: RiotClientService) {}
|
||||
|
||||
public async getByPuuid(
|
||||
puuid: string,
|
||||
options: RiotPlatformLookupOptions = {},
|
||||
): Promise<RiotChampionMasteryDto[]> {
|
||||
return this.riotClientService.get<RiotChampionMasteryDto[]>(
|
||||
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
{
|
||||
platform: options.platform ?? 'kr',
|
||||
signal: options.signal,
|
||||
},
|
||||
parseMasteries,
|
||||
);
|
||||
}
|
||||
|
||||
public async getTopByPuuid(
|
||||
puuid: string,
|
||||
options: MasteriesByPuuidOptions = {},
|
||||
): Promise<RiotChampionMasteryDto[]> {
|
||||
const count = options.count ?? DEFAULT_TOP_MASTERY_COUNT;
|
||||
if (
|
||||
!Number.isInteger(count) ||
|
||||
count <= 0 ||
|
||||
count > MAX_TOP_MASTERY_COUNT
|
||||
) {
|
||||
throw new RangeError('count must be an integer between 1 and 10.');
|
||||
}
|
||||
return this.riotClientService.get<RiotChampionMasteryDto[]>(
|
||||
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
|
||||
{
|
||||
platform: options.platform ?? 'kr',
|
||||
signal: options.signal,
|
||||
query: { count },
|
||||
},
|
||||
parseMasteries,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function parseMasteries(value: unknown): RiotChampionMasteryDto[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new TypeError('Champion masteries response must be an array.');
|
||||
}
|
||||
return value.map((entry, index) => parseEntry(entry, index));
|
||||
}
|
||||
|
||||
function parseEntry(value: unknown, index: number): RiotChampionMasteryDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`championMasteries[${index}] must be an object.`);
|
||||
}
|
||||
const puuid = value.puuid;
|
||||
const championId = value.championId;
|
||||
const championLevel = value.championLevel;
|
||||
const championPoints = value.championPoints;
|
||||
if (typeof puuid !== 'string') {
|
||||
throw new TypeError(`championMasteries[${index}].puuid must be a string.`);
|
||||
}
|
||||
if (typeof championId !== 'number' || !Number.isFinite(championId)) {
|
||||
throw new TypeError(
|
||||
`championMasteries[${index}].championId must be a number.`,
|
||||
);
|
||||
}
|
||||
if (typeof championLevel !== 'number' || !Number.isFinite(championLevel)) {
|
||||
throw new TypeError(
|
||||
`championMasteries[${index}].championLevel must be a number.`,
|
||||
);
|
||||
}
|
||||
if (typeof championPoints !== 'number' || !Number.isFinite(championPoints)) {
|
||||
throw new TypeError(
|
||||
`championMasteries[${index}].championPoints must be a number.`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
...value,
|
||||
puuid,
|
||||
championId,
|
||||
championLevel,
|
||||
championPoints,
|
||||
lastPlayTime:
|
||||
typeof value.lastPlayTime === 'number' ? value.lastPlayTime : undefined,
|
||||
championPointsSinceLastLevel:
|
||||
typeof value.championPointsSinceLastLevel === 'number'
|
||||
? value.championPointsSinceLastLevel
|
||||
: undefined,
|
||||
championPointsUntilNextLevel:
|
||||
typeof value.championPointsUntilNextLevel === 'number'
|
||||
? value.championPointsUntilNextLevel
|
||||
: undefined,
|
||||
markRequiredForNextLevel:
|
||||
typeof value.markRequiredForNextLevel === 'number'
|
||||
? value.markRequiredForNextLevel
|
||||
: undefined,
|
||||
tokensEarned:
|
||||
typeof value.tokensEarned === 'number' ? value.tokensEarned : undefined,
|
||||
championSeasonMilestone:
|
||||
typeof value.championSeasonMilestone === 'number'
|
||||
? value.championSeasonMilestone
|
||||
: undefined,
|
||||
milestoneGrades: Array.isArray(value.milestoneGrades)
|
||||
? (value.milestoneGrades as unknown[]).filter(
|
||||
(v): v is string => typeof v === 'string',
|
||||
)
|
||||
: undefined,
|
||||
nextSeasonMilestone: isRecord(value.nextSeasonMilestone)
|
||||
? value.nextSeasonMilestone
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import {
|
||||
RiotLeagueEntryDto,
|
||||
RiotPlatformLookupOptions,
|
||||
} from './riot.types';
|
||||
|
||||
@Injectable()
|
||||
export class RiotLeagueService {
|
||||
constructor(private readonly riotClientService: RiotClientService) {}
|
||||
|
||||
public async getEntriesByPuuid(
|
||||
puuid: string,
|
||||
options: RiotPlatformLookupOptions = {},
|
||||
): Promise<RiotLeagueEntryDto[]> {
|
||||
return this.riotClientService.get<RiotLeagueEntryDto[]>(
|
||||
`/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
{
|
||||
platform: options.platform ?? 'kr',
|
||||
signal: options.signal,
|
||||
},
|
||||
parseLeagueEntries,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new TypeError('League entries response must be an array.');
|
||||
}
|
||||
return value.map((entry, index) => parseEntry(entry, index));
|
||||
}
|
||||
|
||||
function parseEntry(value: unknown, index: number): RiotLeagueEntryDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`leagueEntries[${index}] must be an object.`);
|
||||
}
|
||||
return {
|
||||
leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`),
|
||||
queueType: requireString(
|
||||
value.queueType,
|
||||
`leagueEntries[${index}].queueType`,
|
||||
),
|
||||
tier: requireString(value.tier, `leagueEntries[${index}].tier`),
|
||||
rank: requireString(value.rank, `leagueEntries[${index}].rank`),
|
||||
puuid: requireString(value.puuid, `leagueEntries[${index}].puuid`),
|
||||
leaguePoints: requireNumber(
|
||||
value.leaguePoints,
|
||||
`leagueEntries[${index}].leaguePoints`,
|
||||
),
|
||||
wins: requireNumber(value.wins, `leagueEntries[${index}].wins`),
|
||||
losses: requireNumber(value.losses, `leagueEntries[${index}].losses`),
|
||||
veteran: typeof value.veteran === 'boolean' ? value.veteran : undefined,
|
||||
inactive: typeof value.inactive === 'boolean' ? value.inactive : undefined,
|
||||
freshBlood:
|
||||
typeof value.freshBlood === 'boolean' ? value.freshBlood : undefined,
|
||||
hotStreak:
|
||||
typeof value.hotStreak === 'boolean' ? value.hotStreak : undefined,
|
||||
miniSeries: isRecord(value.miniSeries) ? value.miniSeries : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
function requireString(value: unknown, path: string): string {
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
throw new TypeError(`${path} must be a non-empty string.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireNumber(value: unknown, path: string): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new TypeError(`${path} must be a finite number.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import {
|
||||
RiotPlatformLookupOptions,
|
||||
RiotSummonerDto,
|
||||
} from './riot.types';
|
||||
|
||||
@Injectable()
|
||||
export class RiotSummonerService {
|
||||
constructor(private readonly riotClientService: RiotClientService) {}
|
||||
|
||||
public async getByPuuid(
|
||||
puuid: string,
|
||||
options: RiotPlatformLookupOptions = {},
|
||||
): Promise<RiotSummonerDto> {
|
||||
return this.riotClientService.get<RiotSummonerDto>(
|
||||
`/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
{
|
||||
platform: options.platform ?? 'kr',
|
||||
signal: options.signal,
|
||||
},
|
||||
parseSummoner,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function parseSummoner(value: unknown): RiotSummonerDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError('Riot summoner response must be an object.');
|
||||
}
|
||||
const puuid = value.puuid;
|
||||
const profileIconId = value.profileIconId;
|
||||
const revisionDate = value.revisionDate;
|
||||
const summonerLevel = value.summonerLevel;
|
||||
if (typeof puuid !== 'string' || puuid.length === 0) {
|
||||
throw new TypeError('Summoner.puuid must be a non-empty string.');
|
||||
}
|
||||
if (typeof profileIconId !== 'number') {
|
||||
throw new TypeError('Summoner.profileIconId must be a number.');
|
||||
}
|
||||
if (typeof revisionDate !== 'number') {
|
||||
throw new TypeError('Summoner.revisionDate must be a number.');
|
||||
}
|
||||
if (typeof summonerLevel !== 'number') {
|
||||
throw new TypeError('Summoner.summonerLevel must be a number.');
|
||||
}
|
||||
return {
|
||||
puuid,
|
||||
profileIconId,
|
||||
revisionDate,
|
||||
summonerLevel,
|
||||
id: typeof value.id === 'string' ? value.id : undefined,
|
||||
accountId:
|
||||
typeof value.accountId === 'string' ? value.accountId : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
|
||||
type RiotWebhookRequest = Request & {
|
||||
rawBody?: Buffer;
|
||||
@@ -14,6 +15,7 @@ type RiotWebhookRequest = Request & {
|
||||
@Controller('riot')
|
||||
export class RiotWebhookController {
|
||||
@All('webhooks/tournament')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public captureTournamentWebhook(@Req() req: RiotWebhookRequest) {
|
||||
const receivedAt = new Date().toISOString();
|
||||
|
||||
@@ -2,18 +2,39 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import {
|
||||
RiotApiErrorBody,
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
RiotRequestOptions,
|
||||
RiotResponseParser,
|
||||
} from './riot.types';
|
||||
|
||||
const RIOT_BASE_URLS: Record<RiotRegionalRoute, string> = {
|
||||
const RIOT_REGION_BASE_URLS: Record<RiotRegionalRoute, string> = {
|
||||
americas: 'https://americas.api.riotgames.com',
|
||||
asia: 'https://asia.api.riotgames.com',
|
||||
europe: 'https://europe.api.riotgames.com',
|
||||
sea: 'https://sea.api.riotgames.com',
|
||||
};
|
||||
|
||||
const RIOT_PLATFORM_BASE_URLS: Record<RiotPlatformRoute, string> = {
|
||||
br1: 'https://br1.api.riotgames.com',
|
||||
eun1: 'https://eun1.api.riotgames.com',
|
||||
euw1: 'https://euw1.api.riotgames.com',
|
||||
jp1: 'https://jp1.api.riotgames.com',
|
||||
kr: 'https://kr.api.riotgames.com',
|
||||
la1: 'https://la1.api.riotgames.com',
|
||||
la2: 'https://la2.api.riotgames.com',
|
||||
me1: 'https://me1.api.riotgames.com',
|
||||
na1: 'https://na1.api.riotgames.com',
|
||||
oc1: 'https://oc1.api.riotgames.com',
|
||||
ph2: 'https://ph2.api.riotgames.com',
|
||||
ru: 'https://ru.api.riotgames.com',
|
||||
sg2: 'https://sg2.api.riotgames.com',
|
||||
th2: 'https://th2.api.riotgames.com',
|
||||
tr1: 'https://tr1.api.riotgames.com',
|
||||
tw2: 'https://tw2.api.riotgames.com',
|
||||
vn2: 'https://vn2.api.riotgames.com',
|
||||
};
|
||||
|
||||
export class RiotApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -67,8 +88,9 @@ export class RiotClientService {
|
||||
}
|
||||
|
||||
private buildUrl(path: string, options: RiotRequestOptions): string {
|
||||
const region = options.region ?? 'asia';
|
||||
const baseUrl = RIOT_BASE_URLS[region];
|
||||
const baseUrl = options.platform
|
||||
? RIOT_PLATFORM_BASE_URLS[options.platform]
|
||||
: RIOT_REGION_BASE_URLS[options.region ?? 'asia'];
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
const url = new URL(`${baseUrl}${normalizedPath}`);
|
||||
|
||||
|
||||
@@ -1,14 +1,34 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SecretModule } from '../global/secret/secret.module';
|
||||
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import { RiotMatchService } from './riot-match.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
import { RiotWebhookController } from './riot-webhook.controller';
|
||||
|
||||
@Module({
|
||||
imports: [SecretModule],
|
||||
controllers: [RiotWebhookController],
|
||||
providers: [RiotClientService, RiotAccountService, RiotMatchService],
|
||||
exports: [RiotClientService, RiotAccountService, RiotMatchService],
|
||||
providers: [
|
||||
RiotClientService,
|
||||
RiotAccountService,
|
||||
RiotMatchService,
|
||||
RiotSummonerService,
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
],
|
||||
exports: [
|
||||
RiotClientService,
|
||||
RiotAccountService,
|
||||
RiotMatchService,
|
||||
RiotSummonerService,
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
],
|
||||
})
|
||||
export class RiotModule {}
|
||||
@@ -1,6 +1,39 @@
|
||||
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea';
|
||||
export const RIOT_REGIONAL_ROUTES = [
|
||||
'americas',
|
||||
'asia',
|
||||
'europe',
|
||||
'sea',
|
||||
] as const;
|
||||
export type RiotRegionalRoute = (typeof RIOT_REGIONAL_ROUTES)[number];
|
||||
|
||||
export const RIOT_PLATFORM_ROUTES = [
|
||||
'br1',
|
||||
'eun1',
|
||||
'euw1',
|
||||
'jp1',
|
||||
'kr',
|
||||
'la1',
|
||||
'la2',
|
||||
'me1',
|
||||
'na1',
|
||||
'oc1',
|
||||
'ph2',
|
||||
'ru',
|
||||
'sg2',
|
||||
'th2',
|
||||
'tr1',
|
||||
'tw2',
|
||||
'vn2',
|
||||
] as const;
|
||||
export type RiotPlatformRoute = (typeof RIOT_PLATFORM_ROUTES)[number];
|
||||
export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial';
|
||||
|
||||
export interface RiotAccountRegionDto {
|
||||
puuid: string;
|
||||
game: string;
|
||||
region: RiotPlatformRoute;
|
||||
}
|
||||
|
||||
export interface RiotAccountApiResponse {
|
||||
puuid: string;
|
||||
gameName?: string;
|
||||
@@ -15,6 +48,7 @@ export interface RiotAccountDto {
|
||||
|
||||
export interface RiotRequestOptions {
|
||||
region?: RiotRegionalRoute;
|
||||
platform?: RiotPlatformRoute;
|
||||
query?: Record<string, string | number | boolean | undefined>;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -38,6 +72,54 @@ export interface RiotMatchLookupOptions {
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface RiotPlatformLookupOptions {
|
||||
platform?: RiotPlatformRoute;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
// Summoner-V4 by-puuid 응답 (간소화 — 실제 응답에 id 가 빠질 수 있어 optional 처리)
|
||||
export interface RiotSummonerDto {
|
||||
puuid: string;
|
||||
profileIconId: number;
|
||||
revisionDate: number;
|
||||
summonerLevel: number;
|
||||
id?: string;
|
||||
accountId?: string;
|
||||
}
|
||||
|
||||
// League-V4 entries by-puuid 응답
|
||||
export interface RiotLeagueEntryDto {
|
||||
leagueId: string;
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank: string;
|
||||
puuid: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
veteran?: boolean;
|
||||
inactive?: boolean;
|
||||
freshBlood?: boolean;
|
||||
hotStreak?: boolean;
|
||||
miniSeries?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Champion-Mastery-V4 by-puuid 응답
|
||||
export interface RiotChampionMasteryDto extends Record<string, unknown> {
|
||||
puuid: string;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
championPoints: number;
|
||||
lastPlayTime?: number;
|
||||
championPointsSinceLastLevel?: number;
|
||||
championPointsUntilNextLevel?: number;
|
||||
markRequiredForNextLevel?: number;
|
||||
tokensEarned?: number;
|
||||
championSeasonMilestone?: number;
|
||||
milestoneGrades?: string[];
|
||||
nextSeasonMilestone?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface RiotMatchIdsLookupOptions extends RiotMatchLookupOptions {
|
||||
start?: number;
|
||||
count?: number;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type {
|
||||
CommunityDocument,
|
||||
UserDocument,
|
||||
} from '../../global/database/schema';
|
||||
|
||||
export interface MeIdentityDto {
|
||||
id: string;
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export interface MeMembershipDto {
|
||||
user: UserDocument;
|
||||
community: CommunityDocument | null;
|
||||
}
|
||||
|
||||
export interface MeResponseDto {
|
||||
identity: MeIdentityDto | null;
|
||||
memberships: MeMembershipDto[];
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { IsBoolean, IsIn, IsOptional } from 'class-validator';
|
||||
import { RIOT_PLATFORM_ROUTES } from '../../riot/riot.types';
|
||||
import type { RiotPlatformRoute } from '../../riot/riot.types';
|
||||
|
||||
export class RefreshRiotAccountDto {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
force?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(RIOT_PLATFORM_ROUTES)
|
||||
platform?: RiotPlatformRoute;
|
||||
}
|
||||
@@ -1,11 +1,120 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import '../auth/auth-request';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
IdentityDocument,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import type { MeResponseDto } from './dto/me-response.dto';
|
||||
import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto';
|
||||
|
||||
@Controller('me')
|
||||
export class UserController {
|
||||
constructor(
|
||||
private readonly enrichment: RiotAccountEnrichmentService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
public me(@CurrentUser() user: UserDocument | undefined) {
|
||||
return { user: user ?? null };
|
||||
@AllowPublicAccess()
|
||||
public async me(@Req() req: Request): Promise<MeResponseDto> {
|
||||
if (req.identity) {
|
||||
return this.resolveMeByIdentity(req.identity);
|
||||
}
|
||||
if (req.user) {
|
||||
return {
|
||||
identity: null,
|
||||
memberships: [
|
||||
{
|
||||
user: req.user,
|
||||
community: await this.findCommunity(req.user),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { identity: null, memberships: [] };
|
||||
}
|
||||
|
||||
@Post('riot-accounts/:puuid/refresh')
|
||||
public async refreshRiotAccount(
|
||||
@CurrentUser() user: UserDocument | undefined,
|
||||
@Req() req: Request,
|
||||
@Param('puuid') puuid: string,
|
||||
@Body() body: RefreshRiotAccountDto,
|
||||
) {
|
||||
const resolvedUser =
|
||||
user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null);
|
||||
if (!resolvedUser) {
|
||||
throw new UnauthorizedException('Authentication required.');
|
||||
}
|
||||
if (!resolvedUser.riotAccounts.some((account) => account.puuid === puuid)) {
|
||||
throw new ForbiddenException('Riot account does not belong to user.');
|
||||
}
|
||||
|
||||
return this.enrichment.enrichRiotAccount({
|
||||
userId: resolvedUser._id,
|
||||
puuid,
|
||||
options: {
|
||||
force: body.force === true,
|
||||
platform: body.platform,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async resolveMeByIdentity(
|
||||
identity: IdentityDocument,
|
||||
): Promise<MeResponseDto> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const users = await UserModel.find({ identityId: identity._id }).exec();
|
||||
const communities = await CommunityModel.find({
|
||||
_id: { $in: users.map((user) => user.communityId) },
|
||||
}).exec();
|
||||
const communityById = new Map(
|
||||
communities.map((community) => [community._id.toString(), community]),
|
||||
);
|
||||
|
||||
return {
|
||||
identity: {
|
||||
id: identity._id.toString(),
|
||||
entraOid: identity.entraOid,
|
||||
tenantId: identity.tenantId,
|
||||
email: identity.email,
|
||||
displayName: identity.displayName,
|
||||
},
|
||||
memberships: users.map((user) => ({
|
||||
user,
|
||||
community: communityById.get(user.communityId.toString()) ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private async findCommunity(user: UserDocument) {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
return CommunityModel.findById(user.communityId).exec();
|
||||
}
|
||||
|
||||
private async findUserByIdentityAndPuuid(
|
||||
identity: IdentityDocument,
|
||||
puuid: string,
|
||||
): Promise<UserDocument | null> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.findOne({
|
||||
identityId: identity._id,
|
||||
'riotAccounts.puuid': puuid,
|
||||
}).exec();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { UserController } from './user.controller';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule],
|
||||
controllers: [UserController],
|
||||
})
|
||||
export class UserModule {}
|
||||
+138
-20
@@ -81,16 +81,54 @@ type SeedPlayer = {
|
||||
wins: number;
|
||||
losses: number;
|
||||
};
|
||||
masteries: ChampionMasteryEntry[];
|
||||
masteries: SeedChampionMastery[];
|
||||
recentStatsSummary: RiotRecentStatsSummary;
|
||||
};
|
||||
|
||||
type SeedChampionMastery = {
|
||||
championId: string;
|
||||
championName?: string;
|
||||
level: number;
|
||||
points: number;
|
||||
};
|
||||
|
||||
const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community';
|
||||
const DEV_COMMUNITY_DESCRIPTION =
|
||||
'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.';
|
||||
|
||||
const NOW = new Date();
|
||||
|
||||
const CHAMPION_IDS: Record<string, number> = {
|
||||
Ahri: 103,
|
||||
Ashe: 22,
|
||||
Camille: 164,
|
||||
Ezreal: 81,
|
||||
Gwen: 887,
|
||||
Hwei: 910,
|
||||
JarvanIV: 59,
|
||||
Jax: 24,
|
||||
Jinx: 222,
|
||||
KaiSa: 145,
|
||||
LeeSin: 64,
|
||||
Nami: 267,
|
||||
Nasus: 75,
|
||||
Nautilus: 111,
|
||||
Nidalee: 76,
|
||||
Orianna: 61,
|
||||
Rakan: 497,
|
||||
Rengar: 107,
|
||||
Sona: 37,
|
||||
Syndra: 134,
|
||||
Taliyah: 163,
|
||||
Thresh: 412,
|
||||
Viego: 234,
|
||||
Viktor: 112,
|
||||
Xayah: 498,
|
||||
Yorick: 83,
|
||||
Yuumi: 350,
|
||||
Zeri: 221,
|
||||
};
|
||||
|
||||
const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
{
|
||||
key: 'priri',
|
||||
@@ -115,9 +153,19 @@ const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
losses: 22,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Syndra', championName: '신드라', level: 7, points: 124300 },
|
||||
{
|
||||
championId: 'Syndra',
|
||||
championName: '신드라',
|
||||
level: 7,
|
||||
points: 124300,
|
||||
},
|
||||
{ championId: 'Ahri', championName: '아리', level: 7, points: 98200 },
|
||||
{ championId: 'Orianna', championName: '오리아나', level: 6, points: 63400 },
|
||||
{
|
||||
championId: 'Orianna',
|
||||
championName: '오리아나',
|
||||
level: 6,
|
||||
points: 63400,
|
||||
},
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 24,
|
||||
@@ -155,7 +203,12 @@ const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
masteries: [
|
||||
{ championId: 'Viego', championName: '비에고', level: 7, points: 138200 },
|
||||
{ championId: 'LeeSin', championName: '리신', level: 6, points: 88700 },
|
||||
{ championId: 'Nidalee', championName: '니달리', level: 6, points: 64100 },
|
||||
{
|
||||
championId: 'Nidalee',
|
||||
championName: '니달리',
|
||||
level: 6,
|
||||
points: 64100,
|
||||
},
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 28,
|
||||
@@ -229,8 +282,18 @@ const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
losses: 11,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Thresh', championName: '쓰레쉬', level: 7, points: 187300 },
|
||||
{ championId: 'Nautilus', championName: '노틸러스', level: 7, points: 144800 },
|
||||
{
|
||||
championId: 'Thresh',
|
||||
championName: '쓰레쉬',
|
||||
level: 7,
|
||||
points: 187300,
|
||||
},
|
||||
{
|
||||
championId: 'Nautilus',
|
||||
championName: '노틸러스',
|
||||
level: 7,
|
||||
points: 144800,
|
||||
},
|
||||
{ championId: 'Rakan', championName: '라칸', level: 6, points: 65300 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
@@ -269,7 +332,12 @@ const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
masteries: [
|
||||
{ championId: 'Jinx', championName: '징크스', level: 7, points: 166100 },
|
||||
{ championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 },
|
||||
{ championId: 'Ezreal', championName: '이즈리얼', level: 6, points: 90100 },
|
||||
{
|
||||
championId: 'Ezreal',
|
||||
championName: '이즈리얼',
|
||||
level: 6,
|
||||
points: 90100,
|
||||
},
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 29,
|
||||
@@ -305,9 +373,19 @@ const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
losses: 8,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Viktor', championName: '빅토르', level: 7, points: 172900 },
|
||||
{
|
||||
championId: 'Viktor',
|
||||
championName: '빅토르',
|
||||
level: 7,
|
||||
points: 172900,
|
||||
},
|
||||
{ championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 },
|
||||
{ championId: 'Taliyah', championName: '탈리야', level: 6, points: 55300 },
|
||||
{
|
||||
championId: 'Taliyah',
|
||||
championName: '탈리야',
|
||||
level: 6,
|
||||
points: 55300,
|
||||
},
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 25,
|
||||
@@ -474,7 +552,10 @@ const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
},
|
||||
];
|
||||
|
||||
function createPreferences(main: Position, sub: Position): PositionPreference[] {
|
||||
function createPreferences(
|
||||
main: Position,
|
||||
sub: Position,
|
||||
): PositionPreference[] {
|
||||
const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter(
|
||||
(position) => position !== main && position !== sub,
|
||||
);
|
||||
@@ -490,6 +571,7 @@ function createPreferences(main: Position, sub: Position): PositionPreference[]
|
||||
}
|
||||
|
||||
function createTier(
|
||||
puuid: string,
|
||||
queueType: string,
|
||||
tier: string,
|
||||
rank: string,
|
||||
@@ -498,9 +580,11 @@ function createTier(
|
||||
losses: number,
|
||||
): TierInfo {
|
||||
return {
|
||||
leagueId: `dev-${puuid}-${queueType}`,
|
||||
queueType,
|
||||
tier,
|
||||
rank: rank || 'I',
|
||||
puuid,
|
||||
leaguePoints,
|
||||
wins,
|
||||
losses,
|
||||
@@ -513,8 +597,10 @@ function selectPrimaryTier(tiers: TierInfo[]) {
|
||||
}
|
||||
|
||||
function createRiotAccount(player: SeedPlayer) {
|
||||
const puuid = `dev-seed-${player.key}-puuid`;
|
||||
const tiers = [
|
||||
createTier(
|
||||
puuid,
|
||||
'RANKED_SOLO_5x5',
|
||||
player.tier.tier,
|
||||
player.tier.rank,
|
||||
@@ -527,6 +613,7 @@ function createRiotAccount(player: SeedPlayer) {
|
||||
if (player.flex) {
|
||||
tiers.push(
|
||||
createTier(
|
||||
puuid,
|
||||
'RANKED_FLEX_SR',
|
||||
player.flex.tier,
|
||||
player.flex.rank,
|
||||
@@ -538,7 +625,7 @@ function createRiotAccount(player: SeedPlayer) {
|
||||
}
|
||||
|
||||
return {
|
||||
puuid: `dev-seed-${player.key}-puuid`,
|
||||
puuid,
|
||||
gameName: player.gameName,
|
||||
tagLine: player.tagLine,
|
||||
profileIconId: player.profileIconId,
|
||||
@@ -550,7 +637,7 @@ function createRiotAccount(player: SeedPlayer) {
|
||||
matchIds: [],
|
||||
recentStatsSummary: player.recentStatsSummary,
|
||||
recentStatsFetchedAt: NOW,
|
||||
championMasteries: player.masteries,
|
||||
championMasteries: createChampionMasteries(puuid, player.masteries),
|
||||
championMasteriesFetchedAt: NOW,
|
||||
championRecords: {},
|
||||
championRecordsFetchedAt: NOW,
|
||||
@@ -559,16 +646,21 @@ function createRiotAccount(player: SeedPlayer) {
|
||||
};
|
||||
}
|
||||
|
||||
function createStaffRiotAccount(key: string, gameName: string, tagLine: string) {
|
||||
function createStaffRiotAccount(
|
||||
key: string,
|
||||
gameName: string,
|
||||
tagLine: string,
|
||||
) {
|
||||
const puuid = `dev-seed-${key}-puuid`;
|
||||
return {
|
||||
puuid: `dev-seed-${key}-puuid`,
|
||||
puuid,
|
||||
gameName,
|
||||
tagLine,
|
||||
profileIconId: 29,
|
||||
revisionDate: Date.now(),
|
||||
summonerLevel: 120,
|
||||
isPrimary: true,
|
||||
tiers: [createTier('RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)],
|
||||
tiers: [createTier(puuid, 'RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)],
|
||||
tierHistory: [],
|
||||
matchIds: [],
|
||||
recentStatsSummary: {
|
||||
@@ -582,10 +674,20 @@ function createStaffRiotAccount(key: string, gameName: string, tagLine: string)
|
||||
mostPlayedChampionIds: ['Orianna', 'JarvanIV'],
|
||||
},
|
||||
recentStatsFetchedAt: NOW,
|
||||
championMasteries: [
|
||||
{ championId: 'Orianna', championName: '오리아나', level: 5, points: 18300 },
|
||||
{ championId: 'JarvanIV', championName: '자르반 4세', level: 5, points: 12600 },
|
||||
],
|
||||
championMasteries: createChampionMasteries(puuid, [
|
||||
{
|
||||
championId: 'Orianna',
|
||||
championName: '오리아나',
|
||||
level: 5,
|
||||
points: 18300,
|
||||
},
|
||||
{
|
||||
championId: 'JarvanIV',
|
||||
championName: '자르반 4세',
|
||||
level: 5,
|
||||
points: 12600,
|
||||
},
|
||||
]),
|
||||
championMasteriesFetchedAt: NOW,
|
||||
championRecords: {},
|
||||
championRecordsFetchedAt: NOW,
|
||||
@@ -594,6 +696,18 @@ function createStaffRiotAccount(key: string, gameName: string, tagLine: string)
|
||||
};
|
||||
}
|
||||
|
||||
function createChampionMasteries(
|
||||
puuid: string,
|
||||
masteries: SeedChampionMastery[],
|
||||
): ChampionMasteryEntry[] {
|
||||
return masteries.map((mastery) => ({
|
||||
puuid,
|
||||
championId: CHAMPION_IDS[mastery.championId] ?? 0,
|
||||
championLevel: mastery.level,
|
||||
championPoints: mastery.points,
|
||||
}));
|
||||
}
|
||||
|
||||
function toMatchParticipant(user: {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
riotAccounts: Array<{
|
||||
@@ -650,7 +764,9 @@ async function main() {
|
||||
await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec();
|
||||
}
|
||||
|
||||
await MatchModel.deleteMany({ communityId: existingCommunity._id }).exec();
|
||||
await MatchModel.deleteMany({
|
||||
communityId: existingCommunity._id,
|
||||
}).exec();
|
||||
await UserModel.deleteMany({ communityId: existingCommunity._id }).exec();
|
||||
await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec();
|
||||
}
|
||||
@@ -664,6 +780,8 @@ async function main() {
|
||||
name: DEV_COMMUNITY_NAME,
|
||||
description: DEV_COMMUNITY_DESCRIPTION,
|
||||
ownerUserId,
|
||||
riotPlatform: 'kr',
|
||||
riotRegion: 'asia',
|
||||
});
|
||||
|
||||
const owner = {
|
||||
|
||||
@@ -1,2 +1,6 @@
|
||||
VITE_API_BASE_URL=http://126.dahyeon.us:3000
|
||||
VITE_API_BASE_URL=http://localhost:3000
|
||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
@@ -0,0 +1,6 @@
|
||||
VITE_API_BASE_URL=http://localhost:3000
|
||||
VITE_DEFAULT_COMMUNITY_ID=
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/<tenant-id>
|
||||
VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
@@ -10,6 +10,8 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@azure/msal-browser": "^5.8.0",
|
||||
"@azure/msal-react": "^5.3.1",
|
||||
"@tanstack/react-query": "^5.100.1",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
|
||||
+41
-9
@@ -1,11 +1,38 @@
|
||||
import { BrowserRouter, Link, Route, Routes } from 'react-router';
|
||||
import { useMsal } from '@azure/msal-react';
|
||||
import DevAuthSwitcher from './components/DevAuthSwitcher';
|
||||
import { DEFAULT_COMMUNITY_ID } from './config';
|
||||
import { useCommunity } from './api/hooks';
|
||||
import { isMsalConfigured } from './lib/auth/msal.config';
|
||||
import AuthCallbackPage from './pages/AuthCallback';
|
||||
import HomePage from './pages/HomePage';
|
||||
import LoginPage from './pages/Login';
|
||||
import MatchDetailPage from './pages/MatchDetailPage';
|
||||
import AuctionPage from './pages/AuctionPage';
|
||||
|
||||
function MsalHeaderActions() {
|
||||
const { accounts, instance } = useMsal();
|
||||
const account = instance.getActiveAccount() ?? accounts[0];
|
||||
|
||||
if (!account) {
|
||||
return (
|
||||
<Link className="btn btn-primary btn-xs px-3" to="/login">
|
||||
로그인
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-xs px-3"
|
||||
onClick={() => void instance.logoutRedirect()}
|
||||
>
|
||||
{account.name ?? account.username} 로그아웃
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
|
||||
const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS';
|
||||
@@ -21,20 +48,25 @@ function App() {
|
||||
>
|
||||
{communityLabel}
|
||||
</Link>
|
||||
{DEFAULT_COMMUNITY_ID ? (
|
||||
<span className="text-[10px] uppercase tracking-wider text-base-content/25">
|
||||
API Live
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] uppercase tracking-wider text-amber-500/70">
|
||||
Set `VITE_DEFAULT_COMMUNITY_ID`
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center gap-3">
|
||||
{DEFAULT_COMMUNITY_ID ? (
|
||||
<span className="text-[10px] uppercase tracking-wider text-base-content/25">
|
||||
API Live
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] uppercase tracking-wider text-amber-500/70">
|
||||
Set `VITE_DEFAULT_COMMUNITY_ID`
|
||||
</span>
|
||||
)}
|
||||
{isMsalConfigured && <MsalHeaderActions />}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/auth/callback" element={<AuthCallbackPage />} />
|
||||
<Route path="/match/:id" element={<MatchDetailPage />} />
|
||||
<Route path="/match/:id/auction" element={<AuctionPage />} />
|
||||
</Routes>
|
||||
|
||||
@@ -68,6 +68,7 @@ export interface ApiRiotAccount {
|
||||
export interface ApiUser {
|
||||
_id: string;
|
||||
communityId: string;
|
||||
identityId?: string;
|
||||
role: CommunityRole;
|
||||
kakaoTalkId?: string;
|
||||
kakaoTalkNickname?: string;
|
||||
@@ -198,8 +199,22 @@ export interface ApiAuction {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiIdentity {
|
||||
id: string;
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export interface ApiMembership {
|
||||
user: ApiUser;
|
||||
community: ApiCommunity | null;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
user: ApiUser | null;
|
||||
identity: ApiIdentity | null;
|
||||
memberships: ApiMembership[];
|
||||
}
|
||||
|
||||
export interface MatchesResponse {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||
import type { ApiAuction, Position, TeamSide } from './types';
|
||||
|
||||
type ConnectionStatus =
|
||||
@@ -31,37 +32,53 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const socket = io(`${API_BASE_URL}/auction`, {
|
||||
transports: ['websocket'],
|
||||
auth: authUserId ? { 'x-auth-user-id': authUserId } : {},
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
let disposed = false;
|
||||
setConnectionStatus('connecting');
|
||||
setError(null);
|
||||
|
||||
socket.on('connect', () => {
|
||||
setConnectionStatus('connected');
|
||||
socket.emit('join', { matchId });
|
||||
});
|
||||
void (async () => {
|
||||
const accessToken = await acquireAccessToken().catch((error) => {
|
||||
console.warn('Failed to acquire socket access token:', error);
|
||||
return null;
|
||||
});
|
||||
if (disposed) return;
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setConnectionStatus('disconnected');
|
||||
});
|
||||
const socket = io(`${API_BASE_URL}/auction`, {
|
||||
transports: ['websocket'],
|
||||
auth: accessToken
|
||||
? { token: accessToken }
|
||||
: authUserId
|
||||
? { 'x-auth-user-id': authUserId }
|
||||
: {},
|
||||
});
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
setAuction(nextAuction);
|
||||
setError(null);
|
||||
});
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.on('error', (payload: { message?: string }) => {
|
||||
setConnectionStatus('error');
|
||||
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
||||
});
|
||||
socket.on('connect', () => {
|
||||
setConnectionStatus('connected');
|
||||
socket.emit('join', { matchId });
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setConnectionStatus('disconnected');
|
||||
});
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
setAuction(nextAuction);
|
||||
setError(null);
|
||||
});
|
||||
|
||||
socket.on('error', (payload: { message?: string }) => {
|
||||
setConnectionStatus('error');
|
||||
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
||||
});
|
||||
})();
|
||||
|
||||
return () => {
|
||||
socket.removeAllListeners();
|
||||
socket.disconnect();
|
||||
disposed = true;
|
||||
const socket = socketRef.current;
|
||||
socket?.removeAllListeners();
|
||||
socket?.disconnect();
|
||||
socketRef.current = null;
|
||||
setConnectionStatus('idle');
|
||||
};
|
||||
|
||||
@@ -36,12 +36,14 @@ function subscribeToWindowChanges(eventName: string, callback: () => void) {
|
||||
}
|
||||
|
||||
export function getAuthUserId(): string | null {
|
||||
if (!import.meta.env.DEV) return null;
|
||||
if (typeof window === 'undefined') return null;
|
||||
const value = window.localStorage.getItem(AUTH_USER_ID_STORAGE_KEY)?.trim();
|
||||
return value ? value : null;
|
||||
}
|
||||
|
||||
export function setAuthUserId(userId: string | null) {
|
||||
if (!import.meta.env.DEV) return;
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
if (!userId?.trim()) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import './index.css';
|
||||
import App from './App.tsx';
|
||||
import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -16,8 +17,10 @@ const queryClient = new QueryClient({
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
<MsalAppProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</MsalAppProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
type AuctionStateView,
|
||||
} from '../api/mappers';
|
||||
import { useAuctionSocket } from '../api/useAuctionSocket';
|
||||
import { DEFAULT_COMMUNITY_ID, setDevCaptainSide, useDevCaptainSide } from '../config';
|
||||
import {
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
setDevCaptainSide,
|
||||
useDevCaptainSide,
|
||||
} from '../config';
|
||||
import { ApiError } from '../lib/api';
|
||||
import { positionIcon, positionLabel } from '../lib/league';
|
||||
import type { Position } from '../api/types';
|
||||
@@ -395,6 +399,10 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
|
||||
export default function AuctionPage() {
|
||||
const { id } = useParams();
|
||||
const meQuery = useMe();
|
||||
const currentUser =
|
||||
meQuery.data?.memberships.find(
|
||||
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
|
||||
)?.user ?? null;
|
||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||
const socket = useAuctionSocket(id);
|
||||
@@ -460,8 +468,8 @@ export default function AuctionPage() {
|
||||
|
||||
const canManageAuction =
|
||||
import.meta.env.DEV ||
|
||||
meQuery.data?.user?.role === 'owner' ||
|
||||
meQuery.data?.user?.role === 'admin';
|
||||
currentUser?.role === 'owner' ||
|
||||
currentUser?.role === 'admin';
|
||||
const phaseLabel: Record<AuctionStateView['phase'], string> = {
|
||||
waiting: '경매 준비 중...',
|
||||
presenting: '다음 선수 등장',
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
export default function AuthCallbackPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => navigate('/', { replace: true }), 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20 text-center">
|
||||
<span className="text-sm text-base-content/45">로그인 처리 중...</span>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useMsal } from '@azure/msal-react';
|
||||
import {
|
||||
isMsalConfigured,
|
||||
MSAL_API_SCOPE,
|
||||
msalInstance,
|
||||
} from '../lib/auth/msal.config';
|
||||
|
||||
function LoginButton() {
|
||||
const { instance } = useMsal();
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm px-5"
|
||||
onClick={() => void instance.loginRedirect({ scopes: [MSAL_API_SCOPE] })}
|
||||
>
|
||||
Microsoft로 로그인
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20">
|
||||
<div className="max-w-md border border-base-content/10 bg-base-100 p-6 shadow-sm">
|
||||
<h1 className="text-xl font-bold tracking-tight">로그인</h1>
|
||||
<p className="mt-2 text-sm text-base-content/50">
|
||||
Microsoft Entra ID 계정으로 로그인하면 LOLYMPUS 멤버십을 불러옵니다.
|
||||
</p>
|
||||
<div className="mt-5">
|
||||
{isMsalConfigured && msalInstance ? (
|
||||
<LoginButton />
|
||||
) : (
|
||||
<div className="text-sm text-amber-600">
|
||||
MSAL 환경변수 설정이 필요합니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -281,6 +281,11 @@ export default function MatchDetailPage() {
|
||||
const authUserId = useAuthUserId();
|
||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||
const meQuery = useMe();
|
||||
const currentUser =
|
||||
meQuery.data?.memberships.find(
|
||||
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
|
||||
)?.user ?? null;
|
||||
const canUseMemberActions = Boolean(currentUser || authUserId);
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||
const [blueCaptainUserId, setBlueCaptainUserId] = useState('');
|
||||
const [redCaptainUserId, setRedCaptainUserId] = useState('');
|
||||
@@ -291,8 +296,8 @@ export default function MatchDetailPage() {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
preferredPositions:
|
||||
meQuery.data?.user?.preferredPositions.length
|
||||
? meQuery.data.user.preferredPositions.slice(0, 5)
|
||||
currentUser?.preferredPositions.length
|
||||
? currentUser.preferredPositions.slice(0, 5)
|
||||
: buildDefaultPreferredPositions(),
|
||||
}),
|
||||
}),
|
||||
@@ -376,7 +381,7 @@ export default function MatchDetailPage() {
|
||||
const match = mapApiMatchToMatchDetail(matchQuery.data);
|
||||
const si = statusBadge(match.status);
|
||||
const canManageAuction =
|
||||
meQuery.data?.user?.role === 'owner' || meQuery.data?.user?.role === 'admin';
|
||||
currentUser?.role === 'owner' || currentUser?.role === 'admin';
|
||||
const auctionNotStarted =
|
||||
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
|
||||
const showAuctionLink = Boolean(auctionQuery.data);
|
||||
@@ -490,7 +495,7 @@ export default function MatchDetailPage() {
|
||||
participants={match.participants}
|
||||
maxParticipants={match.maxParticipants}
|
||||
joined={match.joined}
|
||||
canJoin={Boolean(authUserId)}
|
||||
canJoin={canUseMemberActions}
|
||||
onJoin={() => joinMatchMutation.mutate()}
|
||||
isJoining={joinMatchMutation.isPending}
|
||||
/>
|
||||
@@ -551,9 +556,9 @@ export default function MatchDetailPage() {
|
||||
>
|
||||
{startAuctionMutation.isPending ? '시작 중...' : '경매 시작'}
|
||||
</button>
|
||||
{!authUserId && (
|
||||
{!canUseMemberActions && (
|
||||
<span className="text-xs text-amber-600">
|
||||
Dev Auth에 owner/admin User ID를 먼저 입력해주세요.
|
||||
로그인 또는 Dev Auth에 owner/admin User ID를 먼저 입력해주세요.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user