feat(api): implement tournament and auction system models

Introduces new database models and service integrations for managing tournament-related data including users, matches, and auction processes. Updates NATS connection to remove unused TLS configuration.
This commit is contained in:
dahyeon authored and 박다현 (Dahyeon Park) committed 2026-04-15 17:23:54 +09:00
1 parent 909845a1df
commit 35b7db5344
3 files changed
+574 -207

No files matched your search

@@ -1,14 +1,17 @@
import { Injectable, Scope, OnModuleInit } from '@nestjs/common'; import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { SecretService } from '../secret/secret.service'; import { SecretService } from '../secret/secret.service';
import { moeumModelDefinitions, MoeumModelTypes } from './schema'; import {
tournamentModelDefinitions,
TournamentModelTypes,
} from './schema';
@Injectable({ scope: Scope.DEFAULT }) @Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit { export class ConnectionService implements OnModuleInit {
private connection: mongoose.Connection | null = null; private connection: mongoose.Connection | null = null;
constructor(private readonly secretService: SecretService) {} 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> { public async getConnection(): Promise<mongoose.Connection> {
if (this.connection !== null && this.connection.readyState === 1) { if (this.connection !== null && this.connection.readyState === 1) {
@@ -20,7 +23,7 @@ export class ConnectionService implements OnModuleInit {
); );
const defaultConnection = await mongoose const defaultConnection = await mongoose
.createConnection(connectionString, { .createConnection(connectionString, {
dbName: 'moeum', dbName: 'tournament',
minPoolSize: 10, minPoolSize: 10,
maxPoolSize: 20, maxPoolSize: 20,
}) })
@@ -31,19 +34,18 @@ export class ConnectionService implements OnModuleInit {
return this.connection; return this.connection;
} }
public async getMoeumModels<K extends keyof MoeumModelTypes>( public async getModel<K extends keyof TournamentModelTypes>(
modelKey: K, modelKey: K,
): Promise<mongoose.Model<MoeumModelTypes[K]>> { ): Promise<mongoose.Model<TournamentModelTypes[K]>> {
if (this.moeumModels) if (this.tournamentModels)
return this.moeumModels.get(modelKey) as mongoose.Model< return this.tournamentModels.get(modelKey) as mongoose.Model<
MoeumModelTypes[K] TournamentModelTypes[K]
>; >;
const moeumModels = new Map<K, mongoose.Model<MoeumModelTypes[K]>>(); const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
// const connection = await this.getTenantConnection(tenantId);
const connection = await this.getConnection(); const connection = await this.getConnection();
moeumModelDefinitions.forEach((modelDefinition) => { tournamentModelDefinitions.forEach((modelDefinition) => {
// 이미 생성된 경우 컴파일 스킵. // 이미 생성된 경우 컴파일 스킵.
if ( if (
Object.prototype.hasOwnProperty.call( Object.prototype.hasOwnProperty.call(
@@ -51,15 +53,15 @@ export class ConnectionService implements OnModuleInit {
modelDefinition.name, modelDefinition.name,
) )
) { ) {
moeumModels.set( models.set(
modelDefinition.name as K, modelDefinition.name as K,
connection.models[modelDefinition.name], connection.models[modelDefinition.name],
); );
return; return;
} else { } else {
moeumModels.set( models.set(
modelDefinition.name as K, modelDefinition.name as K,
connection.model<MoeumModelTypes[K]>( connection.model<TournamentModelTypes[K]>(
modelDefinition.name, modelDefinition.name,
modelDefinition.schema, modelDefinition.schema,
modelDefinition.schemaName, modelDefinition.schemaName,
@@ -68,8 +70,8 @@ export class ConnectionService implements OnModuleInit {
} }
}); });
this.moeumModels = moeumModels; this.tournamentModels = models;
return moeumModels.get(modelKey) as mongoose.Model<MoeumModelTypes[K]>; return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
} }
public async createSession( public async createSession(
+550 -180
View File
@@ -1,187 +1,556 @@
import mongoose, { Schema, HydratedDocument } from 'mongoose'; import mongoose, { Schema, HydratedDocument } from 'mongoose';
import { ModelDefinition } from './types'; import { ModelDefinition } from './types';
export type MetadataDataType = export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
| 'string' export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
| 'number'
| 'boolean'
| 'array'
| 'json';
export type MetadataValue = export type MatchStatus =
| string | 'recruiting'
| number | 'team-built'
| boolean | 'in-progress'
| unknown[] | 'finished';
| Record<string, unknown> export const MATCH_STATUSES: MatchStatus[] = [
| null; '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 { export interface MongooseTimestamps {
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
} }
export interface Metadata { // ===== Tier =====
key: string; export interface TierInfo {
value: MetadataValue; queueType: string; // RANKED_SOLO_5x5, RANKED_FLEX_SR 등
dataType: MetadataDataType; tier: string; // IRON, BRONZE, ..., CHALLENGER
isReserved: boolean; rank: string; // I | II | III | IV
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: Date; // Riot API로부터 조회된 시각
} }
export interface TaxonomyChildItem { export interface TierHistoryEntry {
title: string; season: string; // e.g., 'S13', 'S14'
order: number; queueType: string;
articleId?: mongoose.Types.ObjectId; tier: string;
slug?: string; //article document의 slug 참조 (임베딩) rank?: string;
children?: TaxonomyChildItem[]; 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; label: string;
items: TaxonomyChildItem[];
metadatas: Metadata[];
} }
export type TaxonomyDocument = HydratedDocument<Taxonomy>; export interface Match extends MongooseTimestamps {
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 {
title: string; title: string;
slug: string; description: string;
content: string; map: string;
status: 'draft' | 'published' | 'archived'; status: MatchStatus;
metadatas: Metadata[]; 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, queueType: { type: String, required: true },
required: false, // required: true로 하면 value가 null인 경우 에러 발생 tier: { type: String, required: true },
default: null, rank: { type: String, required: true, default: '' },
validate: { leaguePoints: { type: Number, required: true, default: 0 },
validator: function (this: Metadata, v: MetadataValue) { wins: { type: Number, required: true, default: 0 },
if (v === null) { losses: { type: Number, required: true, default: 0 },
return true; fetchedAt: { type: Date, required: true, default: Date.now },
}
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,
}, },
{ _id: false },
); );
export const TaxonomyChildItemSubSchema = new Schema<TaxonomyChildItem>( const TierHistoryEntrySubSchema = new Schema<TierHistoryEntry>(
{ {
title: { type: String, required: true }, season: { type: String, required: true },
order: { type: Number, required: true, default: 100 }, queueType: { type: String, required: true },
slug: { type: String }, // slug는 없을 수도 있으므로 required 제외 tier: { type: String, required: true },
articleId: { type: Schema.Types.ObjectId, ref: 'article' }, rank: { type: String },
}, peakTier: { type: String },
{ peakRank: { type: String },
_id: false, // 하위 아이템마다 _id가 생성되는 것을 방지 (선택 사항) fetchedAt: { type: Date, required: true, default: Date.now },
}, },
{ _id: false },
); );
// **중요: 재귀 참조 설정** const ChampionMasteryEntrySubSchema = new Schema<ChampionMasteryEntry>(
// 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다.
TaxonomyChildItemSubSchema.add({
children: { type: [TaxonomyChildItemSubSchema], default: [] },
});
// 2. 메인 도큐먼트 스키마 (Root)
export const TaxonomySchema = new Schema<Taxonomy>(
{ {
// items 배열은 위에서 정의한 재귀 스키마를 따름 championId: { type: String, required: true },
label: { type: String, required: true }, championName: { type: String },
items: { level: { type: Number, required: true, default: 0 },
type: [TaxonomyChildItemSubSchema], 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: [], default: [],
}, },
// metadata는 구조가 가변적이므로 Mixed 타입 사용 matchIds: { type: [String], required: true, default: [] },
metadatas: { matchIdsFetchedAt: { type: Date },
type: [MetadataSubSchema],
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, required: true,
default: [], default: [],
}, },
}, },
{ {
timestamps: true, // createAt, updatedAt 자동 생성 timestamps: true,
collection: 'taxonomy', // 컬렉션 이름 지정 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 = const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
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>(
{ {
headline: { type: String, required: true }, userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
taxonomies: { puuid: { type: String, required: true },
type: [ContentSectionEmbeddedTaxonomySubSchema], 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, required: true,
default: [], default: [],
}, },
@@ -189,60 +558,61 @@ export const ContentSectionSubSchema = new Schema<ContentSection>(
{ _id: false }, { _id: false },
); );
export const ContentSchema = new Schema<Content>( const AuctionBidSubSchema = new Schema<AuctionBid>(
{ {
key: { type: String, required: true, unique: true }, side: { type: String, enum: TEAM_SIDES, required: true },
label: { type: String, required: true }, amount: { type: Number, required: true },
sections: { bidderUserId: { type: Schema.Types.ObjectId, ref: 'user' },
type: [ContentSectionSubSchema], timestamp: { type: Date, required: true, default: Date.now },
default: [],
},
},
{
timestamps: true,
collection: 'content',
}, },
{ _id: false },
); );
export const ArticleSchema = new Schema<Article>( export const AuctionSchema = new Schema<Auction>(
{ {
title: { type: String, required: true }, matchId: {
content: { type: String, required: true }, type: Schema.Types.ObjectId,
slug: { type: String, required: true, unique: true }, ref: 'match',
status: { required: true,
type: String, unique: true,
enum: ['draft', 'published', 'archived'],
default: 'draft',
}, },
metadatas: { phase: {
type: [MetadataSubSchema], type: String,
enum: AUCTION_PHASES,
required: true,
default: 'waiting',
},
teams: { type: [AuctionTeamSubSchema], required: true, default: [] },
order: {
type: [AuctionPlayerSnapshotSubSchema],
required: true, required: true,
default: [], 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, timestamps: true,
collection: 'article', collection: 'auction',
}, },
); );
ArticleSchema.index({ title: 'text', content: 'text' }); export const tournamentModelDefinitions: ModelDefinition[] = [
{ name: 'user', schema: UserSchema, schemaName: 'user' },
export const moeumModelDefinitions: ModelDefinition[] = [ { name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
{ name: 'taxonomy', schema: TaxonomySchema, schemaName: 'taxonomy' }, { name: 'match', schema: MatchSchema, schemaName: 'match' },
{ name: 'content', schema: ContentSchema, schemaName: 'content' }, { name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
{ name: 'article', schema: ArticleSchema, schemaName: 'article' },
]; ];
export interface MoeumModelTypes { export interface TournamentModelTypes {
taxonomy: Taxonomy; user: User;
content: Content; riotMatch: RiotMatch;
article: Article; match: Match;
auction: Auction;
} }
@@ -18,21 +18,16 @@ import { NatsService } from './nats.service';
): Promise<NatsConnection> => { ): Promise<NatsConnection> => {
await secretService.ready(); await secretService.ready();
const [endpoint, user, password, serviceName, cacert] = const [endpoint, user, password, serviceName] = await Promise.all([
await Promise.all([ secretService.get<string>('NATS_ENDPOINT'),
secretService.get<string>('NATS_ENDPOINT'), secretService.get<string>('NATS_USER'),
secretService.get<string>('NATS_USER'), secretService.get<string>('NATS_PASS'),
secretService.get<string>('NATS_PASS'), secretService.get<string>('SERVICE_NAME'),
secretService.get<string>('SERVICE_NAME'), ]);
fs.readFile('internal-service-ca.pem', 'utf8'),
]);
return connect({ return connect({
name: serviceName, name: serviceName,
servers: [endpoint], servers: [endpoint],
tls: {
ca: cacert,
},
maxReconnectAttempts: -1, maxReconnectAttempts: -1,
reconnectTimeWait: 500, reconnectTimeWait: 500,
reconnect: true, reconnect: true,