UNPKG

saas-smith

Version:

CLI to forge new SaaS projects effortlessly from boilerplates

97 lines (85 loc) 2.79 kB
import chalk from "chalk"; import { execSync } from "child_process"; export function setupMongoDB(projectName, ipAddresses = ["0.0.0.0/0"]) { console.log(chalk.blue("Setting up MongoDB...")); // Check if MongoDB Atlas CLI is installed try { execSync("atlas --version", { stdio: "ignore" }); } catch (error) { console.log(chalk.red("MongoDB Atlas CLI is not installed.")); process.exit(1); } // Authenticate MongoDB Atlas CLI try { execSync("atlas auth login", { stdio: "inherit" }); } catch (error) {} // Create a new MongoDB Atlas cluster try { execSync( `atlas clusters create ${projectName} --provider AWS --region US_WEST_2`, { stdio: "inherit" } ); console.log( chalk.green( `✅ MongoDB Atlas cluster "${projectName}" created successfully.` ) ); } catch (error) { console.log( chalk.red(`❌ Failed to create MongoDB Atlas cluster: ${error.message}`) ); process.exit(1); } // Set up network access try { ipAddresses.forEach((ipAddress) => { execSync(`atlas accessList create ${ipAddress}`, { stdio: "inherit" }); console.log(chalk.green(`✅ Network access set up for IP: ${ipAddress}`)); }); } catch (error) { console.log( chalk.red(`❌ Failed to set up network access: ${error.message}`) ); process.exit(1); } } function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } export async function getMongoDBConnectionString(projectName) { const maxRetries = 10; const delay = 60000; // 30 seconds console.log( chalk.blue(`Provisioning MongoDB cluster this can take 1-3 minutes...`) ); await sleep(delay * 2); for (let attempt = 1; attempt <= maxRetries; attempt++) { try { console.log( `Attempt ${attempt}: Retrieving MongoDB connection string...` ); const stdout = execSync( `atlas clusters connectionStrings describe ${projectName} --output json` ).toString(); const connectionStringJson = JSON.parse(stdout); if (connectionStringJson && connectionStringJson.standardSrv) { return connectionStringJson.standardSrv; } else { throw new Error("Connection string not found in the response."); } } catch (error) { console.log( chalk.red( `Failed to retrieve MongoDB connection string: ${error.message}` ) ); if (attempt < maxRetries) { console.log(`Retrying in ${delay / 1000} seconds...`); await sleep(delay); } else { console.log(chalk.red("Max retries reached. Exiting...")); process.exit(1); } } } }