utils.ts 1.4 KB

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