Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed bugs to ensure proper flow of prompts and remove repetitive prompts #2845

Merged
merged 17 commits into from
Jan 15, 2025

Conversation

Aad1tya27
Copy link

@Aad1tya27 Aad1tya27 commented Jan 10, 2025

What kind of change does this PR introduce?
Bug in setup.ts

Issue Number:

Fixes #2829

Snapshots/Videos:
image

If relevant, did you update the documentation?
No

Does this PR introduce a breaking change?
Yeah, there was a breaking change related to __dirname, which was caused due CommonJS to ES.

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?

Summary by CodeRabbit

  • Chores
    • Enhanced error handling and clarity in the setup process.
    • Improved data importation logic with new functions for Docker and non-Docker scenarios.
    • Updated path resolution mechanisms for transaction logs.
    • Refined database connection logic with retry capabilities.
  • Tests
    • Introduced a new test suite for validating the transaction log path input functionality.
    • Added comprehensive tests for data importation with and without Docker, covering various user scenarios and error conditions.

Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request modifies the setup.ts file to enhance the setup process for the Talawa API, focusing on imports, error handling, logging, and data management. Key changes include updating import statements for better path resolution, improving error handling by throwing descriptive messages, refining the logic for data management, and simplifying user prompts. Additionally, new tests for the askForTransactionLogPath function have been introduced to ensure correct handling of user input.

Changes

File Change Summary
setup.ts - Updated imports to include dirname and fileURLToPath
- Improved error handling in transactionLogPath, askForTransactionLogPath, and wipeExistingData functions
- Modified transaction log path resolution
- Simplified data management and import logic with new functions dataImportWithoutDocker and dataImportWithDocker
- Added connectToDatabase function for MongoDB connection
- Exported function signatures for transactionLogPath, askForTransactionLogPath, and getDockerComposeCommand
tests/setup/transactionLog.spec.ts - Introduced a test suite for askForTransactionLogPath with two test cases for valid and invalid paths
tests/setup/dataImportFlow.spec.ts - Added unit tests for dataImportWithoutDocker and dataImportWithDocker functions, covering various scenarios

Assessment against linked issues

