-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
379 lines (337 loc) Β· 14.1 KB
/
Copy pathindex.js
File metadata and controls
379 lines (337 loc) Β· 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env node
// --------------------
// π οΈ Imports & Setup
// --------------------
const { default: inquirer } = require("inquirer");
const fs = require('fs-extra');
const path = require('path');
const ejs = require('ejs');
const { execSync } = require('child_process');
const chalk = require('chalk');
const { default: ora } = require("ora");
console.log(chalk.cyanBright("π Welcome to Create Node Backend CLI!\n"));
// --------------------
// π Prompt User
// --------------------
inquirer.prompt([
{
type: 'input',
name: 'projectName',
message: 'Enter your project name:',
default: 'my-node-backend',
},
{
type: 'list',
name: 'language',
message: 'Which language do you want to use?',
choices: ['JavaScript', 'TypeScript'],
},
{
type: 'list',
name: 'database',
message: 'Which database do you want to use?',
choices: ['MongoDB', 'PostgreSQL', 'None'],
},
{
type: 'confirm',
name: 'auth',
message: 'Do you want to include JWT authentication?',
default: true,
},
{
type: 'checkbox',
name: 'middleware',
message: 'Which middleware do you want to include?',
choices: ['CORS', 'Helmet', 'Rate Limiting'],
},
{
type: 'confirm',
name: 'logging',
message: 'Do you want to include logging setup (winston/morgan)?',
default: true,
},
{
type: 'checkbox',
name: 'folders',
message: 'Select which folders to include in your project structure:',
choices: [
{ name: 'controllers', checked: true },
{ name: 'routes', checked: true },
{ name: 'middlewares', checked: true },
{ name: 'models', checked: true },
{ name: 'config', checked: true }
],
},
{
type: 'confirm',
name: 'linting',
message: 'Do you want to add ESLint and Prettier setup?',
default: true
}
]).then(async (answers) => {
// const projectPath = path.join(process.cwd(), answers.projectName);
const projectName = answers.projectName;
let projectPath = path.join(process.cwd(), projectName);
// Check if the user entered '.' (current directory)
if (projectName === '.') {
projectPath = process.cwd(); // Use the current directory as the project path
}
// Check if the project folder already exists
if (fs.existsSync(projectPath)) {
console.error(chalk.red(`β The folder '${projectName}' already exists. Please choose a different name or use '.' for the current directory.`));
process.exit(1); // Exit the process with an error code
}
// try {
// // Create the project folder
// await fs.mkdir(projectPath);
// // Continue with creating subfolders and files...
// } catch (error) {
// console.error(chalk.red(`β Error creating project folder: ${error.message}`));
// process.exit(1); // Exit if an error occurs
// }
try {
// --------------------
// π Create Folder Structure
// --------------------
// await fs.mkdirp(path.join(projectPath, 'src', 'controllers'));
// await fs.mkdirp(path.join(projectPath, 'src', 'routes'));
// await fs.mkdirp(path.join(projectPath, 'src', 'middlewares'));
// await fs.mkdirp(path.join(projectPath, 'src', 'models'));
// await fs.mkdirp(path.join(projectPath, 'src', 'config'));
// Create project folder
await fs.mkdir(projectPath);
// Create src and subfolders
await fs.mkdir(path.join(projectPath, 'src'));
for (const folder of answers.folders) {
await fs.mkdir(path.join(projectPath, 'src', folder));
}
// --------------------
// π Render Database Config
// --------------------
const dbContent = await ejs.renderFile(
path.join(__dirname, 'templates', 'db.js.ejs'),
{ database: answers.database }
);
await fs.outputFile(path.join(projectPath, 'src', 'config', 'db.js'), dbContent.trim());
// --------------------
// π€ Render User Model
// --------------------
const userModel = await ejs.renderFile(
path.join(__dirname, 'templates', 'user.model.js.ejs'),
{ database: answers.database }
);
await fs.outputFile(path.join(projectPath, 'src', 'models', 'user.model.js'), userModel.trim());
// --------------------
// π Add Auth if selected
// --------------------
if (answers.auth) {
const authController = await ejs.renderFile(
path.join(__dirname, 'templates', 'auth.controller.js.ejs'),
answers
);
const authMiddleware = await ejs.renderFile(
path.join(__dirname, 'templates', 'auth.middleware.js.ejs'),
answers
);
await fs.outputFile(path.join(projectPath, 'src', 'controllers', 'auth.controller.js'), authController.trim());
await fs.outputFile(path.join(projectPath, 'src', 'middlewares', 'auth.middleware.js'), authMiddleware.trim());
}
// --------------------
// π± Generate .env file
// --------------------
const envContent = `
PORT=3000
MONGO_URI=mongodb://localhost:27017/${answers.projectName}
JWT_SECRET=your_jwt_secret
`.trim();
await fs.outputFile(path.join(projectPath, '.env'), envContent);
// --------------------
// π§ Generate app.js or app.ts
// --------------------
const appFileName = answers.language === 'TypeScript' ? 'app.ts' : 'app.js';
const appTemplatePath = path.join(__dirname, 'templates', appFileName === 'app.ts' ? 'app.ts.ejs' : 'app.js.ejs');
const templateData = {
projectName: answers.projectName,
middleware: answers.middleware,
logging: answers.logging,
linting: answers.linting
};
const renderedApp = await ejs.renderFile(appTemplatePath, templateData);
await fs.writeFile(path.join(projectPath, 'src', appFileName), renderedApp.trim());
// Docker setup
// Write the Dockerfile to the project folder
// await fs.outputFile(path.join(projectPath, 'Dockerfile'), dockerfileContent);
// console.log('π³ Dockerfile created successfully!');
// Render Dockerfile using EJS template
const dockerfileContent = await ejs.renderFile(
path.join(__dirname, 'templates', 'dockerfile.ejs'), // path to the Dockerfile EJS template
{} // You can pass any dynamic data if needed in the template
);
// Write the Dockerfile to the project folder
await fs.outputFile(path.join(projectPath, 'Dockerfile'), dockerfileContent.trim());
console.log('π³ Dockerfile created successfully!');
const dockerignoreContent = await ejs.renderFile(
path.join(__dirname, 'templates', 'dockerignore.ejs'), // path to the Dockerfile EJS template
{} // You can pass any dynamic data if needed in the template
);
// Write the .dockerignore file to the project folder
await fs.outputFile(path.join(projectPath, '.dockerignore'), dockerignoreContent);
console.log('π³ .dockerignore created successfully!');
// --------------------
// π¦ Generate package.json from template
// --------------------
console.log('\nπ οΈ Initializing package.json...\n');
const pkgJsonContent = await ejs.renderFile(
path.join(__dirname, 'templates', 'package.json.ejs'),
answers
);
await fs.outputFile(path.join(projectPath, 'package.json'), pkgJsonContent.trim());
if (answers.linting) {
const lintingTemplates = ['.eslintrc.js', '.prettierrc'];
for (const file of lintingTemplates) {
const rendered = await ejs.renderFile(
path.join(__dirname, 'templates', 'linting', `${file}.ejs`),
{ language: answers.language }
);
await fs.outputFile(path.join(projectPath, file), rendered);
}
await fs.outputFile(path.join(projectPath, '.eslintignore'), 'node_modules\ndist\n');
await fs.outputFile(path.join(projectPath, '.prettierignore'), 'node_modules\ndist\n');
}
// --------------------
// π¦ Install Dependencies
// --------------------
const dependencies = ['express'];
const devDependencies = [];
if (answers.database === 'MongoDB') {
dependencies.push('mongoose');
} else if (answers.database === 'PostgreSQL') {
dependencies.push('@prisma/client', 'prisma');
}
if (answers.auth) {
dependencies.push('jsonwebtoken', 'bcryptjs', 'dotenv');
}
if (answers.middleware.includes('CORS')) {
dependencies.push('cors');
}
if (answers.middleware.includes('Helmet')) {
dependencies.push('helmet');
}
if (answers.middleware.includes('Rate Limiting')) {
dependencies.push('express-rate-limit');
}
if (answers.language === 'TypeScript') {
devDependencies.push('typescript', 'ts-node-dev', '@types/node', '@types/express');
}
if (answers.logging) {
dependencies.push('winston', 'morgan');
}
if (answers.logging) {
const loggerContent = await ejs.renderFile(
path.join(__dirname, 'templates', 'config', 'logger.js.ejs')
);
await fs.outputFile(path.join(projectPath, 'src', 'config', 'logger.js'), loggerContent.trim());
}
if (answers.linting) {
if (answers.language === 'TypeScript') {
devDependencies.push(
'eslint',
'prettier',
'eslint-config-prettier',
'eslint-plugin-prettier',
'@typescript-eslint/parser',
'@typescript-eslint/eslint-plugin',
'typescript'
);
} else {
devDependencies.push(
'eslint',
'prettier',
'eslint-config-prettier',
'eslint-plugin-prettier'
);
}
}
// console.log(chalk.yellow(`\nπ¦ Installing dependencies: ${dependencies.join(', ')}\n`));
const spinner = ora(`Installing dependencies: ${dependencies.join(', ')}`).start();
try {
execSync(`npm install ${dependencies.join(' ')}`, {
cwd: projectPath,
stdio: 'inherit'
});
spinner.succeed('Dependencies installed successfully!');
} catch (installError) {
spinner.fail('Failed to install dependencies');
console.error(chalk.red(installError));
}
if (devDependencies.length > 0) {
console.log(chalk.yellow(`\nπ¦ Installing dependencies: ${dependencies.join(', ')}\n`));
execSync(`npm install -D ${devDependencies.join(' ')}`, {
cwd: projectPath,
stdio: 'inherit'
});
}
// --------------------
// π§ Initialize Prisma if PostgreSQL
// --------------------
if (answers.database === 'PostgreSQL') {
console.log('\nβοΈ Initializing Prisma...\n');
execSync(`npx prisma init`, {
cwd: projectPath,
stdio: 'inherit'
});
}
// --------------------
// π Create tsconfig.json if TypeScript
// --------------------
if (answers.language === 'TypeScript') {
console.log('\nπ Creating tsconfig.json...\n');
const tsConfig = {
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
};
await fs.writeJson(path.join(projectPath, 'tsconfig.json'), tsConfig, { spaces: 2 });
}
// --------------------
// 𧬠Initialize Git
// --------------------
const gitignoreContent = await ejs.renderFile(
path.join(__dirname, 'templates', 'gitignore.ejs'), // path to the Dockerfile EJS template
{} // You can pass any dynamic data if needed in the template
);
await fs.outputFile(path.join(projectPath, '.gitignore'), gitignoreContent);
console.log('\nπ§ Initializing Git repository...\n');
try {
execSync(`git init`, { cwd: projectPath, stdio: 'inherit' });
execSync(`git add .`, { cwd: projectPath, stdio: 'inherit' });
execSync(`git commit -m "Initial commit"`, { cwd: projectPath, stdio: 'inherit' });
console.log('β
Git repo initialized!');
} catch (gitError) {
console.error('β οΈ Failed to initialize Git:', gitError.message);
}
// --------------------
// π Done!
// --------------------
console.log(`\nπ Project '${answers.projectName}' created and setup complete!`);
console.log(`π Location: ${projectPath}`);
console.log(`π Start coding:\n`);
console.log(` cd ${answers.projectName}`);
console.log(` npm start\n`);
// Docker build & run instructions
console.log(`π³ Docker instructions:`);
console.log(` To build the Docker image:`);
console.log(` docker build -t ${answers.projectName} .`);
console.log(` To run the Docker container:`);
console.log(` docker run -p 3000:3000 ${answers.projectName}`);
} catch (error) {
console.error(chalk.red('β Error creating project:', error));
}
});