utils.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import ConnectionString from 'mongodb-connection-string-url';
  2. /**
  3. * Replace the database name in a MongoDB connection URI.
  4. * Uses mongodb-connection-string-url package for robust parsing.
  5. * Supports various URI formats including authentication, replica sets, and query parameters.
  6. *
  7. * @param uri - MongoDB connection URI
  8. * @param newDbName - New database name to use
  9. * @returns Modified URI with the new database name
  10. */
  11. export function replaceMongoDbName(uri: string, newDbName: string): string {
  12. const cs = new ConnectionString(uri);
  13. cs.pathname = `/${newDbName}`;
  14. return cs.href;
  15. }
  16. /**
  17. * Get test database configuration for the current Vitest worker.
  18. * Each worker gets a unique database name to avoid conflicts in parallel execution.
  19. */
  20. export function getTestDbConfig(): {
  21. workerId: string;
  22. dbName: string;
  23. mongoUri: string | null;
  24. } {
  25. // VITEST_WORKER_ID is provided by Vitest (e.g., "1", "2", "3"...)
  26. const workerId = process.env.VITEST_WORKER_ID || '1';
  27. const dbName = `growi_test_${workerId}`;
  28. const mongoUri = process.env.MONGO_URI
  29. ? replaceMongoDbName(process.env.MONGO_URI, dbName)
  30. : null;
  31. return { workerId, dbName, mongoUri };
  32. }