Objective Addressed Explanation
Data importation flow improvement [#2829]
Remove Docker-specific prompts when not using Docker [#2829] The logic now correctly avoids Docker prompts when Docker is not selected.
Clarify data importation questions [#2829]

Possibly related issues

Possibly related PRs

Suggested reviewers

  • palisadoes
  • SiddheshKukade
  • DMills27

Poem

🐰 In the realm of setup's grand design,
Code dances, imports now align!
Errors caught with gentle care,
Data flows without a snare,
Talawa's path now clear and fine! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
setup.ts (3)

226-226: Enhance error handling consistency.

While the error handling improvements are good, consider adding more specific error information to help with troubleshooting.

-    throw new Error("Could not connect to database to check for data");
+    const error = err instanceof Error ? err.message : String(err);
+    throw new Error(`Failed to connect to database: ${error}`);

Also applies to: 242-254


Line range hint 1276-1323: Consider extracting MongoDB connection retry logic.

The MongoDB connection retry logic could be extracted into a separate function for better maintainability.

+async function waitForMongoDB(url: string, maxRetries: number = 30): Promise<void> {
+  let isConnected = false;
+  let retryCount = 0;
+  while (!isConnected) {
+    if (retryCount >= maxRetries) {
+      throw new Error(`Timed out waiting for MongoDB to be ready after ${maxRetries} seconds`);
+    }
+    try {
+      const client = new MongoClient(url);
+      await client.connect();
+      await client.db().command({ ping: 1 });
+      client.close();
+      isConnected = true;
+      console.log("MongoDB is ready!");
+    } catch (err) {
+      const error = err instanceof Error ? err.message : String(err);
+      console.log(
+        `Waiting for MongoDB to be ready... Retry ${retryCount + 1}/${maxRetries}. Details: ${error}`
+      );
+      await new Promise((resolve) => setTimeout(resolve, 1000));
+      retryCount++;
+    }
+  }
+}

1332-1335: Enhance setup completion message.

Consider providing more specific information about what was successfully set up.

-    "\nCongratulations! Talawa API has been successfully setup! 🥂🎉",
+    "\nCongratulations! Talawa API has been successfully set up! 🥂🎉\n" +
+    "- Database configuration: ✅\n" +
+    `- Default data imported: ✅\n` +
+    `- Sample data imported: ${shouldImportSampleData ? "✅" : "❌"}\n` +
+    "- Docker containers: " + (isDockerInstallation ? "✅" : "❌"),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 25207c5 and 067fdb2.

📒 Files selected for processing (1)
  • setup.ts (13 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Check for linting, formatting, and type errors
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (3)
setup.ts (3)

5-5: Import changes align with ES modules transition.

The addition of dirname and fileURLToPath imports properly handles path resolution in ES modules, addressing the breaking change mentioned in the PR objectives.

Also applies to: 34-34


145-149: Improved log path resolution and file management.

The changes correctly handle path resolution for ES modules and improve log file management by:

  • Using dirname(fileURLToPath(import.meta.url)) for proper path resolution
  • Creating logs directory if it doesn't exist

Also applies to: 159-159


Line range hint 1233-1275: Improved data import flow and user prompts.

The changes provide clearer prompts and better separation between default and sample data import operations.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 10, 2025
@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 10, 2025
Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Remember to add tests.
  2. We can't have this again

@Aad1tya27
Copy link
Author

  1. Remember to add tests.
  2. We can't have this again

Yes I'm writing tests now.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
setup.ts (1)

Line range hint 1233-1275: Add error handling for data import operations.

The database setup flow has been improved, but consider adding:

  1. Error handling for failed data imports
  2. Rollback mechanism for partial import failures
  3. Progress indicators for long-running operations
       if (shouldOverwriteData) {
         await wipeExistingData(process.env.MONGO_DB_URL);
-        await importDefaultData();
+        try {
+          console.log("Importing default data...");
+          await importDefaultData();
+          console.log("Default data imported successfully.");
+        } catch (error) {
+          console.error("Failed to import default data:", error);
+          const { shouldRetry } = await inquirer.prompt({
+            type: "confirm",
+            name: "shouldRetry",
+            message: "Would you like to retry importing default data?",
+            default: true,
+          });
+          if (shouldRetry) {
+            await importDefaultData();
+          } else {
+            throw new Error("Setup cannot continue without default data");
+          }
+        }
🧹 Nitpick comments (5)
tests/setup/transactionLog.spec.ts (2)

6-16: Update test documentation to match the actual test cases.

The documentation comments describe test cases for askForSuperAdminEmail and superAdmin functions, but this file is testing the askForTransactionLogPath function. Please update the documentation to reflect the actual test cases in this file.


33-45: Consider adding assertions for prompt calls and error handling.

While the test effectively verifies the retry behavior, consider adding assertions to:

  1. Verify that inquirer.prompt was called exactly twice
  2. Verify error messages shown to users match expected values

Example enhancement:

 const result = await askForTransactionLogPath();
 expect(result).toEqual(testPath);
+expect(inquirer.prompt).toHaveBeenCalledTimes(2);
+expect(console.error).toHaveBeenCalledWith(
+  "Invalid path or file does not exist. Please enter a valid file path."
+);
setup.ts (3)

Line range hint 172-202: Enhance user feedback in the prompt.

Consider the following improvements:

  1. The default path shown in the prompt message should match the actual default path used in transactionLogPath
  2. Error messages could be more specific about permission issues
       {
         type: "input",
         name: "logPath",
         message: "Enter absolute path of log file:",
-        default: null,
+        default: path.join(process.cwd(), "logs", "transaction.log"),
       },

     if (logPath && fs.existsSync(logPath)) {
       try {
         fs.accessSync(logPath, fs.constants.R_OK | fs.constants.W_OK);
         isValidPath = true;
       } catch {
         console.error(
-          "The file is not readable/writable. Please enter a valid file path.",
+          `The file exists but ${!fs.accessSync(logPath, fs.constants.R_OK) ? "is not readable" : "is not writable"}. Please ensure you have proper permissions.`,
         );
       }

Line range hint 1276-1331: Enhance Docker setup reliability.

Consider the following improvements:

  1. Move timeout values to constants
  2. Add health checks for Redis and MinIO services
  3. Add retry mechanism for Docker compose failures
+const MONGODB_READY_TIMEOUT_SECONDS = 30;
+const MONGODB_CHECK_INTERVAL_MS = 1000;
+
     if (shouldStartDockerContainers) {
       console.log("Starting docker container...");
       try {
         await runDockerComposeWithLogs();
         console.log("Docker containers have been built successfully!");
-        // Wait for mongoDB to be ready
-        console.log("Waiting for mongoDB to be ready...");
+        // Wait for services to be ready
+        console.log("Waiting for services to be ready...");
         let isConnected = false;
-        const maxRetries = 30; // 30 seconds timeout
+        const maxRetries = MONGODB_READY_TIMEOUT_SECONDS;
         let retryCount = 0;
+
+        // Check MongoDB readiness
         while (!isConnected) {
           if (retryCount >= maxRetries) {
             throw new Error(
-              "Timed out waiting for MongoDB to be ready after 30 seconds",
+              `Timed out waiting for MongoDB to be ready after ${MONGODB_READY_TIMEOUT_SECONDS} seconds`,
             );
           }
           try {
             const client = new MongoClient(process.env.MONGO_DB_URL as string);
             await client.connect();
             await client.db().command({ ping: 1 });
             client.close();
             isConnected = true;
             console.log("MongoDB is ready!");
           } catch (err) {
             const error = err instanceof Error ? err.message : String(err);
             console.log(
               `Waiting for MongoDB to be ready... Retry ${retryCount + 1}/${maxRetries}. Details: ${error}`,
             );
-            await new Promise((resolve) => setTimeout(resolve, 1000));
+            await new Promise((resolve) => setTimeout(resolve, MONGODB_CHECK_INTERVAL_MS));
             retryCount++;
           }
         }
+
+        // Check Redis readiness
+        console.log("Checking Redis connection...");
+        await checkRedisConnection(`redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`);
+        console.log("Redis is ready!");
+
+        // Check MinIO readiness
+        console.log("Checking MinIO connection...");
+        // Add MinIO health check here
+        console.log("MinIO is ready!");

1332-1335: Enhance the success message with setup details.

Consider adding more information to help users get started:

-  console.log(
-    "\nCongratulations! Talawa API has been successfully setup! 🥂🎉",
-  );
+  console.log(`
+    \nCongratulations! Talawa API has been successfully setup! 🥂🎉
+    
+    Your setup details:
+    - API running on port: ${process.env.SERVER_PORT}
+    - MongoDB URL: ${process.env.MONGO_DB_URL}
+    - Redis host: ${process.env.REDIS_HOST}
+    - MinIO endpoint: ${process.env.MINIO_ENDPOINT}
+    
+    To start the server, run: npm start
+    For more information, visit: https://github.com/PalisadoesFoundation/talawa-api
+  `);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 067fdb2 and 9de22b4.

📒 Files selected for processing (2)
  • setup.ts (15 hunks)
  • tests/setup/transactionLog.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Check for linting, formatting, and type errors
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
tests/setup/transactionLog.spec.ts (1)

22-31: LGTM! Well-structured test case.

The test effectively covers the success scenario with proper mocking of dependencies and validation of the result.

setup.ts (1)

Line range hint 143-171: LGTM! Proper ES modules path resolution implementation.

The function correctly handles the transition from CommonJS to ES modules by using fileURLToPath and dirname for path resolution while maintaining the existing functionality.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 11, 2025
Copy link

codecov bot commented Jan 11, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.68%. Comparing base (eca60ae) to head (d1cccc0).
Report is 4 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #2845   +/-   ##
========================================
  Coverage    97.68%   97.68%           
========================================
  Files          364      364           
  Lines        18563    18563           
  Branches      2677     2677           
========================================
  Hits         18133    18133           
  Misses         425      425           
  Partials         5        5           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (2)
setup.ts (2)

Line range hint 143-170: Add write permission validation for log directory

The function should validate write permissions for the log directory before setting it as the log path.

 export function transactionLogPath(logPath: string | null): void {
   const config = dotenv.parse(fs.readFileSync(".env"));
   const currDir = dirname(fileURLToPath(import.meta.url));
   config.LOG = "true";
   if (!logPath) {
     const defaultLogPath = path.resolve(currDir, "logs");
     const defaultLogFile = path.join(defaultLogPath, "transaction.log");
+    
+    // Validate write permissions
+    try {
+      if (!fs.existsSync(defaultLogPath)) {
+        fs.mkdirSync(defaultLogPath, { recursive: true });
+      }
+      // Test write permissions
+      fs.accessSync(defaultLogPath, fs.constants.W_OK);
+    } catch (error) {
+      throw new Error(`No write permission for log directory: ${defaultLogPath}`);
+    }
-    if (!fs.existsSync(defaultLogPath)) {
-      console.log("Creating logs/transaction.log file...");
-      fs.mkdirSync(defaultLogPath);
-    }

Line range hint 1037-1365: Consider breaking down the main function

The main function is quite long and handles many responsibilities. Consider breaking it down into smaller, focused functions for better maintainability.

Example refactor:

async function configureTokens(): Promise<void> {
  let accessToken: string | null = "";
  let refreshToken: string | null = "";
  
  // ... token configuration logic ...
  
  await accessAndRefreshTokens(accessToken, refreshToken);
}

async function configureLogging(): Promise<void> {
  const { shouldLog } = await inquirer.prompt({
    type: "confirm",
    name: "shouldLog",
    message: "Would you like to enable logging for the database transactions?",
    default: true,
  });
  
  // ... logging configuration logic ...
}

async function main(): Promise<void> {
  console.log("Welcome to the Talawa API setup! 🚀");
  
  await initializeEnvironment();
  await configureTokens();
  await configureLogging();
  // ... other configuration steps ...
}
🧹 Nitpick comments (6)
tests/setup/dataImportFlow.spec.ts (3)

17-52: Test description could be more precise

The test description "should import sample data if the database is empty and user opts to import" doesn't fully reflect what's being tested. Consider renaming to clarify that it tests the flow where sample data is imported instead of default data.

-  it("should import sample data if the database is empty and user opts to import", async () => {
+  it("should import sample data (not default data) when database is empty and user chooses to import sample data", async () => {

17-52: Extract common mock setup to beforeEach

The mock setup code is duplicated across test cases. Consider extracting it to the beforeEach block to improve maintainability and reduce duplication.

 describe("Data Importation Without Docker", () => {
   const mockEnv = { ...process.env }; // Backup the environment variables
+  let checkDbMock: vi.Mock;
+  let wipeExistingDataMock: vi.Mock;
+  let importDataMock: vi.Mock;
+  let importDefaultDataMock: vi.Mock;
 
   beforeEach(() => {
     process.env.MONGO_DB_URL = "mongodb://localhost:27017/sample-table";
     vi.resetAllMocks();
+    
+    checkDbMock = vi
+      .fn()
+      .mockImplementation(async (): Promise<boolean> => {
+        return true;
+      });
+    
+    wipeExistingDataMock = vi
+      .fn()
+      .mockImplementation(async (): Promise<void> => {
+        return Promise.resolve();
+      });
+    
+    importDataMock = vi
+      .fn()
+      .mockImplementation(async (): Promise<void> => {
+        return Promise.resolve();
+      });
+    
+    importDefaultDataMock = vi
+      .fn()
+      .mockImplementation(async (): Promise<void> => {
+        return Promise.resolve();
+      });
   });

Also applies to: 54-89, 91-126, 128-163, 165-200


252-287: Enhance error scenario testing

The error scenario test doesn't validate the actual error message. Consider adding assertions to verify the error details.

   it("should terminate execution if error is encountered while starting containers", async () => {
+    const errorMessage = "Error starting containers";
     const runDockerComposeMock = vi
       .fn()
       .mockImplementation(async (): Promise<void> => {
-        throw new Error("Error starting containers");
+        throw new Error(errorMessage);
       });
     // ... other mocks ...
 
-    await dataImportWithDocker(
+    await expect(dataImportWithDocker(
       runDockerComposeMock,
       importDefaultDataMock,
       importDataMock,
       connectDatabaseMock,
-    );
+    )).rejects.toThrow(errorMessage);
setup.ts (3)

Line range hint 1-34: Consider organizing imports by category

While not critical, organizing imports into categories (built-in modules, external dependencies, internal modules) would improve readability.

+// Built-in Node.js modules
 import * as cryptolib from "crypto";
-import dotenv from "dotenv";
 import fs from "fs";
-import inquirer from "inquirer";
 import path, { dirname } from "path";
 import type { ExecException } from "child_process";
 import { exec, spawn, execSync } from "child_process";
+import { fileURLToPath } from "url";
+
+// External dependencies
+import dotenv from "dotenv";
+import inquirer from "inquirer";
 import { MongoClient } from "mongodb";
+
+// Internal modules
 import { MAXIMUM_IMAGE_SIZE_LIMIT_KB } from "@constants";
-import {
-  askForMongoDBUrl,
-  checkConnection,
-  checkExistingMongoDB,
-} from "@setup/MongoDB";
+// ... rest of internal imports

971-999: Make database connection retry configuration customizable

The retry logic uses hardcoded values. Consider making these configurable through environment variables.

 async function connectToDatabase(): Promise<void> {
   console.log("Waiting for mongoDB to be ready...");
   let isConnected = false;
-  const maxRetries = 30; // 30 seconds timeout
+  const maxRetries = Number(process.env.MONGODB_MAX_RETRIES) || 30;
+  const retryInterval = Number(process.env.MONGODB_RETRY_INTERVAL) || 1000; // milliseconds
   let retryCount = 0;
   while (!isConnected) {
     if (retryCount >= maxRetries) {
       throw new Error(
-        "Timed out waiting for MongoDB to be ready after 30 seconds",
+        `Timed out waiting for MongoDB to be ready after ${maxRetries * retryInterval / 1000} seconds`,
       );
     }
     // ... rest of the function
-      await new Promise((resolve) => setTimeout(resolve, 1000));
+      await new Promise((resolve) => setTimeout(resolve, retryInterval));

Line range hint 471-488: Improve Docker Compose command detection

The function could be more robust in detecting Docker Compose versions and handling errors.

 export function getDockerComposeCommand(): { command: string; args: string[] } {
   let dockerComposeCmd = "docker-compose"; // Default to v1
   let args = ["-f", "docker-compose.dev.yaml", "up", "--build", "-d"];
 
   try {
-    // Test if 'docker compose' works (v2)
-    execSync("docker compose version", { stdio: "ignore" });
+    // Check for Docker Compose v2
+    const result = execSync("docker compose version", { encoding: 'utf8' });
+    if (result.toLowerCase().includes('v2.')) {
+      console.log("Using Docker Compose v2");
+      dockerComposeCmd = "docker";
+      args = ["compose", ...args];
+    } else {
+      console.log("Using Docker Compose v1");
+    }
-    dockerComposeCmd = "docker";
-    args = ["compose", ...args]; // Prefix 'compose' for v2
   } catch (error) {
-    console.log(error);
+    console.log("Docker Compose v2 not detected, falling back to v1");
     dockerComposeCmd =
       process.platform === "win32" ? "docker-compose.exe" : "docker-compose";
   }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9de22b4 and 344be33.

📒 Files selected for processing (2)
  • setup.ts (14 hunks)
  • tests/setup/dataImportFlow.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Testing Application (22.x)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (1)
tests/setup/dataImportFlow.spec.ts (1)

Line range hint 1021-1027: Inconsistent default values in prompts

The default value for importing sample data differs between Docker and non-Docker flows:

  • Docker flow: default: true
  • Non-Docker flow: default: false

This inconsistency might confuse users. Consider aligning the defaults or documenting the reason for the difference.

Also applies to: 385-386

tests/setup/dataImportFlow.spec.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (4)
tests/setup/dataImportFlow.spec.ts (4)

Line range hint 918-975: Refactor data import function for better separation of concerns.

The dataImportWithoutDocker function handles too many responsibilities. Consider splitting it into smaller, focused functions.

  1. Extract user interaction logic:
async function promptForDataImport(isEmptyDb: boolean): Promise<{
  shouldOverwrite: boolean;
  shouldImportSample: boolean;
}> {
  if (!isEmptyDb) {
    const { shouldOverwriteData } = await inquirer.prompt({
      type: "confirm",
      name: "shouldOverwriteData",
      message: "Do you want to delete the existing data and import required default Data?",
      default: false,
    });
    
    if (!shouldOverwriteData) {
      return { shouldOverwrite: false, shouldImportSample: false };
    }
  }

  const { shouldImportSample } = await inquirer.prompt({
    type: "confirm",
    name: "shouldImportSample",
    message: "Do you want to import Talawa sample data for testing?",
    default: false,
  });

  return { 
    shouldOverwrite: !isEmptyDb, 
    shouldImportSample 
  };
}
  1. Add better error handling:
   } catch (error) {
+    if (error instanceof Error) {
+      if (error.message.includes("ECONNREFUSED")) {
+        throw new Error("Database connection refused. Please check if the database is running.");
+      }
+      if (error.message.includes("Authentication failed")) {
+        throw new Error("Database authentication failed. Please check your credentials.");
+      }
+    }
     throw new Error(
       `Failed to check database: ${error instanceof Error ? error.message : String(error)}`,
     );
   }

Line range hint 977-1005: Enhance database connection handling.

The connection retry logic could be more robust and configurable.

  1. Extract retry configuration:
interface RetryConfig {
  maxRetries: number;
  retryDelay: number;
  timeout: number;
}

const DEFAULT_RETRY_CONFIG: RetryConfig = {
  maxRetries: 30,
  retryDelay: 1000,
  timeout: 30000,
};

async function connectToDatabase(config: RetryConfig = DEFAULT_RETRY_CONFIG): Promise<void> {
  console.log("Waiting for mongoDB to be ready...");
  let client: MongoClient | null = null;
  
  try {
    await withRetry(async () => {
      client = new MongoClient(process.env.MONGO_DB_URL as string);
      await client.connect();
      await client.db().command({ ping: 1 });
      console.log("MongoDB is ready!");
    }, config);
  } catch (err) {
    throw new Error(`Database connection failed: ${err instanceof Error ? err.message : String(err)}`);
  } finally {
    if (client) {
      await client.close();
    }
  }
}
  1. Add helper for retry logic:
async function withRetry<T>(
  operation: () => Promise<T>,
  config: RetryConfig
): Promise<T> {
  let lastError: Error | null = null;
  
  for (let i = 0; i < config.maxRetries; i++) {
    try {
      return await operation();
    } catch (err) {
      lastError = err instanceof Error ? err : new Error(String(err));
      console.log(
        `Retry ${i + 1}/${config.maxRetries}. Error: ${lastError.message}`
      );
      await new Promise(resolve => setTimeout(resolve, config.retryDelay));
    }
  }
  
  throw new Error(
    `Operation failed after ${config.maxRetries} retries. Last error: ${lastError?.message}`
  );
}

Line range hint 471-490: Improve Docker command detection and error handling.

The Docker command detection could be more robust and include better error handling.

 export function getDockerComposeCommand(): { command: string; args: string[] } {
+  // Check if Docker CLI is available first
+  try {
+    execSync("docker --version", { stdio: "ignore" });
+  } catch (error) {
+    throw new Error(
+      "Docker CLI not found. Please ensure Docker is installed correctly."
+    );
+  }
+
   let dockerComposeCmd = "docker-compose"; // Default to v1
   let args = ["-f", "docker-compose.dev.yaml", "up", "--build", "-d"];

   try {
     // Test if 'docker compose' works (v2)
     execSync("docker compose version", { stdio: "ignore" });
     dockerComposeCmd = "docker";
     args = ["compose", ...args]; // Prefix 'compose' for v2
   } catch (error) {
-    console.log(error);
+    console.log("Docker Compose v2 not detected, falling back to v1");
     dockerComposeCmd =
       process.platform === "win32" ? "docker-compose.exe" : "docker-compose";
   }

   return { command: dockerComposeCmd, args };
 }

Line range hint 1007-1042: Add cleanup handling for Docker operations.

The Docker import function should handle cleanup in case of failures.

 export async function dataImportWithDocker(
   runDockerComposeWithLogs: () => Promise<void>,
   importDefaultData: () => Promise<void>,
   importData: () => Promise<void>,
   connectToDatabase: () => Promise<void>,
 ): Promise<void> {
+  let containersStarted = false;
   try {
     const { shouldStartDockerContainers } = await inquirer.prompt({
       type: "confirm",
       name: "shouldStartDockerContainers",
       message: "Do you want to start the Docker containers now?",
       default: true,
     });
     
     if (shouldStartDockerContainers) {
       console.log("Starting docker container...");
       await runDockerComposeWithLogs();
+      containersStarted = true;
       // ... rest of the code ...
     }
   } catch (err) {
+    if (containersStarted) {
+      console.log("Error occurred. Cleaning up containers...");
+      try {
+        const { command, args } = getDockerComposeCommand();
+        await new Promise((resolve, reject) => {
+          const cleanup = spawn(command, [...args.slice(0, 2), "down"]);
+          cleanup.on("error", reject);
+          cleanup.on("close", resolve);
+        });
+      } catch (cleanupError) {
+        console.error("Failed to cleanup containers:", cleanupError);
+      }
+    }
     throw err;
   }
 }
🧹 Nitpick comments (7)
tests/setup/dataImportFlow.spec.ts (5)

6-6: Enhance environment variable backup.

Consider using a more type-safe approach for environment variable backup.

-  const mockEnv = { ...process.env }; // Backup the environment variables
+  const mockEnv: NodeJS.ProcessEnv = { ...process.env }; // Backup the environment variables

17-52: Improve test case naming and assertions.

The test case name could be more descriptive of the exact scenario being tested. Also, consider adding assertions for the exact parameters passed to the mocked functions.

-  it("should import sample data if the database is empty and user opts to import", async () => {
+  it("should import sample data without wiping when database is empty and user confirms import", async () => {
     // ... existing code ...
     expect(checkDbMock).toBeCalled();
+    expect(checkDbMock).toHaveBeenCalledWith(process.env.MONGO_DB_URL);
     expect(wipeExistingDataMock).not.toBeCalled();
     expect(importDefaultDataMock).not.toBeCalled();
     expect(importDataMock).toBeCalled();

202-238: Add validation for error message content.

The error handling test should validate the exact error message format.

     await expect(
       dataImportWithoutDocker(
         checkDbMock,
         wipeExistingDataMock,
         importDefaultDataMock,
         importDataMock,
       ),
-    ).rejects.toThrow(errorMessage);
+    ).rejects.toThrow(/^Failed to check database: Database connection failed$/);

1-436: Add test coverage for additional edge cases.

Consider adding test cases for the following scenarios:

  1. Network connectivity issues during database operations
  2. Permission errors when accessing Docker daemon
  3. Invalid data format during import

Example test case for network issues:

it("should handle network connectivity issues during database operations", async () => {
  const connectDatabaseMock = vi
    .fn()
    .mockRejectedValue(new Error("ECONNREFUSED"));
  
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce({
    shouldStartDockerContainers: true,
  });

  await expect(
    dataImportWithDocker(
      vi.fn(),
      vi.fn(),
      vi.fn(),
      connectDatabaseMock,
    )
  ).rejects.toThrow(/ECONNREFUSED/);
});

5-34: Organize imports for better maintainability.

The imports could be better organized by grouping them into:

  1. Node.js built-in modules
  2. External dependencies
  3. Internal modules
-import path, { dirname } from "path";
-import type { ExecException } from "child_process";
-import { exec, spawn, execSync } from "child_process";
-import { MongoClient } from "mongodb";
+// Node.js built-in modules
+import { dirname } from "path";
+import path from "path";
+import type { ExecException } from "child_process";
+import { exec, execSync, spawn } from "child_process";
+import { fileURLToPath } from "url";

+// External dependencies
+import { MongoClient } from "mongodb";
+import dotenv from "dotenv";
+import inquirer from "inquirer";

+// Internal modules
setup.ts (2)

977-1005: Enhance retry mechanism with exponential backoff.

While the connection handling is good, consider implementing exponential backoff for retries to prevent overwhelming the database server.

 async function connectToDatabase(): Promise<void> {
   console.log("Waiting for mongoDB to be ready...");
   let isConnected = false;
   const maxRetries = 30;
   let retryCount = 0;
+  const baseDelay = 1000; // 1 second
   while (!isConnected) {
     if (retryCount >= maxRetries) {
       throw new Error(
         "Timed out waiting for MongoDB to be ready after 30 seconds",
       );
     }
     try {
       const client = new MongoClient(process.env.MONGO_DB_URL as string);
       await client.connect();
       await client.db().command({ ping: 1 });
       client.close();
       isConnected = true;
       console.log("MongoDB is ready!");
     } catch (err) {
       const error = err instanceof Error ? err.message : String(err);
       console.log(
         `Waiting for MongoDB to be ready... Retry ${retryCount + 1}/${maxRetries}. Details: ${error}`,
       );
-      await new Promise((resolve) => setTimeout(resolve, 1000));
+      const delay = Math.min(baseDelay * Math.pow(2, retryCount), 10000); // Cap at 10 seconds
+      await new Promise((resolve) => setTimeout(resolve, delay));
       retryCount++;
     }
   }
   return Promise.resolve();
 }

918-975: Extract common prompt logic to reduce duplication.

Both data import functions have similar prompt handling code. Consider extracting the common prompt logic into a shared function.

async function promptForSampleDataImport(message: string = "Do you want to import Talawa sample data for testing and evaluation purposes?"): Promise<boolean> {
  const { shouldImportSampleData } = await inquirer.prompt({
    type: "confirm",
    name: "shouldImportSampleData",
    message,
    default: false,
  });
  return shouldImportSampleData;
}

This would simplify both functions and make future changes easier to maintain.

Also applies to: 1007-1042

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 344be33 and d9494cb.

📒 Files selected for processing (2)
  • setup.ts (14 hunks)
  • tests/setup/dataImportFlow.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Testing Application (22.x)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (3)
setup.ts (3)

5-5: LGTM! Proper ES modules path handling.

The changes correctly handle the transition from CommonJS to ES modules by using dirname and fileURLToPath instead of __dirname.

Also applies to: 34-34


924-935: Improved error handling with descriptive messages.

The error handling has been enhanced with:

  • Proper error propagation instead of console.log
  • Detailed error messages
  • Type-safe error handling using instanceof checks

1355-1367: LGTM! Clear separation of Docker and non-Docker flows.

The main function now has a clearer separation of concerns between Docker and non-Docker environments, making the code more maintainable.

tests/setup/dataImportFlow.spec.ts Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
tests/setup/dataImportFlow.spec.ts (2)

17-239: Refactor duplicated mock setups in 'Data Importation Without Docker' tests

The mock implementations for checkDbMock, wipeExistingDataMock, importDataMock, and importDefaultDataMock are repeated across multiple tests. To improve maintainability and reduce redundancy, consider refactoring these mocks into shared variables initialized in the beforeEach block.

Example refactoring:

let checkDbMock: ReturnType<typeof vi.fn>;
let wipeExistingDataMock: ReturnType<typeof vi.fn>;
let importDataMock: ReturnType<typeof vi.fn>;
let importDefaultDataMock: ReturnType<typeof vi.fn>;

beforeEach(() => {
  checkDbMock = vi.fn().mockResolvedValue(true);
  wipeExistingDataMock = vi.fn().mockResolvedValue();
  importDataMock = vi.fn().mockResolvedValue();
  importDefaultDataMock = vi.fn().mockResolvedValue();
  vi.resetAllMocks();
});

You can then adjust the return values or behaviors within individual tests as needed.


241-464: Refactor duplicated mock setups in 'Data Importation With Docker' tests

Similar to the previous suggestion, the mock implementations for runDockerComposeMock, importDataMock, importDefaultDataMock, and connectDatabaseMock are repeated across multiple tests. Refactoring them into shared variables initialized in the beforeEach block would enhance readability and maintainability.

Example refactoring:

let runDockerComposeMock: ReturnType<typeof vi.fn>;
let importDataMock: ReturnType<typeof vi.fn>;
let importDefaultDataMock: ReturnType<typeof vi.fn>;
let connectDatabaseMock: ReturnType<typeof vi.fn>;

beforeEach(() => {
  runDockerComposeMock = vi.fn().mockResolvedValue();
  importDataMock = vi.fn().mockResolvedValue();
  importDefaultDataMock = vi.fn().mockResolvedValue();
  connectDatabaseMock = vi.fn().mockResolvedValue();
  vi.resetAllMocks();
});

Override specific behaviors in individual tests when necessary.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d9494cb and 6445f57.

📒 Files selected for processing (1)
  • tests/setup/dataImportFlow.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Testing Application (22.x)
🔇 Additional comments (1)
tests/setup/dataImportFlow.spec.ts (1)

202-239: Excellent work incorporating the database connection failure test

The test case for handling database connection failures is well implemented and enhances the robustness of the test suite. It correctly mocks the rejection and asserts that the error is thrown, ensuring that the error handling logic works as expected.

tests/setup/dataImportFlow.spec.ts Outdated Show resolved Hide resolved
tests/setup/dataImportFlow.spec.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
tests/setup/dataImportFlow.spec.ts (4)

5-15: Consider improving test environment setup.

The test setup could be enhanced in the following ways:

  1. Extract the MongoDB URL to a constant or configuration file
  2. Be more selective about which environment variables to backup
+const TEST_MONGODB_URL = "mongodb://localhost:27017/sample-table";
+const REQUIRED_ENV_VARS = ['MONGO_DB_URL'];

 describe("Data Importation Without Docker", () => {
-  const mockEnv = { ...process.env };
+  const mockEnv = REQUIRED_ENV_VARS.reduce((acc, key) => ({
+    ...acc,
+    [key]: process.env[key]
+  }), {});

   beforeEach(() => {
-    process.env.MONGO_DB_URL = "mongodb://localhost:27017/sample-table";
+    process.env.MONGO_DB_URL = TEST_MONGODB_URL;
     vi.resetAllMocks();
   });

Also applies to: 241-251


17-238: Reduce test setup duplication and improve error handling tests.

Consider the following improvements:

  1. Extract common mock setup to a helper function
  2. Use a specific error type for database connection failures
// Add these helper functions at the beginning of the test suite
function createMocks() {
  return {
    checkDbMock: vi.fn().mockResolvedValue(true),
    wipeExistingDataMock: vi.fn().mockResolvedValue(undefined),
    importDataMock: vi.fn().mockResolvedValue(undefined),
    importDefaultDataMock: vi.fn().mockResolvedValue(undefined),
  };
}

class DatabaseConnectionError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'DatabaseConnectionError';
  }
}

Then use them in your tests:

 it("should handle database connection failure gracefully", async () => {
-    const checkDbMock = vi.fn()...
-    const wipeExistingDataMock = vi.fn()...
-    const importDataMock = vi.fn()...
-    const importDefaultDataMock = vi.fn()...
+    const {
+      checkDbMock,
+      wipeExistingDataMock,
+      importDataMock,
+      importDefaultDataMock
+    } = createMocks();
     const errorMessage = "Database connection failed";
-    checkDbMock.mockRejectedValueOnce(new Error(errorMessage));
+    checkDbMock.mockRejectedValueOnce(new DatabaseConnectionError(errorMessage));

438-463: Improve Docker timeout test reliability and assertions.

The timeout test could be enhanced by:

  1. Using a constant for the timeout value
  2. Adding an explicit assertion for the error message
+const DOCKER_STARTUP_TIMEOUT = 3000;

 it("should handle Docker container startup timeout", async () => {
   const runDockerComposeMock = vi.fn().mockImplementation(async () => {
     return new Promise((_, reject) => {
       setTimeout(() => {
         reject(new Error("Docker compose operation timed out"));
-      }, 3000);
+      }, DOCKER_STARTUP_TIMEOUT);
     });
   });
   const importDataMock = vi.fn();
   const importDefaultDataMock = vi.fn();
   const connectDatabaseMock = vi.fn();

   vi.spyOn(inquirer, "prompt").mockResolvedValueOnce({
     shouldStartDockerContainers: true,
   });

-  await dataImportWithDocker(
+  await expect(dataImportWithDocker(
     runDockerComposeMock,
     importDefaultDataMock,
     importDataMock,
     connectDatabaseMock,
-  );
+  )).rejects.toThrow("Docker compose operation timed out");

   expect(runDockerComposeMock).toBeCalled();
   expect(connectDatabaseMock).not.toBeCalled();
 });

1-464: Add test for MongoDB URL configuration.

Consider adding a test case to verify that the correct MongoDB URL is being used. This ensures that the connection string is properly configured and passed to the database connection functions.

Example test to add:

it("should use the correct MongoDB URL from environment", async () => {
  const TEST_URL = "mongodb://test:27017/db";
  process.env.MONGO_DB_URL = TEST_URL;
  
  const { checkDbMock } = createMocks();
  
  await dataImportWithoutDocker(
    checkDbMock,
    vi.fn(),
    vi.fn(),
    vi.fn(),
  );
  
  expect(checkDbMock).toHaveBeenCalledWith(TEST_URL);
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6445f57 and 5f6b0a0.

📒 Files selected for processing (1)
  • tests/setup/dataImportFlow.spec.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
tests/setup/dataImportFlow.spec.ts (1)
Learnt from: Aad1tya27
PR: PalisadoesFoundation/talawa-api#2845
File: tests/setup/dataImportFlow.spec.ts:113-114
Timestamp: 2025-01-14T00:46:56.756Z
Learning: In talawa-api's setup.ts, two different prompt keys are used for sample data import:
1. `importSampleData` - Used when asking to import sample data after overwriting existing data
2. `shouldImportSampleData` - Used when asking to import sample data into an empty database
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Check for linting, formatting, and type errors
  • GitHub Check: Analyse Code With CodeQL (typescript)

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 14, 2025
@palisadoes
Copy link
Contributor

Your screen shots don't show the user being offered the opportunity to install sample data after saying No to the default data.

@Aad1tya27
Copy link
Author

Aad1tya27 commented Jan 14, 2025

Your screen shots don't show the user being offered the opportunity to install sample data after saying No to the default data.

There is no option to say No to the default data(which is just the organizations). There is only option to reject Sample Data, and on doing so default data will be automatically imported.

@Aad1tya27
Copy link
Author

If Docker is not Used:
Case 1: No Collections Found, Rejected Sample Data => Default Data is loaded
image

Case 2: No Collections Found, Accepted Sample Data => Sample Data is loaded
image
image
(Here there is no repetition anymore.)

Case 3: Collections Found, Data not overwritten => No change
image

Case 4: Collections Found, Data overwritten => option between loading sample data or default data
image

@Aad1tya27
Copy link
Author

@palisadoes If you want to see screenshots of Docker installation I can share them too, and if any other change is required let me know.

@Aad1tya27 Aad1tya27 requested a review from palisadoes January 14, 2025 01:25
@palisadoes
Copy link
Contributor

The logic must be:

  1. If data IS found, then you must be prompted to import it.
    1. If you select Yes :
      1. You are prompted to import the default data.
        1. If you import the default data, then there must be no prompt for importing the sample data
      2. If you do not import the default data, you are prompted to import the default data.
        2. If you do not choose to import the default data, then it's a no-op
  2. If data IS NOT found, then you must be prompted to import it.
    1. If you select Yes
      1. You are prompted to import the default data.
        1. If you import the default data, then there must be no prompt for importing the sample data
      2. If you do not import the default data, you are prompted to import the default data.
        2. If you do not choose to import the default data, then it's a no-op
    2. If you select No, then it's a no-op

Other comments:

The questions are too wordy.

Instead of the prompt :
- Do you want to delete the existing data and import required default Data to start using Talawa?
have:
- Do you want to DESTROY the existing data, replacing it with the default data required for a fresh production system?

Instead of the prompt :
- Do you want to import Talawa sample data for testing and evaluation purposes?
have:
- Do you want to DESTROY the existing data, replacing it with data suitable for testing and evaluation?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
tests/setup/dataImportFlow.spec.ts (4)

203-203: Fix typo in test description

There's an extra space in "should do no-op".

-  it("should  do no-op if db not empty and user imports neither default nor sample data", async () => {
+  it("should do no-op if db not empty and user imports neither default nor sample data", async () => {

278-314: Enhance database connection failure test

The test verifies basic error handling but could be improved to test different types of database failures.

Consider adding test cases for:

  1. Network timeout
  2. Authentication failure
  3. Invalid database URL

Example:

it("should handle database authentication failure", async () => {
  const errorMessage = "Authentication failed";
  checkDbMock.mockRejectedValueOnce(new Error(errorMessage));
  
  await expect(
    dataImportWithoutDocker(
      checkDbMock,
      wipeExistingDataMock,
      importDefaultDataMock,
      importDataMock,
    ),
  ).rejects.toThrow(errorMessage);
});

366-401: Improve error handling test for Docker container startup

The test doesn't verify that the error message is propagated correctly.

Add assertion to verify the error message:

   it("should terminate execution if error is encountered while starting containers", async () => {
+    const errorMessage = "Error starting containers";
     const runDockerComposeMock = vi
       .fn()
       .mockImplementation(async (): Promise<void> => {
-        throw new Error("Error starting containers");
+        throw new Error(errorMessage);
       });
     // ... other mocks ...

-    await dataImportWithDocker(
+    await expect(dataImportWithDocker(
       runDockerComposeMock,
       importDefaultDataMock,
       importDataMock,
       connectDatabaseMock,
-    );
+    )).rejects.toThrow(errorMessage);

     expect(runDockerComposeMock).toBeCalled();
     expect(connectDatabaseMock).not.toBeCalled();
     expect(importDefaultDataMock).not.toBeCalled();
     expect(importDataMock).not.toBeCalled();
   });

553-578: Improve Docker timeout test

The test could be enhanced to:

  1. Use a constant for the timeout value
  2. Verify the exact error message
  3. Add assertion for the rejection
+const MOCK_TIMEOUT = 3000;
+
 it("should handle Docker container startup timeout", async () => {
+  const errorMessage = "Docker compose operation timed out";
   const runDockerComposeMock = vi.fn().mockImplementation(async () => {
     return new Promise((_, reject) => {
       setTimeout(() => {
-        reject(new Error("Docker compose operation timed out"));
+        reject(new Error(errorMessage));
-      }, 3000);
+      }, MOCK_TIMEOUT);
     });
   });
   // ... other mocks ...

-  await dataImportWithDocker(
+  await expect(dataImportWithDocker(
     runDockerComposeMock,
     importDefaultDataMock,
     importDataMock,
     connectDatabaseMock,
-  );
+  )).rejects.toThrow(errorMessage);

   expect(runDockerComposeMock).toBeCalled();
   expect(connectDatabaseMock).not.toBeCalled();
 });
setup.ts (3)

918-992: Enhance error handling in dataImportWithoutDocker

While the error handling is improved, the function could benefit from more specific error types and consistent error handling.

Consider creating custom error types and handling operation-specific errors:

class DatabaseConnectionError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'DatabaseConnectionError';
  }
}

class DataImportError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'DataImportError';
  }
}

export async function dataImportWithoutDocker(...): Promise<void> {
  if (!process.env.MONGO_DB_URL) {
    throw new DatabaseConnectionError("MongoDB URL is not configured");
  }

  try {
    isDbEmpty = await checkDb(process.env.MONGO_DB_URL);
  } catch (error) {
    throw new DatabaseConnectionError(
      `Failed to check database: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  
  try {
    // ... rest of the function ...
  } catch (error) {
    throw new DataImportError(
      `Failed to import data: ${error instanceof Error ? error.message : String(error)}`
    );
  }
}

994-1022: Make database connection retry parameters configurable

The retry parameters are hardcoded. Consider making them configurable through environment variables.

+const DEFAULT_MAX_RETRIES = 30;
+const DEFAULT_RETRY_INTERVAL_MS = 1000;

 async function connectToDatabase(): Promise<void> {
   console.log("Waiting for mongoDB to be ready...");
   let isConnected = false;
-  const maxRetries = 30; // 30 seconds timeout
+  const maxRetries = Number(process.env.MONGODB_MAX_RETRIES) || DEFAULT_MAX_RETRIES;
+  const retryInterval = Number(process.env.MONGODB_RETRY_INTERVAL_MS) || DEFAULT_RETRY_INTERVAL_MS;
   let retryCount = 0;
   
   while (!isConnected) {
     if (retryCount >= maxRetries) {
       throw new Error(
-        "Timed out waiting for MongoDB to be ready after 30 seconds"
+        `Timed out waiting for MongoDB to be ready after ${maxRetries * retryInterval / 1000} seconds`
       );
     }
     // ... rest of the function ...
-      await new Promise((resolve) => setTimeout(resolve, 1000));
+      await new Promise((resolve) => setTimeout(resolve, retryInterval));
     }
   }
   return Promise.resolve();
 }

1024-1069: Improve error handling and logging in dataImportWithDocker

The function could benefit from more detailed error handling and logging.

 export async function dataImportWithDocker(
   runDockerComposeWithLogs: () => Promise<void>,
   importDefaultData: () => Promise<void>,
   importData: () => Promise<void>,
   connectToDatabase: () => Promise<void>,
 ): Promise<void> {
   // ... rest of the function ...
   if (shouldStartDockerContainers) {
     console.log("Starting docker container...");
     try {
       await runDockerComposeWithLogs();
       console.log("Docker containers have been built successfully!");
       
       await connectToDatabase();
       
       // ... rest of the function ...
     } catch (err) {
-      console.log("Some error occurred: " + err);
+      const error = err instanceof Error ? err : new Error(String(err));
+      console.error("Failed to setup Docker environment:", {
+        error: error.message,
+        stack: error.stack,
+        phase: "docker_setup",
+      });
+      throw error;
     }
   }
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f6b0a0 and d1cccc0.

📒 Files selected for processing (2)
  • setup.ts (14 hunks)
  • tests/setup/dataImportFlow.spec.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
tests/setup/dataImportFlow.spec.ts (1)
Learnt from: Aad1tya27
PR: PalisadoesFoundation/talawa-api#2845
File: tests/setup/dataImportFlow.spec.ts:113-114
Timestamp: 2025-01-14T00:46:56.756Z
Learning: In talawa-api's setup.ts, two different prompt keys are used for sample data import:
1. `importSampleData` - Used when asking to import sample data after overwriting existing data
2. `shouldImportSampleData` - Used when asking to import sample data into an empty database
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Testing Application (22.x)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (1)
setup.ts (1)

Line range hint 143-171: LGTM! Path handling updated for ES modules

The changes correctly update the path handling to use fileURLToPath and dirname for ES modules compatibility, replacing the CommonJS __dirname.

@Aad1tya27
Copy link
Author

@palisadoes I've corrected the flow of prompts and changed the tests accordingly. Kindly re-review it. For some reason I'm failing the Validate Code Rabbit check, even though it approved my changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants