-
-
Notifications
You must be signed in to change notification settings - Fork 963
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
base: develop
Are you sure you want to change the base?
Conversation
WalkthroughThe pull request modifies the Changes
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Poem
Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
There was a problem hiding this 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
📒 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
andfileURLToPath
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Remember to add tests.
- We can't have this again
Yes I'm writing tests now. |
There was a problem hiding this 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:
- Error handling for failed data imports
- Rollback mechanism for partial import failures
- 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
andsuperAdmin
functions, but this file is testing theaskForTransactionLogPath
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:
- Verify that
inquirer.prompt
was called exactly twice- 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:
- The default path shown in the prompt message should match the actual default path used in
transactionLogPath
- 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:
- Move timeout values to constants
- Add health checks for Redis and MinIO services
- 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
📒 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
anddirname
for path resolution while maintaining the existing functionality.
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## develop #2845 +/- ##
========================================
Coverage 97.72% 97.72%
========================================
Files 364 364
Lines 18569 18569
Branches 2682 2682
========================================
Hits 18147 18147
Misses 417 417
Partials 5 5 ☔ View full report in Codecov by Sentry. |
What kind of change does this PR introduce?
Bug in setup.ts
Issue Number:
Fixes #2829
Snapshots/Videos:
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
Test Coverage
Other information
Have you read the contributing guide?
Summary by CodeRabbit