.
This commit is contained in:
1 parent
5af2c80cd1
commit
f7ee34da4f
78 files changed
+9016
-150
No files matched your search
@@ -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;
|
||||
|
||||
|
||||
Reference in new issue
Block a user