db design
This commit is contained in:
1 parent
909845a1df
commit
2761780a7b
3 files changed
+574
-207
No files matched your search
@@ -1,14 +1,17 @@
|
||||
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { moeumModelDefinitions, MoeumModelTypes } from './schema';
|
||||
import {
|
||||
tournamentModelDefinitions,
|
||||
TournamentModelTypes,
|
||||
} from './schema';
|
||||
|
||||
@Injectable({ scope: Scope.DEFAULT })
|
||||
export class ConnectionService implements OnModuleInit {
|
||||
private connection: mongoose.Connection | null = null;
|
||||
constructor(private readonly secretService: SecretService) {}
|
||||
|
||||
private moeumModels: Map<string, mongoose.Model<any>> | null = null;
|
||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
||||
|
||||
public async getConnection(): Promise<mongoose.Connection> {
|
||||
if (this.connection !== null && this.connection.readyState === 1) {
|
||||
@@ -20,7 +23,7 @@ export class ConnectionService implements OnModuleInit {
|
||||
);
|
||||
const defaultConnection = await mongoose
|
||||
.createConnection(connectionString, {
|
||||
dbName: 'moeum',
|
||||
dbName: 'tournament',
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
})
|
||||
@@ -31,19 +34,18 @@ export class ConnectionService implements OnModuleInit {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
public async getMoeumModels<K extends keyof MoeumModelTypes>(
|
||||
public async getModel<K extends keyof TournamentModelTypes>(
|
||||
modelKey: K,
|
||||
): Promise<mongoose.Model<MoeumModelTypes[K]>> {
|
||||
if (this.moeumModels)
|
||||
return this.moeumModels.get(modelKey) as mongoose.Model<
|
||||
MoeumModelTypes[K]
|
||||
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
||||
if (this.tournamentModels)
|
||||
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
||||
TournamentModelTypes[K]
|
||||
>;
|
||||
|
||||
const moeumModels = new Map<K, mongoose.Model<MoeumModelTypes[K]>>();
|
||||
// const connection = await this.getTenantConnection(tenantId);
|
||||
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
||||
const connection = await this.getConnection();
|
||||
|
||||
moeumModelDefinitions.forEach((modelDefinition) => {
|
||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||
// 이미 생성된 경우 컴파일 스킵.
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
@@ -51,15 +53,15 @@ export class ConnectionService implements OnModuleInit {
|
||||
modelDefinition.name,
|
||||
)
|
||||
) {
|
||||
moeumModels.set(
|
||||
models.set(
|
||||
modelDefinition.name as K,
|
||||
connection.models[modelDefinition.name],
|
||||
);
|
||||
return;
|
||||
} else {
|
||||
moeumModels.set(
|
||||
models.set(
|
||||
modelDefinition.name as K,
|
||||
connection.model<MoeumModelTypes[K]>(
|
||||
connection.model<TournamentModelTypes[K]>(
|
||||
modelDefinition.name,
|
||||
modelDefinition.schema,
|
||||
modelDefinition.schemaName,
|
||||
@@ -68,8 +70,8 @@ export class ConnectionService implements OnModuleInit {
|
||||
}
|
||||
});
|
||||
|
||||
this.moeumModels = moeumModels;
|
||||
return moeumModels.get(modelKey) as mongoose.Model<MoeumModelTypes[K]>;
|
||||
this.tournamentModels = models;
|
||||
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
|
||||
}
|
||||
|
||||
public async createSession(
|
||||
|
||||
@@ -1,187 +1,556 @@
|
||||
import mongoose, { Schema, HydratedDocument } from 'mongoose';
|
||||
import { ModelDefinition } from './types';
|
||||
|
||||
export type MetadataDataType =
|
||||
| 'string'
|
||||
| 'number'
|
||||
| 'boolean'
|
||||
| 'array'
|
||||
| 'json';
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
||||
|
||||
export type MetadataValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| unknown[]
|
||||
| Record<string, unknown>
|
||||
| null;
|
||||
export type MatchStatus =
|
||||
| 'recruiting'
|
||||
| 'team-built'
|
||||
| 'in-progress'
|
||||
| 'finished';
|
||||
export const MATCH_STATUSES: MatchStatus[] = [
|
||||
'recruiting',
|
||||
'team-built',
|
||||
'in-progress',
|
||||
'finished',
|
||||
];
|
||||
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||
|
||||
export type AuctionPhase =
|
||||
| 'waiting'
|
||||
| 'presenting'
|
||||
| 'bidding'
|
||||
| 'sold'
|
||||
| 'complete';
|
||||
export const AUCTION_PHASES: AuctionPhase[] = [
|
||||
'waiting',
|
||||
'presenting',
|
||||
'bidding',
|
||||
'sold',
|
||||
'complete',
|
||||
];
|
||||
|
||||
export interface MongooseTimestamps {
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Metadata {
|
||||
key: string;
|
||||
value: MetadataValue;
|
||||
dataType: MetadataDataType;
|
||||
isReserved: boolean;
|
||||
// ===== Tier =====
|
||||
export interface TierInfo {
|
||||
queueType: string; // RANKED_SOLO_5x5, RANKED_FLEX_SR 등
|
||||
tier: string; // IRON, BRONZE, ..., CHALLENGER
|
||||
rank: string; // I | II | III | IV
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
fetchedAt: Date; // Riot API로부터 조회된 시각
|
||||
}
|
||||
|
||||
export interface TaxonomyChildItem {
|
||||
title: string;
|
||||
order: number;
|
||||
articleId?: mongoose.Types.ObjectId;
|
||||
slug?: string; //article document의 slug 참조 (임베딩)
|
||||
children?: TaxonomyChildItem[];
|
||||
export interface TierHistoryEntry {
|
||||
season: string; // e.g., 'S13', 'S14'
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank?: string;
|
||||
peakTier?: string;
|
||||
peakRank?: string;
|
||||
fetchedAt: Date;
|
||||
}
|
||||
|
||||
export interface Taxonomy extends MongooseTimestamps {
|
||||
// ===== RiotAccount (User 하위에 임베딩) =====
|
||||
/**
|
||||
* 챔피언 단위 집계 기록. 필드 추가가 잦을 것으로 예상되어 Mixed로 저장.
|
||||
* key: championId (string), value: championId별 누적/평균 지표 자유형 JSON
|
||||
*/
|
||||
export type ChampionRecordMap = Record<string, Record<string, unknown>>;
|
||||
|
||||
export interface ChampionMasteryEntry {
|
||||
championId: string;
|
||||
championName?: string;
|
||||
level: number;
|
||||
points: number;
|
||||
}
|
||||
|
||||
export interface RiotRecentStatsSummary {
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
avgCs: number;
|
||||
mostPlayedChampionIds: string[];
|
||||
// 필드 추가가 잦을 수 있어 확장용 추가 메트릭 영역 허용
|
||||
extras?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface RiotAccount extends MongooseTimestamps {
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
revisionDate: number;
|
||||
summonerLevel: number;
|
||||
isPrimary: boolean;
|
||||
|
||||
// 현재 티어들(솔랭/자랭 각각)
|
||||
tiers: TierInfo[];
|
||||
// 과거 티어 기록
|
||||
tierHistory: TierHistoryEntry[];
|
||||
|
||||
// Riot matchId 참조 (원본은 RiotMatch 컬렉션에 저장)
|
||||
matchIds: string[];
|
||||
matchIdsFetchedAt?: Date;
|
||||
|
||||
// 최근 경기 요약
|
||||
recentStatsSummary?: RiotRecentStatsSummary;
|
||||
recentStatsFetchedAt?: Date;
|
||||
|
||||
// 챔피언 숙련도
|
||||
championMasteries: ChampionMasteryEntry[];
|
||||
championMasteriesFetchedAt?: Date;
|
||||
|
||||
// 챔피언별 기록 (JSON, 필드 추가 자유로움)
|
||||
championRecords: ChampionRecordMap;
|
||||
championRecordsFetchedAt?: Date;
|
||||
}
|
||||
|
||||
// ===== User =====
|
||||
export interface User extends MongooseTimestamps {
|
||||
kakaoTalkId?: string;
|
||||
kakaoTalkNickname?: string;
|
||||
discordId?: string;
|
||||
discordNickname?: string;
|
||||
riotAccounts: RiotAccount[];
|
||||
preferredPositions: Position[];
|
||||
isActivated: boolean;
|
||||
}
|
||||
|
||||
export type UserDocument = HydratedDocument<User>;
|
||||
|
||||
// ===== RiotMatch (Riot 원본 매치 아카이브) =====
|
||||
export interface RiotMatch extends MongooseTimestamps {
|
||||
matchId: string; // Riot matchId (예: KR_7123456789)
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
gameVersion?: string;
|
||||
queueId?: number;
|
||||
participantPuuids: string[];
|
||||
raw: Record<string, unknown>; // Riot API Match-V5 원본 응답 전체
|
||||
fetchedAt: Date;
|
||||
}
|
||||
|
||||
export type RiotMatchDocument = HydratedDocument<RiotMatch>;
|
||||
|
||||
// ===== Match (내전) =====
|
||||
export interface MatchParticipant {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
// 표시용 스냅샷 (대표 RiotAccount 기준)
|
||||
puuid?: string;
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
profileIconId?: number;
|
||||
preferredPositions: Position[];
|
||||
joinedAt: Date;
|
||||
}
|
||||
|
||||
export interface MatchTeamMember {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
assignedPosition: Position;
|
||||
cost?: number; // 경매로 영입된 경우의 입찰가
|
||||
}
|
||||
|
||||
export interface MatchTeam {
|
||||
side: TeamSide;
|
||||
name: string;
|
||||
captainUserId?: mongoose.Types.ObjectId;
|
||||
members: MatchTeamMember[];
|
||||
}
|
||||
|
||||
export interface MatchResult {
|
||||
winnerSide: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
mvpUserId?: mongoose.Types.ObjectId;
|
||||
riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들
|
||||
}
|
||||
|
||||
export interface MatchScheduleItem {
|
||||
time: string;
|
||||
label: string;
|
||||
items: TaxonomyChildItem[];
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
|
||||
export type TaxonomyDocument = HydratedDocument<Taxonomy>;
|
||||
|
||||
export interface ContentSection {
|
||||
headline: string;
|
||||
taxonomies: ContentSectionEmbeddedTaxonomy[];
|
||||
}
|
||||
|
||||
export interface ContentSectionEmbeddedTaxonomy {
|
||||
taxonomyId: mongoose.Types.ObjectId;
|
||||
label: string; // 성능 최적화를 위해 임베딩된 label
|
||||
}
|
||||
|
||||
export interface Content extends MongooseTimestamps {
|
||||
key: string;
|
||||
label: string;
|
||||
sections: ContentSection[];
|
||||
}
|
||||
|
||||
export type ContentDocument = HydratedDocument<Content>;
|
||||
|
||||
export interface Article extends MongooseTimestamps {
|
||||
export interface Match extends MongooseTimestamps {
|
||||
title: string;
|
||||
slug: string;
|
||||
content: string;
|
||||
status: 'draft' | 'published' | 'archived';
|
||||
metadatas: Metadata[];
|
||||
description: string;
|
||||
map: string;
|
||||
status: MatchStatus;
|
||||
scheduledAt: Date;
|
||||
maxParticipants: number;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
participants: MatchParticipant[];
|
||||
teams: MatchTeam[];
|
||||
result?: MatchResult;
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
schedule: MatchScheduleItem[];
|
||||
}
|
||||
|
||||
export type ArticleDocument = HydratedDocument<Article>;
|
||||
export type MatchDocument = HydratedDocument<Match>;
|
||||
|
||||
const metadataValueDefinition =
|
||||
// ===== Auction (경매) =====
|
||||
export interface AuctionPlayerSnapshot {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
// 표시용 스냅샷(대표 RiotAccount 기준) — RiotAccount에서 복사
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
preferredPositions: Position[];
|
||||
tiers: TierInfo[];
|
||||
masteries: ChampionMasteryEntry[];
|
||||
recentStatsSummary?: RiotRecentStatsSummary;
|
||||
}
|
||||
|
||||
export interface AuctionTeamMember {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
assignedPosition: Position;
|
||||
cost: number;
|
||||
}
|
||||
|
||||
export interface AuctionTeam {
|
||||
side: TeamSide;
|
||||
captainUserId: mongoose.Types.ObjectId;
|
||||
points: number;
|
||||
members: AuctionTeamMember[];
|
||||
}
|
||||
|
||||
export interface AuctionBid {
|
||||
side: TeamSide;
|
||||
amount: number;
|
||||
bidderUserId?: mongoose.Types.ObjectId;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface Auction extends MongooseTimestamps {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
phase: AuctionPhase;
|
||||
teams: AuctionTeam[];
|
||||
order: AuctionPlayerSnapshot[];
|
||||
currentIndex: number;
|
||||
bids: AuctionBid[];
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
maxTimerSeconds: number;
|
||||
initialPoints: number;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
}
|
||||
|
||||
export type AuctionDocument = HydratedDocument<Auction>;
|
||||
|
||||
// ===== Sub-schemas =====
|
||||
const TierInfoSubSchema = new Schema<TierInfo>(
|
||||
{
|
||||
type: mongoose.SchemaTypes.Mixed,
|
||||
required: false, // required: true로 하면 value가 null인 경우 에러 발생
|
||||
default: null,
|
||||
validate: {
|
||||
validator: function (this: Metadata, v: MetadataValue) {
|
||||
if (v === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (this.dataType) {
|
||||
case 'string':
|
||||
return typeof v === 'string';
|
||||
case 'number':
|
||||
return typeof v === 'number';
|
||||
case 'boolean':
|
||||
return typeof v === 'boolean';
|
||||
case 'array':
|
||||
return Array.isArray(v);
|
||||
case 'json':
|
||||
return typeof v === 'object' && !Array.isArray(v);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
},
|
||||
message: function (this: Metadata, props: { value: MetadataValue }) {
|
||||
return `Value "${props.value}" does not match the expected data type "${this.dataType}" for key "${this.key}".`;
|
||||
},
|
||||
},
|
||||
} as mongoose.SchemaDefinitionProperty<MetadataValue>;
|
||||
|
||||
export const MetadataSubSchema = new mongoose.Schema<Metadata>(
|
||||
{
|
||||
key: { type: String, required: true },
|
||||
value: metadataValueDefinition,
|
||||
dataType: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: 'string',
|
||||
enum: ['string', 'number', 'boolean', 'array', 'json'],
|
||||
},
|
||||
isReserved: { type: Boolean, required: false, default: false },
|
||||
},
|
||||
{
|
||||
_id: false,
|
||||
queueType: { type: String, required: true },
|
||||
tier: { type: String, required: true },
|
||||
rank: { type: String, required: true, default: '' },
|
||||
leaguePoints: { type: Number, required: true, default: 0 },
|
||||
wins: { type: Number, required: true, default: 0 },
|
||||
losses: { type: Number, required: true, default: 0 },
|
||||
fetchedAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const TaxonomyChildItemSubSchema = new Schema<TaxonomyChildItem>(
|
||||
const TierHistoryEntrySubSchema = new Schema<TierHistoryEntry>(
|
||||
{
|
||||
title: { type: String, required: true },
|
||||
order: { type: Number, required: true, default: 100 },
|
||||
slug: { type: String }, // slug는 없을 수도 있으므로 required 제외
|
||||
articleId: { type: Schema.Types.ObjectId, ref: 'article' },
|
||||
},
|
||||
{
|
||||
_id: false, // 하위 아이템마다 _id가 생성되는 것을 방지 (선택 사항)
|
||||
season: { type: String, required: true },
|
||||
queueType: { type: String, required: true },
|
||||
tier: { type: String, required: true },
|
||||
rank: { type: String },
|
||||
peakTier: { type: String },
|
||||
peakRank: { type: String },
|
||||
fetchedAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
// **중요: 재귀 참조 설정**
|
||||
// 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다.
|
||||
TaxonomyChildItemSubSchema.add({
|
||||
children: { type: [TaxonomyChildItemSubSchema], default: [] },
|
||||
});
|
||||
|
||||
// 2. 메인 도큐먼트 스키마 (Root)
|
||||
export const TaxonomySchema = new Schema<Taxonomy>(
|
||||
const ChampionMasteryEntrySubSchema = new Schema<ChampionMasteryEntry>(
|
||||
{
|
||||
// items 배열은 위에서 정의한 재귀 스키마를 따름
|
||||
label: { type: String, required: true },
|
||||
items: {
|
||||
type: [TaxonomyChildItemSubSchema],
|
||||
championId: { type: String, required: true },
|
||||
championName: { type: String },
|
||||
level: { type: Number, required: true, default: 0 },
|
||||
points: { type: Number, required: true, default: 0 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const RiotRecentStatsSummarySubSchema = new Schema<RiotRecentStatsSummary>(
|
||||
{
|
||||
games: { type: Number, required: true, default: 0 },
|
||||
wins: { type: Number, required: true, default: 0 },
|
||||
losses: { type: Number, required: true, default: 0 },
|
||||
avgKills: { type: Number, required: true, default: 0 },
|
||||
avgDeaths: { type: Number, required: true, default: 0 },
|
||||
avgAssists: { type: Number, required: true, default: 0 },
|
||||
avgCs: { type: Number, required: true, default: 0 },
|
||||
mostPlayedChampionIds: { type: [String], required: true, default: [] },
|
||||
extras: { type: Schema.Types.Mixed, required: false, default: {} },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const RiotAccountSubSchema = new Schema<RiotAccount>(
|
||||
{
|
||||
puuid: { type: String, required: true },
|
||||
gameName: { type: String, required: true },
|
||||
tagLine: { type: String, required: true },
|
||||
profileIconId: { type: Number, required: true, default: 0 },
|
||||
revisionDate: { type: Number, required: true, default: 0 },
|
||||
summonerLevel: { type: Number, required: true, default: 0 },
|
||||
isPrimary: { type: Boolean, required: true, default: false },
|
||||
|
||||
tiers: { type: [TierInfoSubSchema], required: true, default: [] },
|
||||
tierHistory: {
|
||||
type: [TierHistoryEntrySubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
|
||||
// metadata는 구조가 가변적이므로 Mixed 타입 사용
|
||||
metadatas: {
|
||||
type: [MetadataSubSchema],
|
||||
matchIds: { type: [String], required: true, default: [] },
|
||||
matchIdsFetchedAt: { type: Date },
|
||||
|
||||
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
|
||||
recentStatsFetchedAt: { type: Date },
|
||||
|
||||
championMasteries: {
|
||||
type: [ChampionMasteryEntrySubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
championMasteriesFetchedAt: { type: Date },
|
||||
|
||||
championRecords: {
|
||||
type: Schema.Types.Mixed,
|
||||
required: true,
|
||||
default: () => ({}),
|
||||
},
|
||||
championRecordsFetchedAt: { type: Date },
|
||||
},
|
||||
{
|
||||
_id: false,
|
||||
timestamps: true,
|
||||
},
|
||||
);
|
||||
|
||||
export const UserSchema = new Schema<User>(
|
||||
{
|
||||
kakaoTalkId: { type: String },
|
||||
kakaoTalkNickname: { type: String },
|
||||
discordId: { type: String },
|
||||
discordNickname: { type: String },
|
||||
riotAccounts: {
|
||||
type: [RiotAccountSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
validate: [
|
||||
{
|
||||
validator: function (accounts: RiotAccount[]) {
|
||||
const puuids = accounts.map((a) => a.puuid);
|
||||
return puuids.length === new Set(puuids).size;
|
||||
},
|
||||
message: 'Duplicate Riot puuid within a user is not allowed.',
|
||||
},
|
||||
{
|
||||
validator: function (accounts: RiotAccount[]) {
|
||||
if (accounts.length === 0) return true;
|
||||
const primaryCount = accounts.filter((a) => a.isPrimary).length;
|
||||
return primaryCount === 1;
|
||||
},
|
||||
message:
|
||||
'Exactly one Riot account must be marked as primary when accounts exist.',
|
||||
},
|
||||
],
|
||||
},
|
||||
preferredPositions: {
|
||||
type: [{ type: String, enum: POSITIONS }],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
isActivated: { type: Boolean, required: true, default: true },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'user',
|
||||
},
|
||||
);
|
||||
|
||||
UserSchema.index({ kakaoTalkId: 1 }, { unique: true, sparse: true });
|
||||
UserSchema.index({ discordId: 1 }, { unique: true, sparse: true });
|
||||
UserSchema.index({ 'riotAccounts.puuid': 1 }, { unique: true, sparse: true });
|
||||
|
||||
export const RiotMatchSchema = new Schema<RiotMatch>(
|
||||
{
|
||||
matchId: { type: String, required: true, unique: true },
|
||||
gameCreation: { type: Number, required: true, default: 0 },
|
||||
gameDuration: { type: Number, required: true, default: 0 },
|
||||
gameVersion: { type: String },
|
||||
queueId: { type: Number },
|
||||
participantPuuids: { type: [String], required: true, default: [] },
|
||||
raw: { type: Schema.Types.Mixed, required: true, default: () => ({}) },
|
||||
fetchedAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'riot_match',
|
||||
},
|
||||
);
|
||||
|
||||
RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 });
|
||||
|
||||
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
puuid: { type: String },
|
||||
gameName: { type: String },
|
||||
tagLine: { type: String },
|
||||
profileIconId: { type: Number },
|
||||
preferredPositions: {
|
||||
type: [{ type: String, enum: POSITIONS }],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
joinedAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchTeamMemberSubSchema = new Schema<MatchTeamMember>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
assignedPosition: { type: String, enum: POSITIONS, required: true },
|
||||
cost: { type: Number, required: false },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchTeamSubSchema = new Schema<MatchTeam>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
name: { type: String, required: true },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
members: { type: [MatchTeamMemberSubSchema], required: true, default: [] },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: true },
|
||||
blueScore: { type: Number, required: true, default: 0 },
|
||||
redScore: { type: Number, required: true, default: 0 },
|
||||
mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
riotMatchIds: { type: [String], required: true, default: [] },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchScheduleItemSubSchema = new Schema<MatchScheduleItem>(
|
||||
{
|
||||
time: { type: String, required: true },
|
||||
label: { type: String, required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const MatchSchema = new Schema<Match>(
|
||||
{
|
||||
title: { type: String, required: true },
|
||||
description: { type: String, required: true, default: '' },
|
||||
map: { type: String, required: true, default: '소환사의 협곡' },
|
||||
status: {
|
||||
type: String,
|
||||
enum: MATCH_STATUSES,
|
||||
required: true,
|
||||
default: 'recruiting',
|
||||
},
|
||||
scheduledAt: { type: Date, required: true },
|
||||
maxParticipants: { type: Number, required: true, default: 10 },
|
||||
hostUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
participants: {
|
||||
type: [MatchParticipantSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
validate: {
|
||||
validator: function (parts: MatchParticipant[]) {
|
||||
const ids = parts.map((p) => p.userId.toString());
|
||||
return ids.length === new Set(ids).size;
|
||||
},
|
||||
message: 'Duplicate participants are not allowed.',
|
||||
},
|
||||
},
|
||||
teams: { type: [MatchTeamSubSchema], required: true, default: [] },
|
||||
result: { type: MatchResultSubSchema, required: false },
|
||||
prizes: { type: [String], required: true, default: [] },
|
||||
notices: { type: [String], required: true, default: [] },
|
||||
schedule: {
|
||||
type: [MatchScheduleItemSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true, // createAt, updatedAt 자동 생성
|
||||
collection: 'taxonomy', // 컬렉션 이름 지정
|
||||
timestamps: true,
|
||||
collection: 'match',
|
||||
},
|
||||
);
|
||||
|
||||
TaxonomySchema.index({ label: 1 }, { unique: true });
|
||||
MatchSchema.index({ scheduledAt: -1 });
|
||||
MatchSchema.index({ status: 1, scheduledAt: -1 });
|
||||
MatchSchema.index({ title: 'text', description: 'text' });
|
||||
|
||||
export const ContentSectionEmbeddedTaxonomySubSchema =
|
||||
new Schema<ContentSectionEmbeddedTaxonomy>(
|
||||
{
|
||||
taxonomyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'taxonomy',
|
||||
required: true,
|
||||
},
|
||||
label: { type: String, required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const ContentSectionSubSchema = new Schema<ContentSection>(
|
||||
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
||||
{
|
||||
headline: { type: String, required: true },
|
||||
taxonomies: {
|
||||
type: [ContentSectionEmbeddedTaxonomySubSchema],
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
puuid: { type: String, required: true },
|
||||
gameName: { type: String, required: true },
|
||||
tagLine: { type: String, required: true },
|
||||
profileIconId: { type: Number, required: true, default: 0 },
|
||||
preferredPositions: {
|
||||
type: [{ type: String, enum: POSITIONS }],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
tiers: { type: [TierInfoSubSchema], required: true, default: [] },
|
||||
masteries: {
|
||||
type: [ChampionMasteryEntrySubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const AuctionTeamMemberSubSchema = new Schema<AuctionTeamMember>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
assignedPosition: { type: String, enum: POSITIONS, required: true },
|
||||
cost: { type: Number, required: true, default: 0 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const AuctionTeamSubSchema = new Schema<AuctionTeam>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
points: { type: Number, required: true, default: 0 },
|
||||
members: {
|
||||
type: [AuctionTeamMemberSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
@@ -189,60 +558,61 @@ export const ContentSectionSubSchema = new Schema<ContentSection>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const ContentSchema = new Schema<Content>(
|
||||
const AuctionBidSubSchema = new Schema<AuctionBid>(
|
||||
{
|
||||
key: { type: String, required: true, unique: true },
|
||||
label: { type: String, required: true },
|
||||
sections: {
|
||||
type: [ContentSectionSubSchema],
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'content',
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
amount: { type: Number, required: true },
|
||||
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
timestamp: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const ArticleSchema = new Schema<Article>(
|
||||
export const AuctionSchema = new Schema<Auction>(
|
||||
{
|
||||
title: { type: String, required: true },
|
||||
content: { type: String, required: true },
|
||||
slug: { type: String, required: true, unique: true },
|
||||
status: {
|
||||
type: String,
|
||||
enum: ['draft', 'published', 'archived'],
|
||||
default: 'draft',
|
||||
matchId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'match',
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
metadatas: {
|
||||
type: [MetadataSubSchema],
|
||||
phase: {
|
||||
type: String,
|
||||
enum: AUCTION_PHASES,
|
||||
required: true,
|
||||
default: 'waiting',
|
||||
},
|
||||
teams: { type: [AuctionTeamSubSchema], required: true, default: [] },
|
||||
order: {
|
||||
type: [AuctionPlayerSnapshotSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
validate: {
|
||||
validator: function (metas: Metadata[]) {
|
||||
const keys = metas.map((m) => m.key);
|
||||
return keys.length === new Set(keys).size;
|
||||
},
|
||||
message: 'Duplicate metadata keys are not allowed.',
|
||||
},
|
||||
},
|
||||
currentIndex: { type: Number, required: true, default: 0 },
|
||||
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
|
||||
currentBid: { type: Number, required: true, default: 0 },
|
||||
currentBidder: { type: String, enum: TEAM_SIDES, required: false },
|
||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||
initialPoints: { type: Number, required: true, default: 1000 },
|
||||
startedAt: { type: Date, required: false },
|
||||
completedAt: { type: Date, required: false },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'article',
|
||||
collection: 'auction',
|
||||
},
|
||||
);
|
||||
|
||||
ArticleSchema.index({ title: 'text', content: 'text' });
|
||||
|
||||
export const moeumModelDefinitions: ModelDefinition[] = [
|
||||
{ name: 'taxonomy', schema: TaxonomySchema, schemaName: 'taxonomy' },
|
||||
{ name: 'content', schema: ContentSchema, schemaName: 'content' },
|
||||
{ name: 'article', schema: ArticleSchema, schemaName: 'article' },
|
||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
{ name: 'user', schema: UserSchema, schemaName: 'user' },
|
||||
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
|
||||
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
||||
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
||||
];
|
||||
|
||||
export interface MoeumModelTypes {
|
||||
taxonomy: Taxonomy;
|
||||
content: Content;
|
||||
article: Article;
|
||||
export interface TournamentModelTypes {
|
||||
user: User;
|
||||
riotMatch: RiotMatch;
|
||||
match: Match;
|
||||
auction: Auction;
|
||||
}
|
||||
@@ -18,21 +18,16 @@ import { NatsService } from './nats.service';
|
||||
): Promise<NatsConnection> => {
|
||||
await secretService.ready();
|
||||
|
||||
const [endpoint, user, password, serviceName, cacert] =
|
||||
await Promise.all([
|
||||
secretService.get<string>('NATS_ENDPOINT'),
|
||||
secretService.get<string>('NATS_USER'),
|
||||
secretService.get<string>('NATS_PASS'),
|
||||
secretService.get<string>('SERVICE_NAME'),
|
||||
fs.readFile('internal-service-ca.pem', 'utf8'),
|
||||
]);
|
||||
const [endpoint, user, password, serviceName] = await Promise.all([
|
||||
secretService.get<string>('NATS_ENDPOINT'),
|
||||
secretService.get<string>('NATS_USER'),
|
||||
secretService.get<string>('NATS_PASS'),
|
||||
secretService.get<string>('SERVICE_NAME'),
|
||||
]);
|
||||
|
||||
return connect({
|
||||
name: serviceName,
|
||||
servers: [endpoint],
|
||||
tls: {
|
||||
ca: cacert,
|
||||
},
|
||||
maxReconnectAttempts: -1,
|
||||
reconnectTimeWait: 500,
|
||||
reconnect: true,
|
||||
|
||||
Reference in new issue
Block a user