fix(api): eliminate unsafe lint warnings #4

Merged
dahyeon merged 1 commits from release/87 into main 2026-07-25 05:23:15 +00:00
12 changed files with 193 additions and 56 deletions

No files matched your search

@@ -2,6 +2,30 @@ import mongoose from 'mongoose';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
describe('AuctionService', () => { describe('AuctionService', () => {
function requireRecord(
value: unknown,
label: string,
): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${label} must be an object.`);
}
return value as Record<string, unknown>;
}
function requireArray(value: unknown, label: string): unknown[] {
if (!Array.isArray(value)) {
throw new Error(`${label} must be an array.`);
}
return value as unknown[];
}
function parseJsonRecord(value: unknown, label: string) {
if (typeof value !== 'string') {
throw new Error(`${label} must be a JSON string.`);
}
return requireRecord(JSON.parse(value) as unknown, label);
}
function createService(models: Record<string, unknown>) { function createService(models: Record<string, unknown>) {
const auctionHistoryModel = { const auctionHistoryModel = {
findOne: jest.fn().mockReturnValue({ findOne: jest.fn().mockReturnValue({
@@ -1007,7 +1031,12 @@ describe('AuctionService', () => {
); );
const transitionInput = const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1]; auctionRedisCommandService.applyTransition.mock.calls[0][1];
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({ expect(
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: expect.objectContaining({ afterAuctionMongoProjection: expect.objectContaining({
phase: 'bidding', phase: 'bidding',
revision: 2, revision: 2,
@@ -1178,17 +1207,40 @@ describe('AuctionService', () => {
const transitionInput = const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1]; auctionRedisCommandService.applyTransition.mock.calls[0][1];
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson); const durabilityPayload = parseJsonRecord(
expect(durabilityPayload.snapshotBefore).toMatchObject({ transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
const snapshotBefore = requireRecord(
durabilityPayload.snapshotBefore,
'snapshotBefore',
);
const snapshotBeforeTeams = requireArray(
snapshotBefore.auctionTeams,
'snapshotBefore.auctionTeams',
);
const snapshotBeforeTeam = requireRecord(
snapshotBeforeTeams[0],
'snapshotBefore.auctionTeams[0]',
);
const afterAuctionMongoProjection = requireRecord(
durabilityPayload.afterAuctionMongoProjection,
'afterAuctionMongoProjection',
);
const projectedTeams = requireArray(
afterAuctionMongoProjection.auctionTeams,
'afterAuctionMongoProjection.auctionTeams',
);
const projectedTeam = requireRecord(
projectedTeams[0],
'afterAuctionMongoProjection.auctionTeams[0]',
);
expect(snapshotBefore).toMatchObject({
phase: 'bidding', phase: 'bidding',
revision: 4, revision: 4,
}); });
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual( expect(snapshotBeforeTeam.members).toEqual([]);
[], expect(projectedTeam.members).toEqual([
);
expect(
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
).toEqual([
expect.objectContaining({ expect.objectContaining({
memberAcquisitionBidPointAmount: 120, memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(), userId: playerUserId.toString(),
@@ -1396,7 +1448,12 @@ describe('AuctionService', () => {
}); });
const [, transitionInput] = const [, transitionInput] =
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? []; auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({ expect(
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: { afterAuctionMongoProjection: {
matchSideEffectStatus: 'pending', matchSideEffectStatus: 'pending',
phase: 'complete', phase: 'complete',
@@ -2567,7 +2624,10 @@ describe('AuctionService', () => {
durationSeconds: 30, durationSeconds: 30,
mode: 'set-relative', mode: 'set-relative',
}); });
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson); const durabilityPayload = parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
expect(durabilityPayload).toMatchObject({ expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo', auctionActionType: 'undo',
historyMutation: { historyMutation: {
@@ -429,8 +429,14 @@ export function applyCompetitionDomainInvariantIndexes(
} }
} }
export type CompetitionModelName =
| 'competition'
| 'competitionFact'
| 'competitionOutbox'
| 'tournamentCodeAssignment';
export const competitionModelDefinitions: Array<{ export const competitionModelDefinitions: Array<{
name: string; name: CompetitionModelName;
schema: mongoose.Schema; schema: mongoose.Schema;
schemaName: string; schemaName: string;
}> = [ }> = [
@@ -1,4 +1,8 @@
import { projectCompetition } from './competition-projector'; import { projectCompetition } from './competition-projector';
import {
CompetitionDomainError,
type CompetitionDomainErrorCode,
} from './domain-error';
import { generateSeriesGraph } from './series-graph'; import { generateSeriesGraph } from './series-graph';
describe('projectCompetition', () => { describe('projectCompetition', () => {
@@ -323,7 +327,8 @@ describe('projectCompetition', () => {
'team-1', 'team-1',
); );
expect(() => expectCompetitionDomainError(
() =>
projectCompetition({ projectCompetition({
competitionId, competitionId,
revision: 1, revision: 1,
@@ -333,10 +338,7 @@ describe('projectCompetition', () => {
seriesGraph, seriesGraph,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }], facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
}), }),
).toThrow( 'GAME_SERIES_MISMATCH',
expect.objectContaining({
code: 'GAME_SERIES_MISMATCH',
}),
); );
}); });
@@ -356,7 +358,8 @@ describe('projectCompetition', () => {
'team-1', 'team-1',
); );
expect(() => expectCompetitionDomainError(
() =>
projectCompetition({ projectCompetition({
competitionId, competitionId,
revision: 1, revision: 1,
@@ -366,10 +369,7 @@ describe('projectCompetition', () => {
seriesGraph, seriesGraph,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }], facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
}), }),
).toThrow( 'GAME_SLOT_INVALID',
expect.objectContaining({
code: 'GAME_SLOT_INVALID',
}),
); );
}); });
@@ -382,7 +382,8 @@ describe('projectCompetition', () => {
}; };
const seriesGraph = generateSeriesGraph({ competitionId, teams, format }); const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
expect(() => expectCompetitionDomainError(
() =>
projectCompetition({ projectCompetition({
competitionId, competitionId,
revision: 1, revision: 1,
@@ -408,10 +409,7 @@ describe('projectCompetition', () => {
}, },
], ],
}), }),
).toThrow( 'ADJUDICATION_INVALID',
expect.objectContaining({
code: 'ADJUDICATION_INVALID',
}),
); );
}); });
@@ -617,3 +615,23 @@ interface GameSlotLike {
id: string; id: string;
ordinal: number; ordinal: number;
} }
function expectCompetitionDomainError(
action: () => unknown,
expectedCode: CompetitionDomainErrorCode,
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionDomainError);
if (!(thrown instanceof CompetitionDomainError)) {
throw new Error(
`Expected CompetitionDomainError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
@@ -1,6 +1,7 @@
import { import {
assertReversalPreview, assertReversalPreview,
buildReversalFacts, buildReversalFacts,
CompetitionReversalError,
previewSeriesReversal, previewSeriesReversal,
} from './competition-reversal'; } from './competition-reversal';
@@ -19,7 +20,8 @@ describe('Competition reversal planning', () => {
]; ];
it('rejects strict reversal when a descendant has result activity', () => { it('rejects strict reversal when a descendant has result activity', () => {
expect(() => expectCompetitionReversalError(
() =>
previewSeriesReversal({ previewSeriesReversal({
competitionId: 'competition-1', competitionId: 'competition-1',
revision: 2, revision: 2,
@@ -29,8 +31,7 @@ describe('Competition reversal planning', () => {
facts, facts,
assignments, assignments,
}), }),
).toThrow( 'REVERSAL_DESCENDANT_ACTIVITY',
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
); );
}); });
@@ -105,7 +106,8 @@ describe('Competition reversal planning', () => {
assignments, assignments,
}); });
expect(() => expectCompetitionReversalError(
() =>
assertReversalPreview( assertReversalPreview(
{ {
competitionId: 'competition-1', competitionId: 'competition-1',
@@ -118,7 +120,8 @@ describe('Competition reversal planning', () => {
}, },
preview.impactHash, preview.impactHash,
), ),
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' })); 'REVERSAL_PREVIEW_STALE',
);
}); });
it('emits one append-only reversal fact for every active result fact', () => { it('emits one append-only reversal fact for every active result fact', () => {
@@ -160,6 +163,26 @@ describe('Competition reversal planning', () => {
}); });
}); });
function expectCompetitionReversalError(
action: () => unknown,
expectedCode: CompetitionReversalError['code'],
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionReversalError);
if (!(thrown instanceof CompetitionReversalError)) {
throw new Error(
`Expected CompetitionReversalError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
function series(id: string, sources: Array<Record<string, unknown>>) { function series(id: string, sources: Array<Record<string, unknown>>) {
return { return {
id, id,
@@ -2,7 +2,10 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin'; import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
import { SecretService } from '../secret/secret.service'; import { SecretService } from '../secret/secret.service';
import { tournamentModelDefinitions, TournamentModelTypes } from './schema'; import {
tournamentModelDefinitions,
type TournamentModelTypes,
} from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string { export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus'; if (nodeEnv === 'prod') return 'lolympus';
@@ -42,7 +45,8 @@ export class ConnectionService implements OnModuleInit {
private connectionPromise: Promise<mongoose.Connection> | null = null; private connectionPromise: Promise<mongoose.Connection> | null = null;
constructor(private readonly secretService: SecretService) {} constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<string, mongoose.Model<any>> | null = null; private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null =
null;
public async getConnection(): Promise<mongoose.Connection> { public async getConnection(): Promise<mongoose.Connection> {
if ( if (
@@ -89,14 +93,18 @@ export class ConnectionService implements OnModuleInit {
modelKey: K, modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> { ): Promise<mongoose.Model<TournamentModelTypes[K]>> {
const connection = await this.getConnection(); const connection = await this.getConnection();
if (this.tournamentModels) if (this.tournamentModels) {
return this.tournamentModels.get(modelKey) as mongoose.Model< return this.requireTournamentModel(this.tournamentModels, modelKey);
TournamentModelTypes[K] }
>;
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>(); const models = new Map<keyof TournamentModelTypes, unknown>();
tournamentModelDefinitions.forEach((modelDefinition) => { tournamentModelDefinitions.forEach((modelDefinition) => {
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
throw new Error(
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
);
}
applyMongoosePerformancePlugin(modelDefinition.schema); applyMongoosePerformancePlugin(modelDefinition.schema);
// 이미 생성된 경우 컴파일 스킵. // 이미 생성된 경우 컴파일 스킵.
if ( if (
@@ -106,14 +114,14 @@ export class ConnectionService implements OnModuleInit {
) )
) { ) {
models.set( models.set(
modelDefinition.name as K, modelDefinition.name,
connection.models[modelDefinition.name], connection.models[modelDefinition.name],
); );
return; return;
} else { } else {
models.set( models.set(
modelDefinition.name as K, modelDefinition.name,
connection.model<TournamentModelTypes[K]>( connection.model(
modelDefinition.name, modelDefinition.name,
modelDefinition.schema, modelDefinition.schema,
modelDefinition.schemaName, modelDefinition.schemaName,
@@ -123,7 +131,18 @@ export class ConnectionService implements OnModuleInit {
}); });
this.tournamentModels = models; this.tournamentModels = models;
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>; return this.requireTournamentModel(models, modelKey);
}
private requireTournamentModel<K extends keyof TournamentModelTypes>(
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
modelKey: K,
): mongoose.Model<TournamentModelTypes[K]> {
const model = models.get(modelKey);
if (model === undefined) {
throw new Error(`Mongoose model ${modelKey} is not registered.`);
}
return model as mongoose.Model<TournamentModelTypes[K]>;
} }
public async createSession( public async createSession(
@@ -253,9 +253,7 @@ function migrateResult(result: Record<string, unknown>) {
seriesResults.length > 0 ? seriesResults : buildSeries(games); seriesResults.length > 0 ? seriesResults : buildSeries(games);
if (typeof migrated.winnerTeamIndex !== 'number') { if (typeof migrated.winnerTeamIndex !== 'number') {
const migratedSeriesResults = Array.isArray(migrated.seriesResults) const migratedSeriesResults = asArray(migrated.seriesResults);
? migrated.seriesResults
: [];
migrated.winnerTeamIndex = migrated.winnerTeamIndex =
resolveWinnerTeamIndex(migratedSeriesResults) ?? resolveWinnerTeamIndex(migratedSeriesResults) ??
(isSide(migrated.winnerSide) (isSide(migrated.winnerSide)
@@ -117,7 +117,9 @@ function createDb(params: {
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean { function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
const clauses = filter.$or; const clauses = filter.$or;
if (Array.isArray(clauses)) { if (Array.isArray(clauses)) {
return clauses.some((clause) => matchesFilter(doc, clause)); return (clauses as unknown[]).some(
(clause) => isRecord(clause) && matchesFilter(doc, clause),
);
} }
return Object.entries(filter).every(([key, value]) => { return Object.entries(filter).every(([key, value]) => {
@@ -11,7 +11,11 @@ import {
} from '../../../double-elimination/double-elimination.util'; } from '../../../double-elimination/double-elimination.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants'; import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
import { ConnectionService } from '../connection.service'; import { ConnectionService } from '../connection.service';
import type { MatchDocument, TournamentCodeDocument } from '../schema'; import type {
MatchDocument,
TournamentCode,
TournamentCodeDocument,
} from '../schema';
import { SecretModule } from '../../secret/secret.module'; import { SecretModule } from '../../secret/secret.module';
interface CliOptions { interface CliOptions {
@@ -334,7 +338,7 @@ function printPlan(plan: MatchRepairPlan) {
async function applyPlan( async function applyPlan(
match: MatchDocument, match: MatchDocument,
plan: MatchRepairPlan, plan: MatchRepairPlan,
TournamentCodeModel: mongoose.Model<any>, TournamentCodeModel: mongoose.Model<TournamentCode>,
session: mongoose.ClientSession, session: mongoose.ClientSession,
) { ) {
if (plan.skippedReason) return; if (plan.skippedReason) return;
@@ -2485,7 +2485,9 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 }); MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 }); MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: ModelDefinition[] = [ export const tournamentModelDefinitions: Array<
ModelDefinition & { name: keyof TournamentModelTypes }
> = [
...competitionModelDefinitions, ...competitionModelDefinitions,
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
+1 -1
View File
@@ -1,5 +1,5 @@
export interface ModelDefinition { export interface ModelDefinition {
name: string; name: string;
schema: mongoose.Schema<any>; schema: unknown;
schemaName?: string; schemaName?: string;
} }
@@ -34,10 +34,13 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
[PERFORMANCE_PLUGIN_APPLIED]?: boolean; [PERFORMANCE_PLUGIN_APPLIED]?: boolean;
}; };
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
const markedSchema = schema as SchemaWithPerformanceMarker; if (!(schemaValue instanceof mongoose.Schema)) {
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return; throw new TypeError('Mongoose performance plugin requires a Schema.');
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true; }
const schema = schemaValue as SchemaWithPerformanceMarker;
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
schema.pre(QUERY_OPERATION_REGEX, function () { schema.pre(QUERY_OPERATION_REGEX, function () {
const query = this as QueryWithPerformanceState; const query = this as QueryWithPerformanceState;
@@ -5,7 +5,9 @@ describe('MatchService', () => {
function createServiceWithCreateModels() { function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = []; const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = { const MatchModel = {
create: jest.fn().mockImplementation(async (payload) => { create: jest
.fn()
.mockImplementation(async (payload: Record<string, unknown>) => {
createdPayloads.push(payload); createdPayloads.push(payload);
return payload; return payload;
}), }),