create-api-structure 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +132 -2
- package/bin/cli.js +64 -0
- package/package.json +41 -4
- package/src/constants.js +32 -0
- package/src/prompt.js +141 -0
- package/src/scaffold.js +120 -0
- package/src/templates/config.js +37 -0
- package/src/templates/controllers.js +144 -0
- package/src/templates/index.js +23 -0
- package/src/templates/middlewares.js +154 -0
- package/src/templates/models.js +81 -0
- package/src/templates/root.js +254 -0
- package/src/templates/routes.js +36 -0
- package/src/templates/utils.js +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pratiksonaniya2-del
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,133 @@
|
|
|
1
|
-
#
|
|
1
|
+
# create-api-structure
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A zero-dependency CLI tool to scaffold a production-ready **ES Module (`import/export`) Express + MongoDB** backend with a complete MVC folder layout, starter files, JWT authentication, Multer file uploads, security middleware, and automatic dependency installation.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Zero CLI Dependencies** — Fast `npx` / `npm create` startup with no external packages required by the generator itself.
|
|
10
|
+
- **Modern ES Modules (`"type": "module"`)** — Clean `import`/`export` syntax across every generated file (Express v5 + Mongoose v9 ready).
|
|
11
|
+
- **All Essential Dependencies Installed Automatically**:
|
|
12
|
+
- `express`, `mongoose`, `bcryptjs`, `jsonwebtoken`, `dotenv`, `cors`, `helmet`, `morgan`, `cookie-parser`, `multer`
|
|
13
|
+
- `nodemon` in `devDependencies`
|
|
14
|
+
- **Complete MVC Folder & File Structure**:
|
|
15
|
+
- Root: `.env`, `.env.example`, `.gitignore`, `app.js`, `server.js`, `package.json`, `README.md`
|
|
16
|
+
- `config/`: `db.js`, `env.js`
|
|
17
|
+
- `models/`: `user.model.js`
|
|
18
|
+
- `controllers/`: `auth.controller.js`, `health.controller.js`
|
|
19
|
+
- `routes/`: `auth.routes.js`, `health.routes.js`
|
|
20
|
+
- `middlewares/`: `auth.middleware.js`, `error.middleware.js`, `multer.middleware.js`
|
|
21
|
+
- `utils/`: `ApiError.js`, `ApiResponse.js`, `asyncHandler.js`
|
|
22
|
+
- `uploads/`: `.gitkeep`
|
|
23
|
+
- **Auto-generated Secure `JWT_SECRET`** inside `.env`.
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
Run directly with `npm create`:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
npm create api-structure my-backend
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Or with `npx`:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx create-api-structure my-backend
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or initialize inside the current directory:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npx create-api-structure .
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or install globally:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install -g create-api-structure
|
|
51
|
+
create-api-structure my-backend
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### CLI Options
|
|
55
|
+
|
|
56
|
+
| Flag | Description |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| `-y, --yes` | Skip interactive prompts and use defaults |
|
|
59
|
+
| `-p, --port <number>` | Set `PORT` in `.env` (default: `5000`) |
|
|
60
|
+
| `--no-install` | Create folders & files without running `npm install` |
|
|
61
|
+
| `--force` | Overwrite existing conflicting files in target folder |
|
|
62
|
+
| `-h, --help` | Show CLI help |
|
|
63
|
+
| `-v, --version` | Show CLI version |
|
|
64
|
+
|
|
65
|
+
Example non-interactive setup:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
npx create-api-structure my-api -y -p 8000
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Generated Project Structure
|
|
74
|
+
|
|
75
|
+
```text
|
|
76
|
+
my-backend/
|
|
77
|
+
├── config/
|
|
78
|
+
│ ├── db.js
|
|
79
|
+
│ └── env.js
|
|
80
|
+
├── controllers/
|
|
81
|
+
│ ├── auth.controller.js
|
|
82
|
+
│ └── health.controller.js
|
|
83
|
+
├── middlewares/
|
|
84
|
+
│ ├── auth.middleware.js
|
|
85
|
+
│ ├── error.middleware.js
|
|
86
|
+
│ └── multer.middleware.js
|
|
87
|
+
├── models/
|
|
88
|
+
│ └── user.model.js
|
|
89
|
+
├── routes/
|
|
90
|
+
│ ├── auth.routes.js
|
|
91
|
+
│ └── health.routes.js
|
|
92
|
+
├── uploads/
|
|
93
|
+
│ └── .gitkeep
|
|
94
|
+
├── utils/
|
|
95
|
+
│ ├── ApiError.js
|
|
96
|
+
│ ├── ApiResponse.js
|
|
97
|
+
│ └── asyncHandler.js
|
|
98
|
+
├── .env
|
|
99
|
+
├── .env.example
|
|
100
|
+
├── .gitignore
|
|
101
|
+
├── app.js
|
|
102
|
+
├── package.json
|
|
103
|
+
├── README.md
|
|
104
|
+
└── server.js
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Local Development & Publishing
|
|
110
|
+
|
|
111
|
+
1. Run the automated test suite:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
npm test
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
2. Inspect the exact files that will be included in the npm tarball:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
npm pack --dry-run
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
3. Publish to npm:
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
npm publish
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { DEPENDENCIES, DEV_DEPENDENCIES } from "../src/constants.js";
|
|
6
|
+
import { collectOptions, color, parseArgs } from "../src/prompt.js";
|
|
7
|
+
import { scaffoldProject } from "../src/scaffold.js";
|
|
8
|
+
|
|
9
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
10
|
+
const __dirname = path.dirname(__filename);
|
|
11
|
+
const pkg = JSON.parse(
|
|
12
|
+
fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8")
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
function printHelp() {
|
|
16
|
+
const cliName = pkg.name;
|
|
17
|
+
console.log(`
|
|
18
|
+
${color.bold(cliName)} v${pkg.version}
|
|
19
|
+
Scaffold an ES Module Express + MongoDB backend with MVC folders, starter files, and dependencies.
|
|
20
|
+
|
|
21
|
+
${color.bold("Usage:")}
|
|
22
|
+
npx ${cliName} [project-folder] [options]
|
|
23
|
+
npx ${cliName} . [options]
|
|
24
|
+
|
|
25
|
+
${color.bold("Options:")}
|
|
26
|
+
-y, --yes Skip prompts and use default values
|
|
27
|
+
-p, --port <num> Set initial PORT in .env (default: 5000)
|
|
28
|
+
--no-install Generate structure without running npm install
|
|
29
|
+
--force Overwrite conflicting files in target folder
|
|
30
|
+
-h, --help Show this help message
|
|
31
|
+
-v, --version Show package version
|
|
32
|
+
|
|
33
|
+
${color.bold("Included Packages:")}
|
|
34
|
+
Dependencies: ${Object.keys(DEPENDENCIES).join(", ")}
|
|
35
|
+
DevDependencies: ${Object.keys(DEV_DEPENDENCIES).join(", ")}
|
|
36
|
+
`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function main() {
|
|
40
|
+
const parsed = parseArgs(process.argv.slice(2));
|
|
41
|
+
|
|
42
|
+
if (parsed.help) {
|
|
43
|
+
printHelp();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (parsed.version) {
|
|
48
|
+
console.log(`${pkg.name} v${pkg.version}`);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
console.log(color.bold(color.cyan(`\n${pkg.name} v${pkg.version}\n`)));
|
|
53
|
+
const options = await collectOptions(parsed);
|
|
54
|
+
await scaffoldProject(options);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
main().catch((error) => {
|
|
58
|
+
if (error?.name === "AbortError") {
|
|
59
|
+
console.log(color.yellow("\nCancelled."));
|
|
60
|
+
process.exit(130);
|
|
61
|
+
}
|
|
62
|
+
console.error(color.red(`\nError: ${error.message}`));
|
|
63
|
+
process.exit(1);
|
|
64
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-api-structure",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-dependency CLI to scaffold a production-ready ES Module Express + MongoDB backend with MVC folders, JWT auth, Multer, security middleware, and automatic dependency installation.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"create-api-structure": "./bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"start": "node ./bin/cli.js",
|
|
17
|
+
"test": "node --test",
|
|
18
|
+
"prepublishOnly": "node --test"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"express",
|
|
22
|
+
"mongodb",
|
|
23
|
+
"mongoose",
|
|
24
|
+
"backend",
|
|
25
|
+
"boilerplate",
|
|
26
|
+
"scaffolder",
|
|
27
|
+
"cli",
|
|
28
|
+
"starter",
|
|
29
|
+
"mvc",
|
|
30
|
+
"jwt",
|
|
31
|
+
"bcrypt",
|
|
32
|
+
"esm",
|
|
33
|
+
"nodejs"
|
|
34
|
+
],
|
|
35
|
+
"author": "pratiksonaniyaiam",
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18.0.0"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/constants.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const DEFAULT_CONFIG = {
|
|
2
|
+
projectName: "express-mongo-backend",
|
|
3
|
+
port: 5000,
|
|
4
|
+
mongoUri: "mongodb://127.0.0.1:27017",
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export const DEPENDENCIES = {
|
|
8
|
+
express: "^5.0.0",
|
|
9
|
+
mongoose: "^9.0.0",
|
|
10
|
+
bcryptjs: "^3.0.0",
|
|
11
|
+
jsonwebtoken: "^9.0.2",
|
|
12
|
+
dotenv: "^18.0.0",
|
|
13
|
+
cors: "^2.8.5",
|
|
14
|
+
helmet: "^8.0.0",
|
|
15
|
+
morgan: "^1.10.0",
|
|
16
|
+
"cookie-parser": "^1.4.7",
|
|
17
|
+
multer: "^2.0.0",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const DEV_DEPENDENCIES = {
|
|
21
|
+
nodemon: "^3.1.9",
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const PROJECT_FOLDERS = [
|
|
25
|
+
"config",
|
|
26
|
+
"controllers",
|
|
27
|
+
"middlewares",
|
|
28
|
+
"models",
|
|
29
|
+
"routes",
|
|
30
|
+
"uploads",
|
|
31
|
+
"utils",
|
|
32
|
+
];
|
package/src/prompt.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import readline from "node:readline/promises";
|
|
2
|
+
import { stdin as input, stdout as output } from "node:process";
|
|
3
|
+
import { DEFAULT_CONFIG } from "./constants.js";
|
|
4
|
+
|
|
5
|
+
const useColor = Boolean(process.stdout.isTTY && !process.env.NO_COLOR);
|
|
6
|
+
|
|
7
|
+
const wrap = (code) => (text) => (useColor ? `\x1b[${code}m${text}\x1b[0m` : String(text));
|
|
8
|
+
|
|
9
|
+
export const color = {
|
|
10
|
+
bold: wrap("1"),
|
|
11
|
+
dim: wrap("2"),
|
|
12
|
+
red: wrap("31"),
|
|
13
|
+
green: wrap("32"),
|
|
14
|
+
yellow: wrap("33"),
|
|
15
|
+
cyan: wrap("36"),
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function parseArgs(argv) {
|
|
19
|
+
const result = {
|
|
20
|
+
targetDir: null,
|
|
21
|
+
yes: false,
|
|
22
|
+
install: true,
|
|
23
|
+
force: false,
|
|
24
|
+
port: null,
|
|
25
|
+
help: false,
|
|
26
|
+
version: false,
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
30
|
+
const arg = argv[i];
|
|
31
|
+
|
|
32
|
+
if (arg === "-h" || arg === "--help") {
|
|
33
|
+
result.help = true;
|
|
34
|
+
} else if (arg === "-v" || arg === "--version") {
|
|
35
|
+
result.version = true;
|
|
36
|
+
} else if (arg === "-y" || arg === "--yes") {
|
|
37
|
+
result.yes = true;
|
|
38
|
+
} else if (arg === "--no-install") {
|
|
39
|
+
result.install = false;
|
|
40
|
+
} else if (arg === "--force") {
|
|
41
|
+
result.force = true;
|
|
42
|
+
} else if (arg === "-p" || arg === "--port") {
|
|
43
|
+
const nextValue = argv[i + 1];
|
|
44
|
+
if (!nextValue || nextValue.startsWith("-")) {
|
|
45
|
+
throw new Error(`Missing value for ${arg}`);
|
|
46
|
+
}
|
|
47
|
+
result.port = parsePort(nextValue);
|
|
48
|
+
i += 1;
|
|
49
|
+
} else if (arg.startsWith("--port=")) {
|
|
50
|
+
result.port = parsePort(arg.slice("--port=".length));
|
|
51
|
+
} else if (arg.startsWith("-")) {
|
|
52
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
53
|
+
} else if (!result.targetDir) {
|
|
54
|
+
result.targetDir = arg;
|
|
55
|
+
} else {
|
|
56
|
+
throw new Error(`Unexpected argument: ${arg}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parsePort(raw) {
|
|
64
|
+
const num = Number(raw);
|
|
65
|
+
if (!Number.isInteger(num) || num < 1 || num > 65535) {
|
|
66
|
+
throw new Error(`Invalid port "${raw}". Port must be an integer between 1 and 65535.`);
|
|
67
|
+
}
|
|
68
|
+
return num;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function collectOptions(parsedArgs) {
|
|
72
|
+
const nonInteractive = parsedArgs.yes || !process.stdin.isTTY;
|
|
73
|
+
|
|
74
|
+
if (nonInteractive) {
|
|
75
|
+
return {
|
|
76
|
+
targetDir: parsedArgs.targetDir || DEFAULT_CONFIG.projectName,
|
|
77
|
+
port: parsedArgs.port ?? DEFAULT_CONFIG.port,
|
|
78
|
+
install: parsedArgs.install,
|
|
79
|
+
force: parsedArgs.force,
|
|
80
|
+
interactive: false,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const rl = readline.createInterface({ input, output });
|
|
85
|
+
try {
|
|
86
|
+
let targetDir = parsedArgs.targetDir;
|
|
87
|
+
if (!targetDir) {
|
|
88
|
+
const answer = await rl.question(
|
|
89
|
+
color.cyan(`? Project folder (use "." for current folder) [${DEFAULT_CONFIG.projectName}]: `)
|
|
90
|
+
);
|
|
91
|
+
targetDir = answer.trim() || DEFAULT_CONFIG.projectName;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let port = parsedArgs.port;
|
|
95
|
+
if (port === null) {
|
|
96
|
+
const portAnswer = await rl.question(
|
|
97
|
+
color.cyan(`? Server port [${DEFAULT_CONFIG.port}]: `)
|
|
98
|
+
);
|
|
99
|
+
port = portAnswer.trim() ? parsePort(portAnswer.trim()) : DEFAULT_CONFIG.port;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let install = parsedArgs.install;
|
|
103
|
+
if (parsedArgs.install) {
|
|
104
|
+
const installAnswer = await rl.question(
|
|
105
|
+
color.cyan("? Install dependencies with npm now? (Y/n): ")
|
|
106
|
+
);
|
|
107
|
+
const normalized = installAnswer.trim().toLowerCase();
|
|
108
|
+
if (normalized === "n" || normalized === "no") {
|
|
109
|
+
install = false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
targetDir,
|
|
115
|
+
port,
|
|
116
|
+
install,
|
|
117
|
+
force: parsedArgs.force,
|
|
118
|
+
interactive: true,
|
|
119
|
+
};
|
|
120
|
+
} finally {
|
|
121
|
+
rl.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function confirmOverwrite(collidingPaths) {
|
|
126
|
+
const rl = readline.createInterface({ input, output });
|
|
127
|
+
try {
|
|
128
|
+
console.log(color.yellow("\nWarning: Target directory already contains conflicting files:"));
|
|
129
|
+
for (const item of collidingPaths.slice(0, 6)) {
|
|
130
|
+
console.log(color.yellow(` - ${item}`));
|
|
131
|
+
}
|
|
132
|
+
if (collidingPaths.length > 6) {
|
|
133
|
+
console.log(color.yellow(` ...and ${collidingPaths.length - 6} more`));
|
|
134
|
+
}
|
|
135
|
+
const answer = await rl.question(color.cyan("? Overwrite these files? (y/N): "));
|
|
136
|
+
const normalized = answer.trim().toLowerCase();
|
|
137
|
+
return normalized === "y" || normalized === "yes";
|
|
138
|
+
} finally {
|
|
139
|
+
rl.close();
|
|
140
|
+
}
|
|
141
|
+
}
|
package/src/scaffold.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { DEPENDENCIES, DEV_DEPENDENCIES, PROJECT_FOLDERS } from "./constants.js";
|
|
5
|
+
import { color, confirmOverwrite } from "./prompt.js";
|
|
6
|
+
import { buildProjectFiles } from "./templates/index.js";
|
|
7
|
+
import { sanitizePackageName } from "./templates/root.js";
|
|
8
|
+
|
|
9
|
+
function findCollisions(targetPath, files) {
|
|
10
|
+
const collisions = [];
|
|
11
|
+
for (const file of files) {
|
|
12
|
+
const fullPath = path.join(targetPath, file.path);
|
|
13
|
+
if (fs.existsSync(fullPath)) {
|
|
14
|
+
collisions.push(file.path);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return collisions;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function writeProjectStructure(targetPath, files) {
|
|
21
|
+
fs.mkdirSync(targetPath, { recursive: true });
|
|
22
|
+
|
|
23
|
+
for (const folder of PROJECT_FOLDERS) {
|
|
24
|
+
fs.mkdirSync(path.join(targetPath, folder), { recursive: true });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
for (const file of files) {
|
|
28
|
+
const destination = path.join(targetPath, file.path);
|
|
29
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
30
|
+
fs.writeFileSync(destination, file.content, "utf8");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function installDependencies(targetPath) {
|
|
35
|
+
console.log(color.cyan("\nInstalling dependencies with npm...\n"));
|
|
36
|
+
|
|
37
|
+
const result =
|
|
38
|
+
process.platform === "win32"
|
|
39
|
+
? spawnSync("npm install", {
|
|
40
|
+
cwd: targetPath,
|
|
41
|
+
stdio: "inherit",
|
|
42
|
+
shell: true,
|
|
43
|
+
})
|
|
44
|
+
: spawnSync("npm", ["install"], {
|
|
45
|
+
cwd: targetPath,
|
|
46
|
+
stdio: "inherit",
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
if (result.error) {
|
|
50
|
+
throw new Error(`Failed to invoke npm: ${result.error.message}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (result.status !== 0) {
|
|
54
|
+
throw new Error(
|
|
55
|
+
`npm install exited with status ${result.status}. You can run "npm install" manually inside ${targetPath}.`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function scaffoldProject(options) {
|
|
61
|
+
const { targetDir, port, install, force, interactive } = options;
|
|
62
|
+
const targetPath = path.resolve(process.cwd(), targetDir);
|
|
63
|
+
|
|
64
|
+
if (fs.existsSync(targetPath) && !fs.statSync(targetPath).isDirectory()) {
|
|
65
|
+
throw new Error(`Target path "${targetPath}" exists and is not a directory.`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const rawProjectName =
|
|
69
|
+
targetDir === "." ? path.basename(targetPath) : path.basename(targetPath);
|
|
70
|
+
const projectName = sanitizePackageName(rawProjectName);
|
|
71
|
+
const files = buildProjectFiles({ projectName, port });
|
|
72
|
+
|
|
73
|
+
if (fs.existsSync(targetPath) && !force) {
|
|
74
|
+
const collisions = findCollisions(targetPath, files);
|
|
75
|
+
if (collisions.length > 0) {
|
|
76
|
+
if (interactive) {
|
|
77
|
+
const confirmed = await confirmOverwrite(collisions);
|
|
78
|
+
if (!confirmed) {
|
|
79
|
+
console.log(color.yellow("\nScaffolding cancelled. No files were modified."));
|
|
80
|
+
return { cancelled: true, targetPath, filesCreated: 0 };
|
|
81
|
+
}
|
|
82
|
+
} else {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`Target directory already contains conflicting files (${collisions.join(", ")}). Re-run with --force to overwrite.`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
writeProjectStructure(targetPath, files);
|
|
91
|
+
|
|
92
|
+
console.log(color.green(`\nCreated Express + MongoDB (ESM) structure in ${targetPath}`));
|
|
93
|
+
console.log(color.dim(`Folders: ${PROJECT_FOLDERS.join(", ")}`));
|
|
94
|
+
console.log(color.dim(`Dependencies: ${Object.keys(DEPENDENCIES).join(", ")}`));
|
|
95
|
+
console.log(color.dim(`DevDependencies: ${Object.keys(DEV_DEPENDENCIES).join(", ")}`));
|
|
96
|
+
|
|
97
|
+
if (install) {
|
|
98
|
+
installDependencies(targetPath);
|
|
99
|
+
} else {
|
|
100
|
+
console.log(color.yellow("\nSkipped dependency installation (--no-install)."));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const cdTarget = targetDir === "." ? null : targetDir;
|
|
104
|
+
console.log(color.bold("\nNext steps:"));
|
|
105
|
+
if (cdTarget) {
|
|
106
|
+
console.log(` cd ${cdTarget}`);
|
|
107
|
+
}
|
|
108
|
+
if (!install) {
|
|
109
|
+
console.log(" npm install");
|
|
110
|
+
}
|
|
111
|
+
console.log(" npm run dev\n");
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
cancelled: false,
|
|
115
|
+
targetPath,
|
|
116
|
+
projectName,
|
|
117
|
+
filesCreated: files.length,
|
|
118
|
+
installed: install,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export function buildConfigFiles() {
|
|
2
|
+
const dbContent = `import mongoose from "mongoose";
|
|
3
|
+
import env from "./env.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Connect to MongoDB using Mongoose.
|
|
7
|
+
*/
|
|
8
|
+
async function connectDB() {
|
|
9
|
+
if (!env.mongoUri) {
|
|
10
|
+
throw new Error("MONGO_URI is missing in environment variables.");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const connection = await mongoose.connect(env.mongoUri);
|
|
14
|
+
console.log(\`MongoDB connected: \${connection.connection.host}\`);
|
|
15
|
+
return connection;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default connectDB;
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const envContent = `const env = Object.freeze({
|
|
22
|
+
port: Number(process.env.PORT) || 5000,
|
|
23
|
+
nodeEnv: process.env.NODE_ENV || "development",
|
|
24
|
+
mongoUri: process.env.MONGO_URI || "",
|
|
25
|
+
jwtSecret: process.env.JWT_SECRET || "",
|
|
26
|
+
jwtExpiresIn: process.env.JWT_EXPIRES_IN || "7d",
|
|
27
|
+
corsOrigin: process.env.CORS_ORIGIN || "http://localhost:3000",
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export default env;
|
|
31
|
+
`;
|
|
32
|
+
|
|
33
|
+
return [
|
|
34
|
+
{ path: "config/db.js", content: dbContent },
|
|
35
|
+
{ path: "config/env.js", content: envContent },
|
|
36
|
+
];
|
|
37
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
export function buildControllerFiles() {
|
|
2
|
+
const healthControllerContent = `import mongoose from "mongoose";
|
|
3
|
+
import ApiResponse from "../utils/ApiResponse.js";
|
|
4
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
5
|
+
|
|
6
|
+
export const healthCheck = asyncHandler(async (_req, res) => {
|
|
7
|
+
const dbReadyState = mongoose.connection.readyState;
|
|
8
|
+
const dbStatusMap = {
|
|
9
|
+
0: "disconnected",
|
|
10
|
+
1: "connected",
|
|
11
|
+
2: "connecting",
|
|
12
|
+
3: "disconnecting",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
res.status(200).json(
|
|
16
|
+
new ApiResponse(
|
|
17
|
+
200,
|
|
18
|
+
{
|
|
19
|
+
status: "ok",
|
|
20
|
+
database: dbStatusMap[dbReadyState] || "unknown",
|
|
21
|
+
uptimeSeconds: Math.floor(process.uptime()),
|
|
22
|
+
timestamp: new Date().toISOString(),
|
|
23
|
+
},
|
|
24
|
+
"Server is healthy"
|
|
25
|
+
)
|
|
26
|
+
);
|
|
27
|
+
});
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
const authControllerContent = `import User from "../models/user.model.js";
|
|
31
|
+
import ApiError from "../utils/ApiError.js";
|
|
32
|
+
import ApiResponse from "../utils/ApiResponse.js";
|
|
33
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
34
|
+
|
|
35
|
+
function getCookieOptions() {
|
|
36
|
+
return {
|
|
37
|
+
httpOnly: true,
|
|
38
|
+
secure: process.env.NODE_ENV === "production",
|
|
39
|
+
sameSite: "lax",
|
|
40
|
+
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function sanitizeUser(userDoc) {
|
|
45
|
+
const user = userDoc.toObject();
|
|
46
|
+
delete user.password;
|
|
47
|
+
return user;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const registerUser = asyncHandler(async (req, res) => {
|
|
51
|
+
const { name, email, password } = req.body || {};
|
|
52
|
+
|
|
53
|
+
if (!name?.trim() || !email?.trim() || !password) {
|
|
54
|
+
throw new ApiError(400, "Name, email, and password are required");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const normalizedEmail = email.trim().toLowerCase();
|
|
58
|
+
const existingUser = await User.findOne({ email: normalizedEmail });
|
|
59
|
+
|
|
60
|
+
if (existingUser) {
|
|
61
|
+
throw new ApiError(409, "An account with this email already exists");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const avatarPath = req.file ? \`/uploads/\${req.file.filename}\` : "";
|
|
65
|
+
|
|
66
|
+
const user = await User.create({
|
|
67
|
+
name: name.trim(),
|
|
68
|
+
email: normalizedEmail,
|
|
69
|
+
password,
|
|
70
|
+
avatar: avatarPath,
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const accessToken = user.generateAccessToken();
|
|
74
|
+
|
|
75
|
+
res
|
|
76
|
+
.status(201)
|
|
77
|
+
.cookie("accessToken", accessToken, getCookieOptions())
|
|
78
|
+
.json(
|
|
79
|
+
new ApiResponse(
|
|
80
|
+
201,
|
|
81
|
+
{
|
|
82
|
+
user: sanitizeUser(user),
|
|
83
|
+
accessToken,
|
|
84
|
+
},
|
|
85
|
+
"User registered successfully"
|
|
86
|
+
)
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
export const loginUser = asyncHandler(async (req, res) => {
|
|
91
|
+
const { email, password } = req.body || {};
|
|
92
|
+
|
|
93
|
+
if (!email?.trim() || !password) {
|
|
94
|
+
throw new ApiError(400, "Email and password are required");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const user = await User.findOne({ email: email.trim().toLowerCase() }).select(
|
|
98
|
+
"+password"
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
if (!user || !(await user.comparePassword(password))) {
|
|
102
|
+
throw new ApiError(401, "Invalid email or password");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const accessToken = user.generateAccessToken();
|
|
106
|
+
|
|
107
|
+
res
|
|
108
|
+
.status(200)
|
|
109
|
+
.cookie("accessToken", accessToken, getCookieOptions())
|
|
110
|
+
.json(
|
|
111
|
+
new ApiResponse(
|
|
112
|
+
200,
|
|
113
|
+
{
|
|
114
|
+
user: sanitizeUser(user),
|
|
115
|
+
accessToken,
|
|
116
|
+
},
|
|
117
|
+
"Logged in successfully"
|
|
118
|
+
)
|
|
119
|
+
);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
export const logoutUser = asyncHandler(async (_req, res) => {
|
|
123
|
+
res
|
|
124
|
+
.status(200)
|
|
125
|
+
.clearCookie("accessToken", {
|
|
126
|
+
httpOnly: true,
|
|
127
|
+
secure: process.env.NODE_ENV === "production",
|
|
128
|
+
sameSite: "lax",
|
|
129
|
+
})
|
|
130
|
+
.json(new ApiResponse(200, null, "Logged out successfully"));
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
export const getCurrentUser = asyncHandler(async (req, res) => {
|
|
134
|
+
res
|
|
135
|
+
.status(200)
|
|
136
|
+
.json(new ApiResponse(200, { user: req.user }, "Current user fetched"));
|
|
137
|
+
});
|
|
138
|
+
`;
|
|
139
|
+
|
|
140
|
+
return [
|
|
141
|
+
{ path: "controllers/health.controller.js", content: healthControllerContent },
|
|
142
|
+
{ path: "controllers/auth.controller.js", content: authControllerContent },
|
|
143
|
+
];
|
|
144
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { buildConfigFiles } from "./config.js";
|
|
2
|
+
import { buildControllerFiles } from "./controllers.js";
|
|
3
|
+
import { buildMiddlewareFiles } from "./middlewares.js";
|
|
4
|
+
import { buildModelFiles } from "./models.js";
|
|
5
|
+
import { buildRootFiles } from "./root.js";
|
|
6
|
+
import { buildRouteFiles } from "./routes.js";
|
|
7
|
+
import { buildUtilFiles } from "./utils.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Assemble all generated files for the scaffolded Express + MongoDB project.
|
|
11
|
+
*/
|
|
12
|
+
export function buildProjectFiles(options) {
|
|
13
|
+
return [
|
|
14
|
+
...buildRootFiles(options),
|
|
15
|
+
...buildConfigFiles(),
|
|
16
|
+
...buildUtilFiles(),
|
|
17
|
+
...buildModelFiles(),
|
|
18
|
+
...buildMiddlewareFiles(),
|
|
19
|
+
...buildControllerFiles(),
|
|
20
|
+
...buildRouteFiles(),
|
|
21
|
+
{ path: "uploads/.gitkeep", content: "" },
|
|
22
|
+
];
|
|
23
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
export function buildMiddlewareFiles() {
|
|
2
|
+
const authMiddlewareContent = `import jwt from "jsonwebtoken";
|
|
3
|
+
import env from "../config/env.js";
|
|
4
|
+
import User from "../models/user.model.js";
|
|
5
|
+
import ApiError from "../utils/ApiError.js";
|
|
6
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
7
|
+
|
|
8
|
+
function extractToken(req) {
|
|
9
|
+
if (req.cookies?.accessToken) {
|
|
10
|
+
return req.cookies.accessToken;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const authHeader = req.headers.authorization;
|
|
14
|
+
if (authHeader && authHeader.startsWith("Bearer ")) {
|
|
15
|
+
return authHeader.slice(7).trim();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const verifyJWT = asyncHandler(async (req, _res, next) => {
|
|
22
|
+
const token = extractToken(req);
|
|
23
|
+
|
|
24
|
+
if (!token) {
|
|
25
|
+
throw new ApiError(401, "Unauthorized: missing authentication token");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const secret = process.env.JWT_SECRET || env.jwtSecret;
|
|
29
|
+
if (!secret) {
|
|
30
|
+
throw new ApiError(500, "Server configuration error: JWT_SECRET missing");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const decoded = jwt.verify(token, secret);
|
|
34
|
+
const user = await User.findById(decoded._id).select("-password");
|
|
35
|
+
|
|
36
|
+
if (!user) {
|
|
37
|
+
throw new ApiError(401, "Unauthorized: user no longer exists");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
req.user = user;
|
|
41
|
+
next();
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
export const authorizeRoles = (...roles) => {
|
|
45
|
+
return (req, _res, next) => {
|
|
46
|
+
if (!req.user || !roles.includes(req.user.role)) {
|
|
47
|
+
return next(new ApiError(403, "Forbidden: insufficient permissions"));
|
|
48
|
+
}
|
|
49
|
+
return next();
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
`;
|
|
53
|
+
|
|
54
|
+
const errorMiddlewareContent = `import ApiError from "../utils/ApiError.js";
|
|
55
|
+
|
|
56
|
+
export function notFound(req, _res, next) {
|
|
57
|
+
next(new ApiError(404, \`Route not found: \${req.originalUrl}\`));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function errorHandler(err, _req, res, _next) {
|
|
61
|
+
let statusCode = err.statusCode || 500;
|
|
62
|
+
let message = err.message || "Internal Server Error";
|
|
63
|
+
let errors = Array.isArray(err.errors) ? err.errors : [];
|
|
64
|
+
|
|
65
|
+
if (err.name === "ValidationError") {
|
|
66
|
+
statusCode = 400;
|
|
67
|
+
message = "Validation failed";
|
|
68
|
+
errors = Object.values(err.errors).map((item) => item.message);
|
|
69
|
+
} else if (err.name === "CastError") {
|
|
70
|
+
statusCode = 400;
|
|
71
|
+
message = \`Invalid \${err.path}: \${err.value}\`;
|
|
72
|
+
} else if (err.code === 11000) {
|
|
73
|
+
statusCode = 409;
|
|
74
|
+
const duplicateFields = Object.keys(err.keyValue || {}).join(", ");
|
|
75
|
+
message = duplicateFields
|
|
76
|
+
? \`Duplicate value for field(s): \${duplicateFields}\`
|
|
77
|
+
: "Duplicate key error";
|
|
78
|
+
} else if (err.name === "JsonWebTokenError") {
|
|
79
|
+
statusCode = 401;
|
|
80
|
+
message = "Invalid authentication token";
|
|
81
|
+
} else if (err.name === "TokenExpiredError") {
|
|
82
|
+
statusCode = 401;
|
|
83
|
+
message = "Authentication token has expired";
|
|
84
|
+
} else if (err.name === "MulterError") {
|
|
85
|
+
statusCode = 400;
|
|
86
|
+
message = err.message || "File upload error";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const response = {
|
|
90
|
+
success: false,
|
|
91
|
+
statusCode,
|
|
92
|
+
message,
|
|
93
|
+
...(errors.length > 0 ? { errors } : {}),
|
|
94
|
+
...(process.env.NODE_ENV === "development" && err.stack
|
|
95
|
+
? { stack: err.stack }
|
|
96
|
+
: {}),
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
res.status(statusCode).json(response);
|
|
100
|
+
}
|
|
101
|
+
`;
|
|
102
|
+
|
|
103
|
+
const multerMiddlewareContent = `import fs from "node:fs";
|
|
104
|
+
import path from "node:path";
|
|
105
|
+
import multer from "multer";
|
|
106
|
+
import ApiError from "../utils/ApiError.js";
|
|
107
|
+
|
|
108
|
+
const uploadDir = path.resolve("uploads");
|
|
109
|
+
const ALLOWED_MIME_TYPES = new Set([
|
|
110
|
+
"image/jpeg",
|
|
111
|
+
"image/png",
|
|
112
|
+
"image/webp",
|
|
113
|
+
"image/gif",
|
|
114
|
+
]);
|
|
115
|
+
|
|
116
|
+
const storage = multer.diskStorage({
|
|
117
|
+
destination(_req, _file, cb) {
|
|
118
|
+
fs.mkdirSync(uploadDir, { recursive: true });
|
|
119
|
+
cb(null, uploadDir);
|
|
120
|
+
},
|
|
121
|
+
filename(_req, file, cb) {
|
|
122
|
+
const ext = path.extname(file.originalname).toLowerCase();
|
|
123
|
+
const baseName = path
|
|
124
|
+
.basename(file.originalname, ext)
|
|
125
|
+
.replace(/[^a-zA-Z0-9_-]/g, "-")
|
|
126
|
+
.slice(0, 40);
|
|
127
|
+
const uniqueSuffix = \`\${Date.now()}-\${Math.round(Math.random() * 1e9)}\`;
|
|
128
|
+
cb(null, \`\${baseName || "file"}-\${uniqueSuffix}\${ext}\`);
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
function fileFilter(_req, file, cb) {
|
|
133
|
+
if (!ALLOWED_MIME_TYPES.has(file.mimetype)) {
|
|
134
|
+
cb(new ApiError(400, "Only JPEG, PNG, WEBP, and GIF files are allowed"));
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
cb(null, true);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export const upload = multer({
|
|
141
|
+
storage,
|
|
142
|
+
fileFilter,
|
|
143
|
+
limits: {
|
|
144
|
+
fileSize: 5 * 1024 * 1024, // 5 MB
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
`;
|
|
148
|
+
|
|
149
|
+
return [
|
|
150
|
+
{ path: "middlewares/auth.middleware.js", content: authMiddlewareContent },
|
|
151
|
+
{ path: "middlewares/error.middleware.js", content: errorMiddlewareContent },
|
|
152
|
+
{ path: "middlewares/multer.middleware.js", content: multerMiddlewareContent },
|
|
153
|
+
];
|
|
154
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export function buildModelFiles() {
|
|
2
|
+
const userModelContent = `import mongoose from "mongoose";
|
|
3
|
+
import bcrypt from "bcryptjs";
|
|
4
|
+
import jwt from "jsonwebtoken";
|
|
5
|
+
import env from "../config/env.js";
|
|
6
|
+
|
|
7
|
+
const userSchema = new mongoose.Schema(
|
|
8
|
+
{
|
|
9
|
+
name: {
|
|
10
|
+
type: String,
|
|
11
|
+
required: [true, "Name is required"],
|
|
12
|
+
trim: true,
|
|
13
|
+
minlength: [2, "Name must be at least 2 characters"],
|
|
14
|
+
maxlength: [80, "Name cannot exceed 80 characters"],
|
|
15
|
+
},
|
|
16
|
+
email: {
|
|
17
|
+
type: String,
|
|
18
|
+
required: [true, "Email is required"],
|
|
19
|
+
unique: true,
|
|
20
|
+
lowercase: true,
|
|
21
|
+
trim: true,
|
|
22
|
+
match: [/^\\S+@\\S+\\.\\S+$/, "Please provide a valid email address"],
|
|
23
|
+
},
|
|
24
|
+
password: {
|
|
25
|
+
type: String,
|
|
26
|
+
required: [true, "Password is required"],
|
|
27
|
+
minlength: [6, "Password must be at least 6 characters"],
|
|
28
|
+
select: false,
|
|
29
|
+
},
|
|
30
|
+
role: {
|
|
31
|
+
type: String,
|
|
32
|
+
enum: ["user", "admin"],
|
|
33
|
+
default: "user",
|
|
34
|
+
},
|
|
35
|
+
avatar: {
|
|
36
|
+
type: String,
|
|
37
|
+
default: "",
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
timestamps: true,
|
|
42
|
+
}
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
userSchema.pre("save", async function () {
|
|
46
|
+
if (!this.isModified("password")) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
this.password = await bcrypt.hash(this.password, 10);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
userSchema.methods.comparePassword = async function (candidatePassword) {
|
|
53
|
+
return bcrypt.compare(candidatePassword, this.password);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
userSchema.methods.generateAccessToken = function () {
|
|
57
|
+
const secret = process.env.JWT_SECRET || env.jwtSecret;
|
|
58
|
+
if (!secret) {
|
|
59
|
+
throw new Error("JWT_SECRET is not configured.");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return jwt.sign(
|
|
63
|
+
{
|
|
64
|
+
_id: this._id,
|
|
65
|
+
email: this.email,
|
|
66
|
+
role: this.role,
|
|
67
|
+
},
|
|
68
|
+
secret,
|
|
69
|
+
{
|
|
70
|
+
expiresIn: process.env.JWT_EXPIRES_IN || env.jwtExpiresIn,
|
|
71
|
+
}
|
|
72
|
+
);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const User = mongoose.model("User", userSchema);
|
|
76
|
+
|
|
77
|
+
export default User;
|
|
78
|
+
`;
|
|
79
|
+
|
|
80
|
+
return [{ path: "models/user.model.js", content: userModelContent }];
|
|
81
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { DEPENDENCIES, DEV_DEPENDENCIES } from "../constants.js";
|
|
3
|
+
|
|
4
|
+
export function sanitizePackageName(name) {
|
|
5
|
+
const cleaned = String(name || "")
|
|
6
|
+
.trim()
|
|
7
|
+
.toLowerCase()
|
|
8
|
+
.replace(/[^a-z0-9._-]+/g, "-")
|
|
9
|
+
.replace(/^[._-]+|[._-]+$/g, "");
|
|
10
|
+
|
|
11
|
+
return cleaned || "express-mongo-backend";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function toDatabaseName(name) {
|
|
15
|
+
return sanitizePackageName(name).replace(/[^a-z0-9]+/g, "_");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function buildRootFiles({ projectName, port }) {
|
|
19
|
+
const pkgName = sanitizePackageName(projectName);
|
|
20
|
+
const dbName = toDatabaseName(pkgName);
|
|
21
|
+
const jwtSecret = crypto.randomBytes(32).toString("hex");
|
|
22
|
+
|
|
23
|
+
const packageJson = {
|
|
24
|
+
name: pkgName,
|
|
25
|
+
version: "1.0.0",
|
|
26
|
+
description: "Express + MongoDB (ESM) backend API",
|
|
27
|
+
type: "module",
|
|
28
|
+
main: "server.js",
|
|
29
|
+
scripts: {
|
|
30
|
+
dev: "nodemon server.js",
|
|
31
|
+
start: "node server.js",
|
|
32
|
+
},
|
|
33
|
+
engines: {
|
|
34
|
+
node: ">=18.0.0",
|
|
35
|
+
},
|
|
36
|
+
dependencies: { ...DEPENDENCIES },
|
|
37
|
+
devDependencies: { ...DEV_DEPENDENCIES },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const envContent = [
|
|
41
|
+
`PORT=${port}`,
|
|
42
|
+
"NODE_ENV=development",
|
|
43
|
+
`MONGO_URI=mongodb://127.0.0.1:27017/${dbName}`,
|
|
44
|
+
`JWT_SECRET=${jwtSecret}`,
|
|
45
|
+
"JWT_EXPIRES_IN=7d",
|
|
46
|
+
"CORS_ORIGIN=http://localhost:3000",
|
|
47
|
+
"",
|
|
48
|
+
].join("\n");
|
|
49
|
+
|
|
50
|
+
const envExampleContent = [
|
|
51
|
+
`PORT=${port}`,
|
|
52
|
+
"NODE_ENV=development",
|
|
53
|
+
`MONGO_URI=mongodb://127.0.0.1:27017/${dbName}`,
|
|
54
|
+
"JWT_SECRET=replace-with-your-super-secret-jwt-key",
|
|
55
|
+
"JWT_EXPIRES_IN=7d",
|
|
56
|
+
"CORS_ORIGIN=http://localhost:3000",
|
|
57
|
+
"",
|
|
58
|
+
].join("\n");
|
|
59
|
+
|
|
60
|
+
const gitignoreContent = [
|
|
61
|
+
"# Dependencies",
|
|
62
|
+
"node_modules/",
|
|
63
|
+
"",
|
|
64
|
+
"# Environment variables",
|
|
65
|
+
".env",
|
|
66
|
+
".env.local",
|
|
67
|
+
".env.*.local",
|
|
68
|
+
"",
|
|
69
|
+
"# Uploads (keep folder via .gitkeep)",
|
|
70
|
+
"uploads/*",
|
|
71
|
+
"!uploads/.gitkeep",
|
|
72
|
+
"",
|
|
73
|
+
"# Logs & OS artifacts",
|
|
74
|
+
"logs/",
|
|
75
|
+
"*.log",
|
|
76
|
+
"npm-debug.log*",
|
|
77
|
+
".DS_Store",
|
|
78
|
+
"Thumbs.db",
|
|
79
|
+
"",
|
|
80
|
+
"# Build & coverage",
|
|
81
|
+
"coverage/",
|
|
82
|
+
"dist/",
|
|
83
|
+
"",
|
|
84
|
+
].join("\n");
|
|
85
|
+
|
|
86
|
+
const appJsContent = `import path from "node:path";
|
|
87
|
+
import express from "express";
|
|
88
|
+
import cors from "cors";
|
|
89
|
+
import helmet from "helmet";
|
|
90
|
+
import morgan from "morgan";
|
|
91
|
+
import cookieParser from "cookie-parser";
|
|
92
|
+
|
|
93
|
+
import healthRoutes from "./routes/health.routes.js";
|
|
94
|
+
import authRoutes from "./routes/auth.routes.js";
|
|
95
|
+
import { errorHandler, notFound } from "./middlewares/error.middleware.js";
|
|
96
|
+
|
|
97
|
+
const app = express();
|
|
98
|
+
|
|
99
|
+
const allowedOrigins = (process.env.CORS_ORIGIN || "http://localhost:3000")
|
|
100
|
+
.split(",")
|
|
101
|
+
.map((origin) => origin.trim())
|
|
102
|
+
.filter(Boolean);
|
|
103
|
+
|
|
104
|
+
app.use(helmet());
|
|
105
|
+
app.use(
|
|
106
|
+
cors({
|
|
107
|
+
origin: allowedOrigins.includes("*") ? true : allowedOrigins,
|
|
108
|
+
credentials: true,
|
|
109
|
+
})
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
if (process.env.NODE_ENV !== "test") {
|
|
113
|
+
app.use(morgan("dev"));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
app.use(express.json({ limit: "16kb" }));
|
|
117
|
+
app.use(express.urlencoded({ extended: true, limit: "16kb" }));
|
|
118
|
+
app.use(cookieParser());
|
|
119
|
+
app.use("/uploads", express.static(path.resolve("uploads")));
|
|
120
|
+
|
|
121
|
+
app.get("/", (_req, res) => {
|
|
122
|
+
res.status(200).json({
|
|
123
|
+
success: true,
|
|
124
|
+
message: "Express + MongoDB API is running",
|
|
125
|
+
health: "/api/v1/health",
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
app.use("/api/v1/health", healthRoutes);
|
|
130
|
+
app.use("/api/v1/auth", authRoutes);
|
|
131
|
+
|
|
132
|
+
app.use(notFound);
|
|
133
|
+
app.use(errorHandler);
|
|
134
|
+
|
|
135
|
+
export default app;
|
|
136
|
+
`;
|
|
137
|
+
|
|
138
|
+
const serverJsContent = `import "dotenv/config";
|
|
139
|
+
import mongoose from "mongoose";
|
|
140
|
+
import app from "./app.js";
|
|
141
|
+
import connectDB from "./config/db.js";
|
|
142
|
+
import env from "./config/env.js";
|
|
143
|
+
|
|
144
|
+
let server;
|
|
145
|
+
|
|
146
|
+
async function startServer() {
|
|
147
|
+
try {
|
|
148
|
+
await connectDB();
|
|
149
|
+
server = app.listen(env.port, () => {
|
|
150
|
+
console.log(
|
|
151
|
+
\`Server running in \${env.nodeEnv} mode on http://localhost:\${env.port}\`
|
|
152
|
+
);
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
console.error("Failed to start server:", error.message);
|
|
156
|
+
process.exit(1);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function shutdown(signal) {
|
|
161
|
+
console.log(\`\\n\${signal} received. Shutting down gracefully...\`);
|
|
162
|
+
try {
|
|
163
|
+
if (server) {
|
|
164
|
+
await new Promise((resolve) => server.close(resolve));
|
|
165
|
+
}
|
|
166
|
+
await mongoose.connection.close();
|
|
167
|
+
process.exit(0);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
console.error("Error during shutdown:", error.message);
|
|
170
|
+
process.exit(1);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
175
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
176
|
+
process.on("unhandledRejection", (reason) => {
|
|
177
|
+
console.error("Unhandled Rejection:", reason);
|
|
178
|
+
shutdown("unhandledRejection");
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
startServer();
|
|
182
|
+
`;
|
|
183
|
+
|
|
184
|
+
const readmeContent = `# ${pkgName}
|
|
185
|
+
|
|
186
|
+
Express + MongoDB (ES Modules) backend API scaffolded with \`create-api-structure\`.
|
|
187
|
+
|
|
188
|
+
## Project Structure
|
|
189
|
+
|
|
190
|
+
\`\`\`text
|
|
191
|
+
.
|
|
192
|
+
├── config/
|
|
193
|
+
│ ├── db.js # Mongoose connection setup
|
|
194
|
+
│ └── env.js # Environment configuration
|
|
195
|
+
├── controllers/
|
|
196
|
+
│ ├── auth.controller.js # Register, login, logout, current user
|
|
197
|
+
│ └── health.controller.js # Health check handler
|
|
198
|
+
├── middlewares/
|
|
199
|
+
│ ├── auth.middleware.js # JWT cookie/bearer verification
|
|
200
|
+
│ ├── error.middleware.js # 404 + centralized error handler
|
|
201
|
+
│ └── multer.middleware.js # File upload storage and filter
|
|
202
|
+
├── models/
|
|
203
|
+
│ └── user.model.js # User schema with bcrypt + JWT methods
|
|
204
|
+
├── routes/
|
|
205
|
+
│ ├── auth.routes.js # /api/v1/auth/*
|
|
206
|
+
│ └── health.routes.js # /api/v1/health
|
|
207
|
+
├── uploads/ # Uploaded files directory
|
|
208
|
+
├── utils/
|
|
209
|
+
│ ├── ApiError.js # Custom HTTP error class
|
|
210
|
+
│ ├── ApiResponse.js # Standard JSON response wrapper
|
|
211
|
+
│ └── asyncHandler.js # Async route wrapper
|
|
212
|
+
├── .env # Local environment variables
|
|
213
|
+
├── .env.example # Example environment template
|
|
214
|
+
├── .gitignore
|
|
215
|
+
├── app.js # Express app & middleware pipeline
|
|
216
|
+
├── package.json
|
|
217
|
+
└── server.js # Entry point & DB bootstrap
|
|
218
|
+
\`\`\`
|
|
219
|
+
|
|
220
|
+
## Quick Start
|
|
221
|
+
|
|
222
|
+
1. Make sure MongoDB is running locally or update \`MONGO_URI\` in \`.env\`.
|
|
223
|
+
2. Start the development server:
|
|
224
|
+
|
|
225
|
+
\`\`\`bash
|
|
226
|
+
npm run dev
|
|
227
|
+
\`\`\`
|
|
228
|
+
|
|
229
|
+
Or start in production mode:
|
|
230
|
+
|
|
231
|
+
\`\`\`bash
|
|
232
|
+
npm start
|
|
233
|
+
\`\`\`
|
|
234
|
+
|
|
235
|
+
## Starter API Endpoints
|
|
236
|
+
|
|
237
|
+
- \`GET /\` — API welcome message
|
|
238
|
+
- \`GET /api/v1/health\` — Health & uptime status
|
|
239
|
+
- \`POST /api/v1/auth/register\` — Register user (supports JSON or \`multipart/form-data\` with \`avatar\`)
|
|
240
|
+
- \`POST /api/v1/auth/login\` — Login and receive JWT cookie + token
|
|
241
|
+
- \`POST /api/v1/auth/logout\` — Clear JWT cookie (protected)
|
|
242
|
+
- \`GET /api/v1/auth/me\` — Fetch authenticated user profile (protected)
|
|
243
|
+
`;
|
|
244
|
+
|
|
245
|
+
return [
|
|
246
|
+
{ path: "package.json", content: `${JSON.stringify(packageJson, null, 2)}\n` },
|
|
247
|
+
{ path: ".env", content: envContent },
|
|
248
|
+
{ path: ".env.example", content: envExampleContent },
|
|
249
|
+
{ path: ".gitignore", content: gitignoreContent },
|
|
250
|
+
{ path: "app.js", content: appJsContent },
|
|
251
|
+
{ path: "server.js", content: serverJsContent },
|
|
252
|
+
{ path: "README.md", content: readmeContent },
|
|
253
|
+
];
|
|
254
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export function buildRouteFiles() {
|
|
2
|
+
const healthRoutesContent = `import { Router } from "express";
|
|
3
|
+
import { healthCheck } from "../controllers/health.controller.js";
|
|
4
|
+
|
|
5
|
+
const router = Router();
|
|
6
|
+
|
|
7
|
+
router.get("/", healthCheck);
|
|
8
|
+
|
|
9
|
+
export default router;
|
|
10
|
+
`;
|
|
11
|
+
|
|
12
|
+
const authRoutesContent = `import { Router } from "express";
|
|
13
|
+
import {
|
|
14
|
+
getCurrentUser,
|
|
15
|
+
loginUser,
|
|
16
|
+
logoutUser,
|
|
17
|
+
registerUser,
|
|
18
|
+
} from "../controllers/auth.controller.js";
|
|
19
|
+
import { verifyJWT } from "../middlewares/auth.middleware.js";
|
|
20
|
+
import { upload } from "../middlewares/multer.middleware.js";
|
|
21
|
+
|
|
22
|
+
const router = Router();
|
|
23
|
+
|
|
24
|
+
router.post("/register", upload.single("avatar"), registerUser);
|
|
25
|
+
router.post("/login", loginUser);
|
|
26
|
+
router.post("/logout", verifyJWT, logoutUser);
|
|
27
|
+
router.get("/me", verifyJWT, getCurrentUser);
|
|
28
|
+
|
|
29
|
+
export default router;
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
return [
|
|
33
|
+
{ path: "routes/health.routes.js", content: healthRoutesContent },
|
|
34
|
+
{ path: "routes/auth.routes.js", content: authRoutesContent },
|
|
35
|
+
];
|
|
36
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export function buildUtilFiles() {
|
|
2
|
+
const apiErrorContent = `/**
|
|
3
|
+
* Standardized operational API error.
|
|
4
|
+
*/
|
|
5
|
+
class ApiError extends Error {
|
|
6
|
+
constructor(statusCode, message = "Something went wrong", errors = [], stack = "") {
|
|
7
|
+
super(message);
|
|
8
|
+
this.statusCode = statusCode;
|
|
9
|
+
this.data = null;
|
|
10
|
+
this.message = message;
|
|
11
|
+
this.success = false;
|
|
12
|
+
this.errors = errors;
|
|
13
|
+
|
|
14
|
+
if (stack) {
|
|
15
|
+
this.stack = stack;
|
|
16
|
+
} else {
|
|
17
|
+
Error.captureStackTrace(this, this.constructor);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export default ApiError;
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
const apiResponseContent = `/**
|
|
26
|
+
* Standardized API success response wrapper.
|
|
27
|
+
*/
|
|
28
|
+
class ApiResponse {
|
|
29
|
+
constructor(statusCode, data = null, message = "Success") {
|
|
30
|
+
this.statusCode = statusCode;
|
|
31
|
+
this.data = data;
|
|
32
|
+
this.message = message;
|
|
33
|
+
this.success = statusCode < 400;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export default ApiResponse;
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
const asyncHandlerContent = `/**
|
|
41
|
+
* Wraps async Express route handlers and forwards errors to next().
|
|
42
|
+
*/
|
|
43
|
+
const asyncHandler = (requestHandler) => (req, res, next) => {
|
|
44
|
+
Promise.resolve(requestHandler(req, res, next)).catch(next);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export default asyncHandler;
|
|
48
|
+
`;
|
|
49
|
+
|
|
50
|
+
return [
|
|
51
|
+
{ path: "utils/ApiError.js", content: apiErrorContent },
|
|
52
|
+
{ path: "utils/ApiResponse.js", content: apiResponseContent },
|
|
53
|
+
{ path: "utils/asyncHandler.js", content: asyncHandlerContent },
|
|
54
|
+
];
|
|
55
|
+
}
|