mongoms.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import ConnectionString from 'mongodb-connection-string-url';
  2. import { MongoMemoryServer } from 'mongodb-memory-server-core';
  3. import mongoose from 'mongoose';
  4. import { mongoOptions } from '~/server/util/mongoose-utils';
  5. let mongoServer: MongoMemoryServer | undefined;
  6. /**
  7. * Replace the database name in a MongoDB connection URI.
  8. * Uses mongodb-connection-string-url package for robust parsing.
  9. * Supports various URI formats including authentication, replica sets, and query parameters.
  10. *
  11. * @param uri - MongoDB connection URI
  12. * @param newDbName - New database name to use
  13. * @returns Modified URI with the new database name
  14. */
  15. export function replaceMongoDbName(uri: string, newDbName: string): string {
  16. const cs = new ConnectionString(uri);
  17. cs.pathname = `/${newDbName}`;
  18. return cs.href;
  19. }
  20. beforeAll(async () => {
  21. // Generate unique database name for each test worker to avoid conflicts in parallel execution
  22. // VITEST_WORKER_ID is provided by Vitest (e.g., "1", "2", "3"...)
  23. const workerId = process.env.VITEST_WORKER_ID || '1';
  24. const dbName = `growi_test_${workerId}`;
  25. // Use external MongoDB if MONGO_URI is provided (e.g., in CI with GitHub Actions services)
  26. if (process.env.MONGO_URI) {
  27. const mongoUri = replaceMongoDbName(process.env.MONGO_URI, dbName);
  28. // biome-ignore lint/suspicious/noConsole: Allow logging
  29. console.log(`Using external MongoDB at ${mongoUri} (worker: ${workerId})`);
  30. await mongoose.connect(mongoUri, mongoOptions);
  31. return;
  32. }
  33. // Use MongoMemoryServer for local development
  34. // set debug flag
  35. process.env.MONGOMS_DEBUG = process.env.VITE_MONGOMS_DEBUG;
  36. // set version
  37. mongoServer = await MongoMemoryServer.create({
  38. instance: {
  39. dbName,
  40. },
  41. binary: {
  42. version: process.env.VITE_MONGOMS_VERSION,
  43. downloadDir: 'node_modules/.cache/mongodb-binaries',
  44. },
  45. });
  46. // biome-ignore lint/suspicious/noConsole: Allow logging
  47. console.log(
  48. `MongoMemoryServer is running on ${mongoServer.getUri()} (worker: ${workerId})`,
  49. );
  50. await mongoose.connect(mongoServer.getUri(), mongoOptions);
  51. });
  52. afterAll(async () => {
  53. await mongoose.disconnect();
  54. // Stop MongoMemoryServer if it was created
  55. if (mongoServer) {
  56. await mongoServer.stop();
  57. }
  58. });