Skip to content

Commit b31af99

Browse files
feat: add database selection and MongoDB setup; enhance environment configuration
1 parent a254a1c commit b31af99

File tree

5 files changed

+155
-28
lines changed

5 files changed

+155
-28
lines changed

src/commands/init.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { setupESLintConfig } from "../tasks/setUpEslint.js";
55
import { setupFolderStructure } from "../tasks/setUpFolderStructure.js";
66
import { setupEnv } from "../tasks/setupEnv.js";
77
import { configureIndex } from "../tasks/configureIndex.js";
8+
import { setupDb } from "../tasks/setupDb.js";
89
const project = async () => {
910

1011
try {
@@ -17,6 +18,7 @@ const project = async () => {
1718
await installDependencies({ ...projectDetails });
1819

1920

21+
2022
if (projectDetails.features.includes('eslint')) {
2123

2224

@@ -26,9 +28,19 @@ const project = async () => {
2628

2729
await setupFolderStructure(projectDetails.projectName);
2830

29-
await setupEnv(projectDetails.language);
31+
if (projectDetails.database === "MongoDB") {
32+
33+
await setupDb(projectDetails.projectName, projectDetails.language);
34+
await configureIndex(projectDetails.projectName, projectDetails.language, projectDetails.framework, projectDetails.database);
35+
} else {
36+
await configureIndex(projectDetails.projectName, projectDetails.language, projectDetails.framework, null);
37+
}
38+
39+
await setupEnv(projectDetails.projectName, projectDetails.language);
40+
41+
42+
3043

31-
await configureIndex(projectDetails.projectName, projectDetails.language, projectDetails.framework);
3244

3345
return projectDetails.projectName;
3446
} catch (error) {

src/prompts/prompts.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ async function askProjectDetails() {
2828
choices: ["none", "Express"],
2929
default: "none",
3030
},
31+
{
32+
type: "list",
33+
name: "database",
34+
message: "Choose the database:",
35+
choices: ["none", "MongoDB"],
36+
default: "none",
37+
},
3138
{
3239
type: "checkbox",
3340
name: "features",

src/tasks/configureIndex.js

Lines changed: 70 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import path from "path";
22
import { writeFile } from "../utils/fileSystem.js";
33
import { logSuccess } from "../utils/logger.js";
44

5-
export async function configureIndex(projectName, language, framework) {
5+
export async function configureIndex(projectName, language, framework, database) {
66
try {
77
const isTS = language === "TypeScript";
88
const extension = isTS ? "ts" : "js";
@@ -13,41 +13,39 @@ export async function configureIndex(projectName, language, framework) {
1313
indexContent = isTS
1414
? `
1515
import express, { Request, Response } from 'express';
16-
import dotenv from 'dotenv';
17-
18-
dotenv.config();
16+
import ENV from "./config/env.config";
17+
${database ? `import connectDB from './config/db.config';` : ''}
1918
2019
const app = express();
2120
2221
app.get('/', (req: Request, res: Response) => {
2322
res.send('Hello from ${projectName} backend!');
2423
});
2524
26-
const port = process.env.PORT || 3000;
27-
app.listen(port, () =>
28-
console.log('🚀 Server running on http://localhost:' + port)
29-
);
25+
const port: number = ENV.PORT || 3000;
26+
{{APP_LISTEN}};
3027
`
3128
: `
3229
import express from 'express';
33-
import dotenv from 'dotenv';
34-
35-
dotenv.config();
30+
import ENV from "./config/env.config.js";
31+
${database ? `import connectDB from './config/db.config.js';` : ''}
3632
3733
const app = express();
3834
app.use(express.json());
3935
4036
app.get('/', (req, res) => res.send('Hello from ${projectName} backend!'));
4137
42-
const port = process.env.PORT || 3000;
43-
app.listen(port, () => console.log('🚀 Server running on http://localhost:' + port));
38+
const port = ENV.PORT || 3000;
39+
{{APP_LISTEN}};
4440
`;
4541
} else {
4642
indexContent = isTS
4743
? `
4844
import http, { IncomingMessage, ServerResponse } from 'http';
45+
import ENV from "./config/env.config";
46+
${database ? `import connectDB from './config/db.config';` : ''}
4947
50-
const server = http.createServer((req: IncomingMessage, res: ServerResponse) => {
48+
const app = http.createServer((req: IncomingMessage, res: ServerResponse) => {
5149
if (req.url === '/' && req.method === 'GET') {
5250
res.writeHead(200, { 'Content-Type': 'text/plain' });
5351
res.end('Hello from ${projectName} backend!');
@@ -57,15 +55,15 @@ const server = http.createServer((req: IncomingMessage, res: ServerResponse) =>
5755
}
5856
});
5957
60-
const PORT = process.env.PORT || 3000;
61-
server.listen(PORT, () => {
62-
console.log(\`🚀 Server running on http://localhost:\${PORT}\`);
63-
});
58+
const PORT: number = ENV.PORT || 3000;
59+
{{APP_LISTEN}};
6460
`
6561
: `
6662
import http from 'http';
63+
import ENV from "./config/env.config.js";
64+
${database ? `import connectDB from './config/db.config.js';` : ''}
6765
68-
const server = http.createServer((req, res) => {
66+
const app = http.createServer((req, res) => {
6967
if (req.url === '/' && req.method === 'GET') {
7068
res.writeHead(200, { 'Content-Type': 'text/plain' });
7169
res.end('Hello from ${projectName} backend!');
@@ -75,15 +73,64 @@ const server = http.createServer((req, res) => {
7573
}
7674
});
7775
78-
const PORT = process.env.PORT || 3000;
79-
server.listen(PORT, () => {
80-
console.log(\`🚀 Server running on http://localhost:\${PORT}\`);
76+
const PORT = ENV.PORT || 3000;
77+
{{APP_LISTEN}}
78+
`;
79+
}
80+
81+
// 🔥 NOW: inject the APP_LISTEN logic
82+
let appListenLogic = '';
83+
84+
if (database) {
85+
if (framework === 'Express') {
86+
appListenLogic = isTS
87+
? `
88+
connectDB().then(() => {
89+
app.listen(port, () => console.log(\`🚀 Server running on port \${port}\`));
90+
}).catch((err: any) => {
91+
console.error('❌ Failed to connect to DB:', err);
92+
});
93+
`
94+
: `
95+
connectDB().then(() => {
96+
app.listen(port, () => console.log(\`🚀 Server running on port \${port}\`));
97+
}).catch((err) => {
98+
console.error('❌ Failed to connect to DB:', err);
8199
});
100+
`;
101+
} else {
102+
appListenLogic = isTS
103+
? `
104+
connectDB().then(() => {
105+
app.listen(PORT, () => console.log(\`🚀 Server running on port \${PORT}\`));
106+
}).catch((err: any) => {
107+
console.error('❌ Failed to connect to DB:', err);
108+
});
109+
`
110+
: `
111+
connectDB().then(() => {
112+
app.listen(PORT, () => console.log(\`🚀 Server running on port \${PORT}\`));
113+
}).catch((err) => {
114+
console.error('❌ Failed to connect to DB:', err);
115+
});
116+
`;
117+
}
118+
} else {
119+
if (framework === 'Express') {
120+
appListenLogic = `
121+
app.listen(port, () => console.log(\`🚀 Server running on port \${port}\`));
82122
`;
123+
} else {
124+
appListenLogic = `
125+
app.listen(PORT, () => console.log(\`🚀 Server running on port \${PORT}\`));
126+
`;
127+
}
83128
}
84129

85-
const indexPath = path.join(process.cwd(), "src", `index.${extension}`);
130+
// 🪄 Replace the placeholder with the actual logic
131+
indexContent = indexContent.replace('{{APP_LISTEN}}', appListenLogic.trim());
86132

133+
const indexPath = path.join(process.cwd(), "src", `index.${extension}`);
87134
await writeFile(indexPath, indexContent.trim(), "utf-8");
88135

89136
logSuccess(`✅ Created src/index.${extension}`);

src/tasks/setupDb.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { writeFile } from "../utils/fileSystem.js";
2+
import path from "path";
3+
import { exec } from "child_process";
4+
import { promisify } from "util";
5+
const execPromise = promisify(exec);
6+
export async function setupDb(projectName, language) {
7+
try {
8+
9+
10+
await execPromise("npm install mongoose", { stdio: "ignore" });
11+
12+
const extension = language === "TypeScript" ? "ts" : "js";
13+
14+
const configDbPath = path.join(process.cwd(), "src", "config", `db.config.${extension}`);
15+
16+
const configDbContent = language === "TypeScript" ? `import mongoose from "mongoose";
17+
import ENV from "./env.config";
18+
19+
const connectDB = async () => {
20+
try {
21+
await mongoose.connect(ENV.MONGO_URI);
22+
console.log("MongoDB connected successfully");
23+
} catch (err) {
24+
console.error("Error connecting to MongoDB:", err);
25+
process.exit(1);
26+
}
27+
};
28+
29+
export default connectDB;
30+
`: `import mongoose from "mongoose";
31+
import ENV from "./env.config.js";
32+
33+
const connectDB = async () => {
34+
try {
35+
await mongoose.connect(ENV.MONGO_URI);
36+
console.log("MongoDB connected successfully");
37+
} catch (err) {
38+
console.error("Error connecting to MongoDB:", err);
39+
process.exit(1);
40+
}
41+
};
42+
43+
export default connectDB;
44+
`;
45+
46+
writeFile(configDbPath, configDbContent.trim(), "utf-8")
47+
48+
}
49+
50+
51+
catch (error) {
52+
53+
throw new error;
54+
55+
}
56+
57+
}

src/tasks/setupEnv.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { writeFile } from "../utils/fileSystem.js";
22
import path from "path";
33

4-
export async function setupEnv(language) {
4+
5+
export async function setupEnv(projectName, language) {
56
try {
67

78
const extension = language === "TypeScript" ? "ts" : "js";
89

910
const envContent = `
10-
PORT=3000
11+
PORT=3000
12+
MONGO_URI=mongodb+srv://<username>::<password>@cluster0.m8oca.mongodb.net/<database_name>?retryWrites=true&w=majority&appName=Cluster0
1113
`;
1214

1315
const envPath = path.join(process.cwd(), ".env");
@@ -24,6 +26,7 @@ export async function setupEnv(language) {
2426
2527
const ENV : any = {
2628
PORT: process.env.PORT || 3000,
29+
MONGO_URI: process.env.MONGO_URI
2730
};
2831
2932
export default ENV;
@@ -36,13 +39,14 @@ export default ENV;
3639
3740
const ENV = {
3841
PORT: process.env.PORT || 3000,
42+
MONGO_URI: process.env.MONGO_URI
3943
};
4044
4145
export default ENV;
4246
4347
`;
4448

45-
await writeFile(configEnvPath, configEnvContent.trim(), "utf-8")
49+
writeFile(configEnvPath, configEnvContent.trim(), "utf-8")
4650

4751
}
4852

0 commit comments

Comments
 (0)