migrate-mongo.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import path from 'node:path';
  2. import { beforeAll } from 'vitest';
  3. import { mongoOptions } from '~/server/util/mongoose-utils';
  4. import { getTestDbConfig } from './mongo';
  5. // Track if migrations have been run for this worker
  6. let migrationsRun = false;
  7. /**
  8. * Run database migrations using migrate-mongo API.
  9. * This is necessary when using external MongoDB in CI to ensure each worker's
  10. * database has the required schema and indexes.
  11. */
  12. async function runMigrations(mongoUri: string, dbName: string): Promise<void> {
  13. // Dynamic import for migrate-mongo (CommonJS module)
  14. // @ts-expect-error migrate-mongo does not have type definitions
  15. const { config, up, database } = await import('migrate-mongo');
  16. // Set custom config for this worker's database
  17. config.set({
  18. mongodb: {
  19. url: mongoUri,
  20. databaseName: dbName,
  21. options: mongoOptions,
  22. },
  23. // Use process.cwd() for reliability in Vitest environment
  24. // In CI, tests run from apps/app directory
  25. migrationsDir: path.resolve(process.cwd(), 'src/migrations'),
  26. changelogCollectionName: 'migrations',
  27. });
  28. // Connect and run migrations
  29. const { db, client } = await database.connect();
  30. try {
  31. const migrated = await up(db, client);
  32. if (migrated.length > 0) {
  33. // biome-ignore lint/suspicious/noConsole: Allow logging
  34. console.log(`Migrations applied: ${migrated.join(', ')}`);
  35. }
  36. } finally {
  37. await client.close();
  38. }
  39. }
  40. beforeAll(async () => {
  41. // Skip if already run (setupFiles run per test file, but we only need to migrate once per worker)
  42. if (migrationsRun) {
  43. return;
  44. }
  45. const { dbName, mongoUri } = getTestDbConfig();
  46. // Only run migrations when using external MongoDB (CI environment)
  47. if (mongoUri == null) {
  48. return;
  49. }
  50. // biome-ignore lint/suspicious/noConsole: Allow logging
  51. console.log(`Running migrations for ${dbName}...`);
  52. await runMigrations(mongoUri, dbName);
  53. migrationsRun = true;
  54. });