import 'reflect-metadata'; import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import { readFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import { ConnectionService, resolveMongoDbName } from '../connection.service'; import { SecretModule } from '../../secret/secret.module'; import { migrateTeamIndex } from './20260502-team-index'; interface CliOptions { dryRun: boolean; limit?: number; nodeEnv: string; } @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: [ resolve(__dirname, '../../../../../../project.env'), resolve(process.cwd(), '../project.env'), resolve(process.cwd(), 'apps/project.env'), resolve(process.cwd(), 'project.env'), ], }), SecretModule, ], providers: [ConnectionService], }) class MigrationModule {} async function loadMachineEnvFile() { const homeDir = process.env.HOME ?? process.env.USERPROFILE; if (!homeDir) return; const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); try { const file = await readFile(machineEnvFile, 'utf8'); for (const rawLine of file.split(/\r?\n/)) { const line = rawLine.trim(); if (!line || line.startsWith('#')) continue; const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); if (!matched) continue; const [, key, rawValue] = matched; process.env[key] = rawValue.replace(/^["']|["']$/g, ''); } } catch { // 로컬 machine env 파일이 없으면 그냥 지나간다. } } function parseArgs(argv: string[]): CliOptions { let dryRun = true; let limit: number | undefined; let nodeEnv = process.env.NODE_ENV ?? 'dev'; for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; if (arg === '--apply') { dryRun = false; continue; } if (arg === '--dry-run') { dryRun = true; continue; } if (arg === '--env') { const value = argv[index + 1]; if (!value) throw new Error('--env requires dev, test, or prod.'); nodeEnv = value; index += 1; continue; } if (arg.startsWith('--env=')) { nodeEnv = arg.slice('--env='.length); continue; } if (arg === '--limit') { const value = Number(argv[index + 1]); if (!Number.isInteger(value) || value < 1) { throw new Error('--limit requires a positive integer.'); } limit = value; index += 1; continue; } if (arg.startsWith('--limit=')) { const value = Number(arg.slice('--limit='.length)); if (!Number.isInteger(value) || value < 1) { throw new Error('--limit requires a positive integer.'); } limit = value; continue; } if (arg === '--help' || arg === '-h') { printHelp(); process.exit(0); } throw new Error(`Unknown argument: ${arg}`); } if (!['dev', 'test', 'prod'].includes(nodeEnv)) { throw new Error('--env must be dev, test, or prod.'); } return { dryRun, limit, nodeEnv }; } function printHelp() { console.log(`Usage: pnpm --filter api exec ts-node src/modules/global/database/migrations/run-team-index.ts [--dry-run] pnpm --filter api exec ts-node src/modules/global/database/migrations/run-team-index.ts --apply Options: --dry-run Print affected counts without writing. Default. --apply Apply updates to MongoDB. --env dev | test | prod. Default: NODE_ENV or dev. --limit Only scan first n documents per collection. `); } async function main() { const options = parseArgs(process.argv.slice(2)); process.env.NODE_ENV = options.nodeEnv; await loadMachineEnvFile(); const app = await NestFactory.createApplicationContext(MigrationModule, { logger: options.dryRun ? ['log', 'warn', 'error'] : ['log', 'warn', 'error'], }); try { const connectionService = app.get(ConnectionService); const connection = await connectionService.getConnection(); if (!connection.db) { throw new Error('MongoDB connection has no db handle.'); } const dbName = resolveMongoDbName(options.nodeEnv); console.log( `[team-index migration] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${dbName}`, ); const stats = await migrateTeamIndex(connection.db as Parameters[0], { dryRun: options.dryRun, limit: options.limit, }); console.table(stats); if (options.dryRun) { console.log('No writes were made. Re-run with --apply to update documents.'); } else { console.log('Migration applied.'); } } finally { await app.close(); } } void main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; });