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

fix: fix mongo db urls mismatch inside .env and docker-compose.dev.yaml file, along with some other setup fixes #2879

Closed

Conversation

aakarsh-2004
Copy link

@aakarsh-2004 aakarsh-2004 commented Jan 21, 2025

What kind of change does this PR introduce?

bug fix, when setting up the project locally using docker

Issue Number:

Fixes #2864

Snapshots/Videos:

The error looked some like
mongodb-not-connecting-error

Not everything works correctly and mongo starts successfully after docker setup
image

Previously default mongodb urls mismatched in .env file and docker-compose.dev.yaml file

MONGO_DB_URL inside .env previously.
mongodb-url- env

MONGO_DB_URL inside docker-compose.dev.yaml previously.
mongodb-url-docker-compose dev yaml

Now the default urls match!

MONGO_DB_URL inside .env now.
Screenshot 2025-01-21 152532

MONGO_DB_URL inside docker-compose.dev.yaml now.
image

I also fixed the Import Default Organization functionality was not working when setting up with docker and this error was being thrown.
Screenshot 2025-01-19 130059

This was happening because when setting up for the first time or from scratch constants.ts had stored MONGO_DB_URL was empty as MONGO_DB_URL later gets populated after user runs npm run setup. So instead we used process.env.MONGO_DB_URL for connecting to the MongoDB Container.
Also I followed the same file importing convention inside loadDefaultOrg.ts as used in loadSampleData.ts for better readability.

Summary

This PR ensures that users have easy time setting up this project locally without having to think much about it or so that users do not have to solve bugs on how to setup this project locally.

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

Have you read the contributing guide?

Yes

Summary by CodeRabbit

Release Notes

  • Configuration Updates

    • Enhanced MongoDB connection configuration with replica set and direct connection settings
    • Updated default MongoDB connection URL to include more specific connection parameters
  • Path Resolution

    • Improved module path resolution method using fileURLToPath
  • Testing

    • Updated test cases to reflect new MongoDB connection URL format

These changes improve database connection reliability and configuration consistency across different environments.

…, also correct the default mongodb url when not setting up with docker
…aml file, also correct the default mongodb url when not setting up with docker"

This reverts commit 8af7c63.
…, also correct the default mongodb url when not setting up with docker
…tabase not able to connect automatically/throws error after docker containers have started and fix the test for connecting to mongodb with correct url
Copy link

coderabbitai bot commented Jan 21, 2025

Walkthrough

The pull request introduces modifications to the MongoDB connection string across multiple files. The changes primarily involve appending query parameters ?replicaSet=rs0&directConnection=true to the MongoDB URL in various setup and configuration files. This ensures consistency in the database connection method across different environments, addressing potential discrepancies in how the MongoDB connection is established during project setup and development.

Changes

File Change Summary
setup.ts Modified MongoDB URL construction to append query parameters
src/db.ts Switched MongoDB URL source from constant import to environment variable
src/setup/MongoDB.ts Updated default MongoDB connection string with more specific parameters
src/utilities/loadDefaultOrg.ts Updated dirname definition using fileURLToPath
tests/setup/mongoDB.spec.ts Updated test cases to match new MongoDB URL format

Assessment against linked issues

Objective Addressed Explanation
Match MongoDB URLs in .env and docker-compose.dev.yaml
Add ?replicaSet=rs0&directConnection=true to MongoDB URL

Possibly related PRs

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes
  • adithyanotfound

Poem

🐰 MongoDB's dance, a connection so bright,
Replica sets spinning with pure delight,
Strings aligned, parameters neat,
Our database setup is now complete!
Code rabbit hops with joy so clear 🌟

✨ 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

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Congratulations on making your first PR! 🎊 If you haven't already, check out our Contributing Guidelines and PR Reporting Guidelines to ensure that you are following our guidelines for contributing and creating PR.

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 (2)
src/utilities/loadDefaultOrg.ts (1)

Line range hint 15-15: Fix typo in function name.

The function name has a typo: "Organiation" should be "Organization".

