Разбить API на слои, комментарии на русском
Skeleton contracts / contracts (pull_request) Canceled after 0s

routes -> http/auth -> repositories -> infra; поведение не изменилось, smoke, persistence и тесты уровня 4 перепрогнаны.
This commit is contained in:
celis
2026-10-29 22:25:01 +03:00
parent cac37bddec
commit b79be9b0eb
35 changed files with 729 additions and 486 deletions
+28 -39
View File
@@ -1,49 +1,38 @@
// Apply versioned SQL migrations once each: node dist/migrate.js
// Применяет версионируемые SQL-миграции из migrations/ по одному разу: node dist/migrate.js
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import pg from 'pg';
/** NAME_FILE (Docker secret path) wins over NAME; secret values are never logged. */
export function setting(name: string, fallback?: string): string {
const file = process.env[name + '_FILE'];
if (file) return readFileSync(file, 'utf8').trim();
const value = process.env[name] ?? fallback;
if (value === undefined) throw new Error('missing setting ' + name);
return value;
}
import { setting } from './config.js';
const dir = process.env.MIGRATIONS_DIR ?? fileURLToPath(new URL('../migrations', import.meta.url));
async function migrate() {
const client = new pg.Client({ connectionString: setting('DATABASE_URL'), connectionTimeoutMillis: 5000 });
await client.connect();
try {
// one runner at a time; a concurrent runner waits and then skips what is applied
await client.query('SELECT pg_advisory_lock(20262)');
await client.query('CREATE TABLE IF NOT EXISTS schema_migrations '
+ '(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())');
const done = new Set((await client.query('SELECT version FROM schema_migrations')).rows.map((r) => r.version));
for (const file of readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
const version = file.slice(0, -4);
if (done.has(version)) {
console.log('skip', version);
continue;
}
await client.query('BEGIN'); // DDL is transactional in PostgreSQL: all or nothing
try {
await client.query(readFileSync(join(dir, file), 'utf8'));
await client.query('INSERT INTO schema_migrations (version) VALUES ($1)', [version]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
}
console.log('applied', version);
const client = new pg.Client({ connectionString: setting('DATABASE_URL'), connectionTimeoutMillis: 5000 });
await client.connect();
try {
// advisory lock: два одновременных запуска не применят миграцию дважды — второй подождёт и пропустит её
await client.query('SELECT pg_advisory_lock(20262)');
await client.query('CREATE TABLE IF NOT EXISTS schema_migrations '
+ '(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())');
const done = new Set((await client.query('SELECT version FROM schema_migrations')).rows.map((r) => r.version));
for (const file of readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
const version = file.slice(0, -4);
if (done.has(version)) {
console.log('skip', version);
continue;
}
} finally {
await client.end();
// DDL в PostgreSQL транзакционен: миграция и запись о ней применяются целиком или никак
await client.query('BEGIN');
try {
await client.query(readFileSync(join(dir, file), 'utf8'));
await client.query('INSERT INTO schema_migrations (version) VALUES ($1)', [version]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
}
console.log('applied', version);
}
} finally {
await client.end();
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await migrate();