mongoms.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. 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. // Use unique database name per worker to avoid conflicts in parallel execution
  40. dbName,
  41. },
  42. binary: {
  43. version: process.env.VITE_MONGOMS_VERSION,
  44. downloadDir: 'node_modules/.cache/mongodb-binaries',
  45. },
  46. });
  47. // biome-ignore lint/suspicious/noConsole: Allow logging
  48. console.log(`MongoMemoryServer is running on ${mongoServer.getUri()} (worker: ${workerId})`);
  49. await mongoose.connect(mongoServer.getUri(), mongoOptions);
  50. });
  51. afterAll(async () => {
  52. await mongoose.disconnect();
  53. // Stop MongoMemoryServer if it was created
  54. if (mongoServer) {
  55. await mongoServer.stop();
  56. }
  57. });