-export async function loadDefaultOrganiation(dbName?: string): Promise<void> {
+export async function loadDefaultOrganization(dbName?: string): Promise<void> {
setup.ts (1)

Line range hint 1-1379: ⚠️ Pipeline failure: Unauthorized file modification.

The pipeline indicates that this file is protected and cannot be modified. Please:

  1. Check if you have the necessary permissions to modify this file
  2. Consult with the repository maintainers about the correct process for updating protected files
🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Unauthorized file modification or deletion attempt. This file is protected and cannot be changed.

🧹 Nitpick comments (3)
src/setup/MongoDB.ts (1)

79-80: Document the MongoDB URL parameters.

The default URL now includes specific parameters (replicaSet=rs0&directConnection=true). Please add a comment explaining why these parameters are required and their impact.

    {
      type: "input",
      name: "url",
      message: "Enter your MongoDB URL:",
+      // Default URL includes replica set and direct connection parameters required for proper MongoDB connection
+      // replicaSet=rs0: Enables replica set mode for transaction support
+      // directConnection=true: Ensures direct connection to the specified MongoDB instance
      default:
        "mongodb://localhost:27017/talawa-api?replicaSet=rs0&directConnection=true",
    },
tests/setup/mongoDB.spec.ts (1)

73-75: Add test cases for invalid MongoDB URLs.

While the current tests cover the happy path with the new URL format, consider adding test cases for:

  1. URLs without required parameters
  2. Malformed URLs
  3. URLs with incorrect replica set names

Example test case:

it("should fail for URLs missing required parameters", async () => {
  const invalidUrl = "mongodb://localhost:27017/talawa-api";
  vi.spyOn(module, "checkConnection").mockImplementationOnce(() =>
    Promise.resolve(false)
  );
  
  const result = await module.checkConnection(invalidUrl);
  expect(result).toBe(false);
});

Also applies to: 103-105, 113-114

setup.ts (1)

448-448: Consider extracting MongoDB URL parameters to a constant.

The MongoDB URL parameters are duplicated. Consider extracting them to a constant for better maintainability.

+const MONGODB_URL_PARAMS = "?replicaSet=rs0&directConnection=true";
+
 // In the mongoDB function
-DB_URL = `${url?.endsWith("/talawa-api?replicaSet=rs0&directConnection=true") ? url : `${url}/talawa-api?replicaSet=rs0&directConnection=true`}`;
+DB_URL = `${url?.endsWith(`/talawa-api${MONGODB_URL_PARAMS}`) ? url : `${url}/talawa-api${MONGODB_URL_PARAMS}`}`;

Also applies to: 454-454

🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Unauthorized file modification or deletion attempt. This file is protected and cannot be changed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3341235 and 2520345.

📒 Files selected for processing (5)
  • setup.ts (2 hunks)
  • src/db.ts (1 hunks)
  • src/setup/MongoDB.ts (1 hunks)
  • src/utilities/loadDefaultOrg.ts (1 hunks)
  • tests/setup/mongoDB.spec.ts (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: PR Workflow
setup.ts

[error] Unauthorized file modification or deletion attempt. This file is protected and cannot be changed.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
src/utilities/loadDefaultOrg.ts (1)

3-3: LGTM! Good improvement in path handling.

The change to use fileURLToPath is a better approach for ES modules as it handles URL encoding/decoding properly.

Also applies to: 7-7

setup.ts (1)

1167-1168: LGTM! Docker MongoDB URL is now consistent.

The Docker MongoDB URL now includes the correct parameters, ensuring consistency with non-Docker environments.

🧰 Tools
🪛 GitHub Actions: PR Workflow

[error] Unauthorized file modification or deletion attempt. This file is protected and cannot be changed.

@@ -14,7 +13,7 @@ export const connect = async (dbName?: string): Promise<void> => {

// If no connection exists, attempt to establish a new connection.
try {
await mongoose.connect(MONGO_DB_URL as string, {
await mongoose.connect(process.env.MONGO_DB_URL as string, {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for MONGO_DB_URL environment variable.

While using process.env directly is fine, we should validate that the URL is set and properly formatted before using it.

+    const mongoUrl = process.env.MONGO_DB_URL;
+    if (!mongoUrl) {
+      throw new Error('MONGO_DB_URL environment variable is not set');
+    }
-    await mongoose.connect(process.env.MONGO_DB_URL as string, {
+    await mongoose.connect(mongoUrl, {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await mongoose.connect(process.env.MONGO_DB_URL as string, {
const mongoUrl = process.env.MONGO_DB_URL;
if (!mongoUrl) {
throw new Error('MONGO_DB_URL environment variable is not set');
}
await mongoose.connect(mongoUrl, {

@Cioppolo14
Copy link
Contributor

@aakarsh-2004 Please fix the failed tests.

@aakarsh-2004
Copy link
Author

aakarsh-2004 commented Jan 21, 2025

Please add ignore-sensitive-files-pr label in this PR/issue, as I need to edit the setup.ts file. @Cioppolo14

@varshith257 varshith257 added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 21, 2025
@varshith257
Copy link
Member

@aakarsh-2004 Open a new PR against upstream develop-postgres branch. Closing for now

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.

3 participants