-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
227 lines (179 loc) · 5.37 KB
/
index.js
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
#!/usr/bin/env node
import fs from 'fs'
import chalk from "chalk"
import inquirer from "inquirer"
import { getLatestVersion } from './api/api.js'
const questions = [
{
type: "input",
name: "name",
message: "Whats your project name?",
default: "myapp"
},
{
type: "confirm",
name: "useCors",
message: "Do you want to enable CORS?",
default: false
},
{
type: "confirm",
name: "useErrorHandler",
message: "Do you want to use a basic Error Handler?",
default: false
},
{
type: "confirm",
name: "useEnvFile",
message: "Do you want to use an environment file?",
default: false
},
]
const ErrorMiddleware = `import {envMode} from '../app.js'
export const errorMiddleware = (err, req, res , next)=>{
err.message||= "Internal Server Error"
err.statusCode= err.statusCode || 500
const response ={
success:false,
message:err.message,
}
if(envMode==="DEVELOPMENT"){
response.error= err
}
return res.status(err.statusCode).json(response)
}
export const TryCatch = (passedFunc)=> async(req,res,next)=>{
try{
await passedFunc(req, res, next)
}
catch(error){
next(error)
}
}
`
const ErrorHandler = `export default class ErrorHandler extends Error{
constructor(message , statusCode){
super(message)
this.statusCode = statusCode
}
}
`
async function createApp() {
try {
const answer = await inquirer.prompt(questions)
const projectName = answer.name
const dir = `${process.cwd()}/${projectName}`;
const fileExtension = "js"
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
fs.mkdirSync(`${dir}/routes`)
fs.mkdirSync(`${dir}/models`)
fs.mkdirSync(`${dir}/controllers`)
fs.mkdirSync(`${dir}/middlewares`)
fs.mkdirSync(`${dir}/utils`)
fs.mkdirSync(`${dir}/lib`)
}
if (answer.useErrorHandler) {
fs.writeFileSync(`${dir}/middlewares/error.js`, ErrorMiddleware)
fs.writeFileSync(`${dir}/utils/errorHandler.js`, ErrorHandler)
}
const importLines = ['import express from "express"']
const middlewareLines = [
`app.use(express.json())`,
`app.use(express.urlencoded({extended:true}))`
]
if (answer.useCors) {
importLines.push(`import cors from "cors"`)
middlewareLines.push(`app.use(cors({
origin:"*',
credentials:true
}))`)
}
if (answer.useErrorHandler) {
importLines.push(`import {errorMiddleware} from './middleware/error.js'`)
}
if (answer.useEnvFile) {
importLines.push(`import dotenv from 'dotenv`)
const envFileContent = `PORT=4000`
fs.writeFileSync(`${dir}/.env`, envFileContent)
}
const baseFileContent = `${importLines.join("\n")}
${answer.useEnvFile ? "dotenv.config({path: './.env',})" : ""}
export const envMode = process.env.NODE_ENV?.trim() || 'DEVELOPMENT'
const port = process.env.PORT || 3000
const app = express()
${middlewareLines.join("\n")}
app.get('/', (req, res) => {
res.send('Hello, World!')
})
// Define your routes here
app.get("*", (req, res) => {
res.status(404).json({
success: false,
message: 'Page not found'
})
})
${answer.useErrorHandler ? "app.use(errorMiddleware)" : ""}
app.listen(port, () => console.log('Server is working on Port:'+port+' in '+envMode+' Mode.'))`
fs.writeFileSync(`${dir}/app.${fileExtension}`, baseFileContent)
const dependenciesPromise = [getLatestVersion("express")]
if (answer.useCors)
dependenciesPromise.push(getLatestVersion("cors"))
if (answer.useEnvFile)
dependenciesPromise.push(getLatestVersion("dotenv"));
const devDependenciesPromise = [
getLatestVersion("nodemon"),
]
const dependenciesRaw = await Promise.all(dependenciesPromise);
const devDependenciesRaw = await Promise.all(devDependenciesPromise);
const dependencies = dependenciesRaw.map(
(dependency) => `"${dependency.name}": "${dependency.version}"`
);
const devDependencies = devDependenciesRaw.map(
(dependency) => `"${dependency.name}": "${dependency.version}"`
);
const npmScriptsJs = JSON.stringify({
start: "set NODE_ENV=PRODUCTION & node app.js",
dev: "npx nodemon app.js",
});
const packageJsonContent = `{
"name": "${projectName}",
"version": "1.0.0",
"description": "",
"main": ${'"app.js"'},
"scripts": ${npmScriptsJs
}
,
"keywords": [],
"author": "",
"type": "module",
"license": "ISC",
"dependencies": {
${dependencies.join(",")}
},
"devDependencies": {
${devDependencies[0]
}
}
}`;
fs.writeFileSync(`${dir}/package.json`, packageJsonContent);
console.log("\n");
console.log(
chalk.bgWhite(
chalk.black(` 🎉 Project '${projectName}' created successfully! 🎉 `)
)
);
console.log("\n");
console.log(chalk.magentaBright(chalk.italic("Next Steps:")));
console.log(chalk.bold(`-> cd ${projectName}`));
console.log(chalk.bold(`-> npm install \n`));
console.log(chalk.greenBright(chalk.italic("Start your server: ")));
console.log(chalk.bold(`1- npm run dev 🚀\n`));
} catch (error) {
console.error(error);
}
}
createApp().catch((err) => {
console.error(err)
}
)