create-oikko-mongo 1.0.0 → 1.1.1
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/AGENTS.md +96 -0
- package/README.md +43 -0
- package/bin/index.js +275 -137
- package/llms.txt +145 -0
- package/package.json +17 -4
- package/template/.cursorrules +25 -0
- package/template/AGENTS.md +159 -0
- package/template/README.md +91 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# AI Agent Guide: `create-oikko-mongo`
|
|
2
|
+
|
|
3
|
+
This document instructs AI coding assistants (such as Antigravity, Claude Code, Cursor, Copilot, Devin, Windsurf, Aider) on how to understand, execute, maintain, and contribute to the `create-oikko-mongo` package.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Package Purpose & Overview
|
|
8
|
+
|
|
9
|
+
`create-oikko-mongo` is an enterprise scaffolding CLI tool designed to create scalable, production-ready MERN (MongoDB + Express + TypeScript) backend architectures.
|
|
10
|
+
|
|
11
|
+
It provides:
|
|
12
|
+
- Fully offline-capable scaffolding from a local `template/` directory.
|
|
13
|
+
- Dynamic token generation (64-character cryptographic hex secrets for JWT and session).
|
|
14
|
+
- Dynamic role injection into `src/app/modules/user/user.interface.ts`.
|
|
15
|
+
- Dynamic `.env` and `.env.example` replacement.
|
|
16
|
+
- Zero-leak TypeScript configuration with strict types.
|
|
17
|
+
- Dual-mode execution: Interactive terminal wizard and Non-Interactive automated/AI mode.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. CLI Execution Instructions for AI Agents
|
|
22
|
+
|
|
23
|
+
> **IMPORTANT FOR AI AGENTS**: Subprocess shells running in AI agents or CI/CD pipelines typically do NOT have an interactive TTY (`process.stdin.isTTY` is `false` or unallocated).
|
|
24
|
+
|
|
25
|
+
### How to Run:
|
|
26
|
+
Always provide the `-y`, `--yes`, or `--default` flag when bootstrapping a project:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# Standard automated scaffold:
|
|
30
|
+
node ./bin/index.js my-app --yes --no-install
|
|
31
|
+
|
|
32
|
+
# Custom automated scaffold:
|
|
33
|
+
node ./bin/index.js my-app --port 8080 --db "mongodb://localhost:27017/my-app" --roles "customer,admin" --force --yes
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Supported CLI Flags:
|
|
37
|
+
| Flag | Type | Default | Description |
|
|
38
|
+
| :--- | :--- | :--- | :--- |
|
|
39
|
+
| `[project-name]` | String | `my-oikko-app` | Positional argument for the target directory name. |
|
|
40
|
+
| `-y, --yes, --default` | Boolean | `false` | Skips all interactive prompts and uses defaults/supplied flags. |
|
|
41
|
+
| `-f, --force` | Boolean | `false` | Overwrites existing target directory without confirmation. |
|
|
42
|
+
| `--port` | String | `5000` | HTTP port injected into `.env`. |
|
|
43
|
+
| `--db` | String | `mongodb://localhost:27017/<name>` | MongoDB connection string. |
|
|
44
|
+
| `--roles` | String | `user, admin, super_admin` | Comma-delimited roles dynamically converted to `Role` enum. |
|
|
45
|
+
| `--pm` | String | `npm` | Package manager: `npm`, `pnpm`, `yarn`, `bun`. |
|
|
46
|
+
| `--latest` | Boolean | `false` | Converts dependencies in `package.json` to `"latest"`. |
|
|
47
|
+
| `--no-install` | Boolean | `false` | Skips running the package manager installation step. |
|
|
48
|
+
| `-h, --help` | Boolean | `false` | Outputs formatted CLI help. |
|
|
49
|
+
| `-v, --version` | Boolean | `false` | Outputs package version. |
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 3. Project File Tree & Responsibilities
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
create-oikko-mongo/
|
|
57
|
+
├── bin/
|
|
58
|
+
│ └── index.js # CLI entry point. Parses args, manages prompts/fallbacks, copies template & injects dynamic variables.
|
|
59
|
+
├── template/ # Boilerplate files copied into the user's project.
|
|
60
|
+
│ ├── .env.example # Variable template with placeholders ({{PORT}}, {{DB_URL}}, {{JWT_ACCESS_SECRET}}, etc.).
|
|
61
|
+
│ ├── _gitignore # Renamed to .gitignore during scaffolding.
|
|
62
|
+
│ ├── package.json # Base dependencies and scripts for the generated app.
|
|
63
|
+
│ ├── tsconfig.json # TypeScript configuration.
|
|
64
|
+
│ ├── AGENTS.md # AI Agent guide bundled into EVERY generated project!
|
|
65
|
+
│ ├── .cursorrules # Cursor IDE guidelines bundled into EVERY generated project!
|
|
66
|
+
│ ├── README.md # Documentation bundled into EVERY generated project!
|
|
67
|
+
│ └── src/ # Modular backend codebase (app, server, modules, config, middlewares, etc.).
|
|
68
|
+
├── AGENTS.md # This file (AI instructions for the CLI package itself).
|
|
69
|
+
├── llms.txt # Condensed LLM knowledge specification.
|
|
70
|
+
├── package.json # CLI tool package manifest.
|
|
71
|
+
└── README.md # Public documentation for developers.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## 4. Key Mechanisms to Know
|
|
77
|
+
|
|
78
|
+
### 1. Role Enum Dynamic Replacement
|
|
79
|
+
In `bin/index.js`, user-defined roles are transformed into TypeScript enum code:
|
|
80
|
+
```javascript
|
|
81
|
+
const enumCode = `export enum Role {\n${roles
|
|
82
|
+
.map((r) => ` ${r.key} = "${r.val}"`)
|
|
83
|
+
.join(",\n")}\n}`;
|
|
84
|
+
```
|
|
85
|
+
It regex-replaces `export enum Role\s*\{[\s\S]*?\}` inside `src/app/modules/user/user.interface.ts`.
|
|
86
|
+
|
|
87
|
+
### 2. Environment Variables Injection
|
|
88
|
+
`bin/index.js` dynamically generates:
|
|
89
|
+
- `JWT_ACCESS_SECRET`: 48 bytes hex (`crypto.randomBytes(48).toString("hex")`)
|
|
90
|
+
- `JWT_REFRESH_SECRET`: 48 bytes hex
|
|
91
|
+
- `SESSION_SECRET`: 24 bytes hex
|
|
92
|
+
|
|
93
|
+
It replaces placeholders in `.env.example` and produces `.env` and `.env.example`.
|
|
94
|
+
|
|
95
|
+
### 3. Safe TTY Handling
|
|
96
|
+
The CLI automatically detects if stdout/stdin is a TTY. If running non-interactively or in non-TTY environments (such as an AI subagent or background task), it logs using standard `console.log` rather than attempting to render interactive TTY prompts or spinners, preventing `ERR_TTY_INIT_FAILED`.
|
package/README.md
CHANGED
|
@@ -11,6 +11,7 @@ Production-grade, modular MongoDB, Express, and TypeScript backend scaffolder.
|
|
|
11
11
|
- [Overview](#overview)
|
|
12
12
|
- [Quick Start](#quick-start)
|
|
13
13
|
- [CLI Setup Modes](#cli-setup-modes)
|
|
14
|
+
- [AI Agent & Non-Interactive Usage](#ai-agent--non-interactive-usage)
|
|
14
15
|
- [Architecture & Directory Structure](#architecture--directory-structure)
|
|
15
16
|
- [Core Capabilities](#core-capabilities)
|
|
16
17
|
- [Authentication & Authorization](#authentication--authorization)
|
|
@@ -91,6 +92,48 @@ Allows comprehensive customization during initialization:
|
|
|
91
92
|
|
|
92
93
|
---
|
|
93
94
|
|
|
95
|
+
## AI Agent & Non-Interactive Usage
|
|
96
|
+
|
|
97
|
+
`create-oikko-mongo` is fully optimized for **AI Agents** (Cursor, Copilot, Claude Code, Devin, Antigravity, Windsurf) and automated CI/CD pipelines.
|
|
98
|
+
|
|
99
|
+
When running inside subagents or non-TTY environments, always specify `--yes` or pass explicit configuration flags to avoid interactive prompt halts:
|
|
100
|
+
|
|
101
|
+
### Examples for AI Agents:
|
|
102
|
+
```bash
|
|
103
|
+
# Instant default scaffolding (Zero prompts)
|
|
104
|
+
npx create-oikko-mongo my-app --yes
|
|
105
|
+
|
|
106
|
+
# Custom configuration in a single command
|
|
107
|
+
npx create-oikko-mongo my-store --roles "customer,seller,admin" --port 8000 --pm pnpm --force
|
|
108
|
+
|
|
109
|
+
# Fast generation skipping npm install
|
|
110
|
+
npx create-oikko-mongo my-api --yes --no-install
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Supported CLI Flags:
|
|
114
|
+
|
|
115
|
+
| Flag | Type | Default | Description |
|
|
116
|
+
| :--- | :--- | :--- | :--- |
|
|
117
|
+
| `[project-name]` | String | `my-oikko-app` | Target project directory name. |
|
|
118
|
+
| `-y, --yes, --default` | Boolean | `false` | Non-interactive execution using defaults or provided flags. |
|
|
119
|
+
| `-f, --force` | Boolean | `false` | Overwrites the destination directory if it already exists. |
|
|
120
|
+
| `--port <port>` | String | `5000` | HTTP port written to `.env`. |
|
|
121
|
+
| `--db <uri>` | String | `mongodb://localhost:27017/<name>` | MongoDB connection string. |
|
|
122
|
+
| `--roles <list>` | String | `user, admin, super_admin` | Comma-separated roles injected into `Role` enum. |
|
|
123
|
+
| `--pm <manager>` | String | `npm` | Package manager: `npm`, `pnpm`, `yarn`, `bun`. |
|
|
124
|
+
| `--latest` | Boolean | `false` | Sets all dependencies to `"latest"` before installing. |
|
|
125
|
+
| `--no-install` | Boolean | `false` | Skips package manager dependency installation. |
|
|
126
|
+
| `-h, --help` | Boolean | `false` | Displays help message and exits. |
|
|
127
|
+
| `-v, --version` | Boolean | `false` | Displays package version and exits. |
|
|
128
|
+
|
|
129
|
+
### Built-in AI Guidelines in Scaffolded Projects
|
|
130
|
+
Every project created with `create-oikko-mongo` automatically bundles:
|
|
131
|
+
- `AGENTS.md` - Complete architectural guidelines, coding patterns, and module generation recipes for AI agents.
|
|
132
|
+
- `.cursorrules` - Rules tailored for Cursor and IDE-based AI assistants.
|
|
133
|
+
- `llms.txt` - High-signal project summary following the `llms.txt` standard.
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
94
137
|
## Architecture & Directory Structure
|
|
95
138
|
|
|
96
139
|
The generated codebase follows a strict modular structure. Each feature domain contains its own controllers, services, interfaces, models, routes, and validation schemas:
|
package/bin/index.js
CHANGED
|
@@ -7,10 +7,12 @@ import path from "path";
|
|
|
7
7
|
import crypto from "crypto";
|
|
8
8
|
import { execSync } from "child_process";
|
|
9
9
|
import { fileURLToPath } from "url";
|
|
10
|
+
import { parseArgs } from "node:util";
|
|
10
11
|
|
|
11
12
|
const __filename = fileURLToPath(import.meta.url);
|
|
12
13
|
const __dirname = path.dirname(__filename);
|
|
13
14
|
const templateDir = path.resolve(__dirname, "../template");
|
|
15
|
+
const pkgJsonPath = path.resolve(__dirname, "../package.json");
|
|
14
16
|
|
|
15
17
|
function generateSecureSecret(bytes = 32) {
|
|
16
18
|
return crypto.randomBytes(bytes).toString("hex");
|
|
@@ -28,170 +30,296 @@ function parseRoles(input) {
|
|
|
28
30
|
});
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (!projectName) {
|
|
39
|
-
projectName = await text({
|
|
40
|
-
message: "What is your project name?",
|
|
41
|
-
placeholder: "my-oikko-app",
|
|
42
|
-
defaultValue: "my-oikko-app",
|
|
43
|
-
validate(value) {
|
|
44
|
-
if (!value.trim()) return "Project name cannot be empty.";
|
|
45
|
-
if (/^[A-Z]/.test(value)) return "Project name must start with a lowercase letter.";
|
|
46
|
-
if (/[^a-z0-9-_]/.test(value)) return "Only lowercase letters, numbers, hyphens, and underscores allowed.";
|
|
47
|
-
},
|
|
48
|
-
});
|
|
33
|
+
function validateProjectName(value) {
|
|
34
|
+
if (!value || !value.trim()) return "Project name cannot be empty.";
|
|
35
|
+
if (/^[A-Z]/.test(value)) return "Project name must start with a lowercase letter.";
|
|
36
|
+
if (/[^a-z0-9-_]/.test(value)) return "Only lowercase letters, numbers, hyphens, and underscores allowed.";
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
49
39
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
40
|
+
const defaultRoles = [
|
|
41
|
+
{ key: "USER", val: "user" },
|
|
42
|
+
{ key: "ADMIN", val: "admin" },
|
|
43
|
+
{ key: "SUPER_ADMIN", val: "super_admin" },
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
async function getPackageVersion() {
|
|
47
|
+
try {
|
|
48
|
+
const pkgData = await fs.readJson(pkgJsonPath);
|
|
49
|
+
return pkgData.version || "1.0.0";
|
|
50
|
+
} catch {
|
|
51
|
+
return "1.0.0";
|
|
54
52
|
}
|
|
53
|
+
}
|
|
55
54
|
|
|
56
|
-
|
|
55
|
+
function printHelp(version) {
|
|
56
|
+
console.log(`
|
|
57
|
+
${color.bold(color.cyan("create-oikko-mongo"))} v${version}
|
|
58
|
+
Production-ready MERN enterprise backend scaffolder by Oikko
|
|
59
|
+
|
|
60
|
+
${color.bold("USAGE:")}
|
|
61
|
+
npx create-oikko-mongo [project-name] [options]
|
|
62
|
+
npm create oikko-mongo [project-name] [options]
|
|
63
|
+
|
|
64
|
+
${color.bold("ARGUMENTS:")}
|
|
65
|
+
[project-name] Directory name for the new project (default: my-oikko-app)
|
|
66
|
+
|
|
67
|
+
${color.bold("OPTIONS:")}
|
|
68
|
+
-y, --yes, --default Non-interactive setup using defaults (Ideal for AI agents & CI/CD)
|
|
69
|
+
-f, --force Overwrite destination directory if it already exists
|
|
70
|
+
--port <port> Backend server port (default: 5000)
|
|
71
|
+
--db <uri> MongoDB connection URI (default: mongodb://localhost:27017/<project-name>)
|
|
72
|
+
--roles <list> Comma-separated user roles (default: user, admin, super_admin)
|
|
73
|
+
--pm <manager> Package manager: npm | pnpm | yarn | bun (default: npm)
|
|
74
|
+
--latest Upgrade all dependencies to latest npm releases
|
|
75
|
+
--no-install Skip running package manager install
|
|
76
|
+
-h, --help Show this help message and exit
|
|
77
|
+
-v, --version Show version number and exit
|
|
78
|
+
|
|
79
|
+
${color.bold("AI AGENT & NON-INTERACTIVE EXAMPLES:")}
|
|
80
|
+
# Instant default scaffolding:
|
|
81
|
+
npx create-oikko-mongo my-app --yes
|
|
82
|
+
|
|
83
|
+
# Custom setup without interactive prompts:
|
|
84
|
+
npx create-oikko-mongo my-store --roles "customer,seller,admin" --port 8000 --pm pnpm --force
|
|
85
|
+
|
|
86
|
+
# Scaffolding without auto-install:
|
|
87
|
+
npx create-oikko-mongo my-api --yes --no-install
|
|
88
|
+
`);
|
|
89
|
+
}
|
|
57
90
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
91
|
+
async function main() {
|
|
92
|
+
const version = await getPackageVersion();
|
|
93
|
+
|
|
94
|
+
// Parse CLI arguments
|
|
95
|
+
const { values, positionals } = parseArgs({
|
|
96
|
+
args: process.argv.slice(2),
|
|
97
|
+
options: {
|
|
98
|
+
help: { type: "boolean", short: "h", default: false },
|
|
99
|
+
version: { type: "boolean", short: "v", default: false },
|
|
100
|
+
yes: { type: "boolean", short: "y", default: false },
|
|
101
|
+
default: { type: "boolean", default: false },
|
|
102
|
+
force: { type: "boolean", short: "f", default: false },
|
|
103
|
+
port: { type: "string" },
|
|
104
|
+
db: { type: "string" },
|
|
105
|
+
roles: { type: "string" },
|
|
106
|
+
pm: { type: "string" },
|
|
107
|
+
latest: { type: "boolean", default: false },
|
|
108
|
+
"no-install": { type: "boolean", default: false },
|
|
109
|
+
install: { type: "boolean", default: true },
|
|
110
|
+
},
|
|
111
|
+
strict: false,
|
|
112
|
+
allowPositionals: true,
|
|
113
|
+
});
|
|
63
114
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
115
|
+
if (values.help) {
|
|
116
|
+
printHelp(version);
|
|
117
|
+
process.exit(0);
|
|
118
|
+
}
|
|
68
119
|
|
|
69
|
-
|
|
120
|
+
if (values.version) {
|
|
121
|
+
console.log(`create-oikko-mongo v${version}`);
|
|
122
|
+
process.exit(0);
|
|
70
123
|
}
|
|
71
124
|
|
|
72
|
-
|
|
73
|
-
const
|
|
74
|
-
message: "Select setup mode:",
|
|
75
|
-
options: [
|
|
76
|
-
{
|
|
77
|
-
value: "default",
|
|
78
|
-
label: "⚡ Default Setup (Recommended)",
|
|
79
|
-
hint: "Instant start with standard roles (USER, ADMIN, SUPER_ADMIN), port 5000 & MongoDB",
|
|
80
|
-
},
|
|
81
|
-
{
|
|
82
|
-
value: "custom",
|
|
83
|
-
label: "🛠️ Custom Setup",
|
|
84
|
-
hint: "Customize roles, port, database URI, and package versions",
|
|
85
|
-
},
|
|
86
|
-
],
|
|
87
|
-
});
|
|
125
|
+
const isTTY = Boolean(process.stdout?.isTTY && process.stdin?.isTTY);
|
|
126
|
+
const isNonInteractive = Boolean(values.yes || values.default || !isTTY);
|
|
88
127
|
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
128
|
+
if (isTTY && !isNonInteractive) {
|
|
129
|
+
console.log();
|
|
130
|
+
intro(color.bold(color.bgCyan(color.black(" 🚀 OIKKO • MERN STARTER (MongoDB + Express + TS) "))));
|
|
131
|
+
} else {
|
|
132
|
+
console.log(color.bold(color.cyan(`\n🚀 OIKKO • MERN STARTER v${version} (Automated/AI Mode)\n`)));
|
|
92
133
|
}
|
|
93
134
|
|
|
94
|
-
//
|
|
95
|
-
let
|
|
96
|
-
let dbUrl = `mongodb://localhost:27017/${projectName}`;
|
|
97
|
-
let roles = [
|
|
98
|
-
{ key: "USER", val: "user" },
|
|
99
|
-
{ key: "ADMIN", val: "admin" },
|
|
100
|
-
{ key: "SUPER_ADMIN", val: "super_admin" },
|
|
101
|
-
];
|
|
102
|
-
let installLatest = false; // Default: Tested & Stable versions
|
|
103
|
-
let packageManager = "npm";
|
|
104
|
-
let runInstall = true;
|
|
105
|
-
|
|
106
|
-
if (setupMode === "custom") {
|
|
107
|
-
// Custom Port
|
|
108
|
-
const portAnswer = await text({
|
|
109
|
-
message: "Backend server PORT:",
|
|
110
|
-
placeholder: "5000",
|
|
111
|
-
defaultValue: "5000",
|
|
112
|
-
});
|
|
113
|
-
if (isCancel(portAnswer)) {
|
|
114
|
-
cancel("Operation cancelled.");
|
|
115
|
-
process.exit(0);
|
|
116
|
-
}
|
|
117
|
-
port = portAnswer.trim() || "5000";
|
|
135
|
+
// 1. Resolve Project Name
|
|
136
|
+
let projectName = positionals[0];
|
|
118
137
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
138
|
+
if (!projectName) {
|
|
139
|
+
if (isNonInteractive) {
|
|
140
|
+
projectName = "my-oikko-app";
|
|
141
|
+
} else {
|
|
142
|
+
projectName = await text({
|
|
143
|
+
message: "What is your project name?",
|
|
144
|
+
placeholder: "my-oikko-app",
|
|
145
|
+
defaultValue: "my-oikko-app",
|
|
146
|
+
validate(value) {
|
|
147
|
+
return validateProjectName(value) || undefined;
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
if (isCancel(projectName)) {
|
|
152
|
+
cancel("Operation cancelled.");
|
|
153
|
+
process.exit(0);
|
|
154
|
+
}
|
|
128
155
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
placeholder: "user, admin, super_admin",
|
|
135
|
-
defaultValue: "user, admin, super_admin",
|
|
136
|
-
hint: "Example: user, seller, admin or student, teacher, admin",
|
|
137
|
-
});
|
|
138
|
-
if (isCancel(rolesAnswer)) {
|
|
139
|
-
cancel("Operation cancelled.");
|
|
140
|
-
process.exit(0);
|
|
156
|
+
} else {
|
|
157
|
+
const error = validateProjectName(projectName);
|
|
158
|
+
if (error) {
|
|
159
|
+
console.error(color.red(`Error: ${error}`));
|
|
160
|
+
process.exit(1);
|
|
141
161
|
}
|
|
142
|
-
|
|
162
|
+
}
|
|
143
163
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
164
|
+
const targetDir = path.resolve(process.cwd(), projectName);
|
|
165
|
+
|
|
166
|
+
// Directory conflict handling
|
|
167
|
+
if (fs.existsSync(targetDir)) {
|
|
168
|
+
if (values.force) {
|
|
169
|
+
await fs.emptyDir(targetDir);
|
|
170
|
+
} else if (isNonInteractive) {
|
|
171
|
+
console.error(color.red(`Error: Target directory "${projectName}" already exists. Use --force to overwrite.`));
|
|
172
|
+
process.exit(1);
|
|
173
|
+
} else {
|
|
174
|
+
const overwrite = await confirm({
|
|
175
|
+
message: `Directory "${projectName}" already exists. Do you want to overwrite it?`,
|
|
176
|
+
initialValue: false,
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
if (isCancel(overwrite) || !overwrite) {
|
|
180
|
+
cancel("Operation cancelled.");
|
|
181
|
+
process.exit(0);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
await fs.emptyDir(targetDir);
|
|
157
185
|
}
|
|
158
|
-
|
|
186
|
+
}
|
|
159
187
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
188
|
+
// 2. Setup Mode & Options Resolution
|
|
189
|
+
let port = values.port || "5000";
|
|
190
|
+
let dbUrl = values.db || `mongodb://localhost:27017/${projectName}`;
|
|
191
|
+
let roles = values.roles ? parseRoles(values.roles) : defaultRoles;
|
|
192
|
+
let installLatest = Boolean(values.latest);
|
|
193
|
+
let packageManager = values.pm || "npm";
|
|
194
|
+
let runInstall = values["no-install"] ? false : Boolean(values.install);
|
|
195
|
+
|
|
196
|
+
if (!isNonInteractive) {
|
|
197
|
+
const setupMode = await select({
|
|
198
|
+
message: "Select setup mode:",
|
|
163
199
|
options: [
|
|
164
200
|
{
|
|
165
|
-
value: "
|
|
166
|
-
label: "
|
|
167
|
-
hint: "
|
|
201
|
+
value: "default",
|
|
202
|
+
label: "⚡ Default Setup (Recommended)",
|
|
203
|
+
hint: "Instant start with standard roles (USER, ADMIN, SUPER_ADMIN), port 5000 & MongoDB",
|
|
168
204
|
},
|
|
169
205
|
{
|
|
170
|
-
value: "
|
|
171
|
-
label: "
|
|
172
|
-
hint: "
|
|
206
|
+
value: "custom",
|
|
207
|
+
label: "🛠️ Custom Setup",
|
|
208
|
+
hint: "Customize roles, port, database URI, and package versions",
|
|
173
209
|
},
|
|
174
210
|
],
|
|
175
211
|
});
|
|
176
|
-
|
|
212
|
+
|
|
213
|
+
if (isCancel(setupMode)) {
|
|
177
214
|
cancel("Operation cancelled.");
|
|
178
215
|
process.exit(0);
|
|
179
216
|
}
|
|
180
|
-
installLatest = versionStrategy === "latest";
|
|
181
217
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
218
|
+
if (setupMode === "custom") {
|
|
219
|
+
// Custom Port
|
|
220
|
+
const portAnswer = await text({
|
|
221
|
+
message: "Backend server PORT:",
|
|
222
|
+
placeholder: "5000",
|
|
223
|
+
defaultValue: port,
|
|
224
|
+
});
|
|
225
|
+
if (isCancel(portAnswer)) {
|
|
226
|
+
cancel("Operation cancelled.");
|
|
227
|
+
process.exit(0);
|
|
228
|
+
}
|
|
229
|
+
port = portAnswer.trim() || "5000";
|
|
230
|
+
|
|
231
|
+
// Custom DB URL
|
|
232
|
+
const dbAnswer = await text({
|
|
233
|
+
message: "MongoDB connection URI:",
|
|
234
|
+
placeholder: `mongodb://localhost:27017/${projectName}`,
|
|
235
|
+
defaultValue: dbUrl,
|
|
236
|
+
});
|
|
237
|
+
if (isCancel(dbAnswer)) {
|
|
238
|
+
cancel("Operation cancelled.");
|
|
239
|
+
process.exit(0);
|
|
240
|
+
}
|
|
241
|
+
dbUrl = dbAnswer.trim() || `mongodb://localhost:27017/${projectName}`;
|
|
242
|
+
|
|
243
|
+
// Custom Roles
|
|
244
|
+
const rolesAnswer = await text({
|
|
245
|
+
message: "Define User Roles (comma-separated):",
|
|
246
|
+
placeholder: "user, admin, super_admin",
|
|
247
|
+
defaultValue: roles.map((r) => r.val).join(", "),
|
|
248
|
+
hint: "Example: user, seller, admin or student, teacher, admin",
|
|
249
|
+
});
|
|
250
|
+
if (isCancel(rolesAnswer)) {
|
|
251
|
+
cancel("Operation cancelled.");
|
|
252
|
+
process.exit(0);
|
|
253
|
+
}
|
|
254
|
+
roles = parseRoles(rolesAnswer);
|
|
255
|
+
|
|
256
|
+
// Package Manager
|
|
257
|
+
const pmAnswer = await select({
|
|
258
|
+
message: "Select package manager:",
|
|
259
|
+
options: [
|
|
260
|
+
{ value: "npm", label: "npm" },
|
|
261
|
+
{ value: "pnpm", label: "pnpm" },
|
|
262
|
+
{ value: "yarn", label: "yarn" },
|
|
263
|
+
{ value: "bun", label: "bun" },
|
|
264
|
+
],
|
|
265
|
+
});
|
|
266
|
+
if (isCancel(pmAnswer)) {
|
|
267
|
+
cancel("Operation cancelled.");
|
|
268
|
+
process.exit(0);
|
|
269
|
+
}
|
|
270
|
+
packageManager = pmAnswer;
|
|
271
|
+
|
|
272
|
+
// Dependency Version Strategy
|
|
273
|
+
const versionStrategy = await select({
|
|
274
|
+
message: "Dependency version strategy:",
|
|
275
|
+
options: [
|
|
276
|
+
{
|
|
277
|
+
value: "stable",
|
|
278
|
+
label: "🛡️ Tested & Stable (Recommended)",
|
|
279
|
+
hint: "Uses tested SemVer ranges with caret (^). Prevents breaking changes.",
|
|
280
|
+
},
|
|
281
|
+
{
|
|
282
|
+
value: "latest",
|
|
283
|
+
label: "⚡ Bleeding Edge (latest)",
|
|
284
|
+
hint: "Forces latest releases from npm registry. May introduce breaking changes.",
|
|
285
|
+
},
|
|
286
|
+
],
|
|
287
|
+
});
|
|
288
|
+
if (isCancel(versionStrategy)) {
|
|
289
|
+
cancel("Operation cancelled.");
|
|
290
|
+
process.exit(0);
|
|
291
|
+
}
|
|
292
|
+
installLatest = versionStrategy === "latest";
|
|
293
|
+
|
|
294
|
+
// Install dependencies now
|
|
295
|
+
const installAnswer = await confirm({
|
|
296
|
+
message: "Run package installation now?",
|
|
297
|
+
initialValue: true,
|
|
298
|
+
});
|
|
299
|
+
if (isCancel(installAnswer)) {
|
|
300
|
+
cancel("Operation cancelled.");
|
|
301
|
+
process.exit(0);
|
|
302
|
+
}
|
|
303
|
+
runInstall = installAnswer;
|
|
190
304
|
}
|
|
191
|
-
runInstall = installAnswer;
|
|
192
305
|
}
|
|
193
306
|
|
|
194
|
-
|
|
307
|
+
// Spinner / Progress helper that works safely in both TTY and non-TTY (AI agents/subprocesses)
|
|
308
|
+
const createSafeSpinner = () => {
|
|
309
|
+
if (!isTTY) {
|
|
310
|
+
return {
|
|
311
|
+
start(msg) {
|
|
312
|
+
console.log(color.cyan(`⏳ ${msg}`));
|
|
313
|
+
},
|
|
314
|
+
stop(msg) {
|
|
315
|
+
console.log(color.green(`${msg}`));
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
return spinner();
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const s = createSafeSpinner();
|
|
195
323
|
s.start(`Scaffolding project in ${color.cyan(projectName)}...`);
|
|
196
324
|
|
|
197
325
|
// 1. Copy template files
|
|
@@ -203,14 +331,13 @@ async function main() {
|
|
|
203
331
|
await fs.rename(gitignorePath, path.join(targetDir, ".gitignore"));
|
|
204
332
|
}
|
|
205
333
|
|
|
206
|
-
// 3. Update package.json
|
|
334
|
+
// 3. Update package.json & README.md
|
|
207
335
|
const pkgPath = path.join(targetDir, "package.json");
|
|
208
336
|
if (await fs.pathExists(pkgPath)) {
|
|
209
337
|
const pkg = await fs.readJson(pkgPath);
|
|
210
338
|
pkg.name = projectName;
|
|
211
339
|
|
|
212
340
|
if (installLatest) {
|
|
213
|
-
// Update all to "latest"
|
|
214
341
|
for (const dep of Object.keys(pkg.dependencies || {})) {
|
|
215
342
|
pkg.dependencies[dep] = "latest";
|
|
216
343
|
}
|
|
@@ -222,6 +349,13 @@ async function main() {
|
|
|
222
349
|
await fs.writeJson(pkgPath, pkg, { spaces: 2 });
|
|
223
350
|
}
|
|
224
351
|
|
|
352
|
+
const readmePath = path.join(targetDir, "README.md");
|
|
353
|
+
if (await fs.pathExists(readmePath)) {
|
|
354
|
+
let readmeContent = await fs.readFile(readmePath, "utf-8");
|
|
355
|
+
readmeContent = readmeContent.replace(/\{\{PROJECT_NAME\}\}/g, projectName);
|
|
356
|
+
await fs.writeFile(readmePath, readmeContent, "utf-8");
|
|
357
|
+
}
|
|
358
|
+
|
|
225
359
|
// 4. Dynamically Inject Roles into user.interface.ts
|
|
226
360
|
const userInterfacePath = path.join(targetDir, "src/app/modules/user/user.interface.ts");
|
|
227
361
|
if (await fs.pathExists(userInterfacePath)) {
|
|
@@ -285,9 +419,13 @@ async function main() {
|
|
|
285
419
|
}
|
|
286
420
|
|
|
287
421
|
console.log();
|
|
288
|
-
|
|
422
|
+
if (isTTY && !isNonInteractive) {
|
|
423
|
+
outro(color.bold(color.green(`🎉 Success! Your Oikko MongoDB project is ready at ./${projectName}`)));
|
|
424
|
+
} else {
|
|
425
|
+
console.log(color.bold(color.green(`🎉 Success! Your Oikko MongoDB project is ready at ./${projectName}\n`)));
|
|
426
|
+
}
|
|
289
427
|
|
|
290
|
-
console.log(color.cyan("
|
|
428
|
+
console.log(color.cyan("Next steps:"));
|
|
291
429
|
console.log(` ${color.white(`cd ${projectName}`)}`);
|
|
292
430
|
if (!runInstall) {
|
|
293
431
|
console.log(` ${color.white(`${packageManager} install`)}`);
|
package/llms.txt
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# create-oikko-mongo
|
|
2
|
+
> Production-grade, modular MongoDB, Express, and TypeScript enterprise backend scaffolder by Oikko.
|
|
3
|
+
|
|
4
|
+
This file provides LLMs and AI Agents with complete context on `create-oikko-mongo`, including CLI execution syntax, non-interactive flags, architecture, and coding conventions.
|
|
5
|
+
|
|
6
|
+
## Quick Reference for AI Agents
|
|
7
|
+
|
|
8
|
+
When executing `create-oikko-mongo` from an AI Agent or automated script, ALWAYS use non-interactive flags to prevent TTY input blocking:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
# Default setup (Recommended for AI agents):
|
|
12
|
+
npx create-oikko-mongo <project-name> --yes
|
|
13
|
+
|
|
14
|
+
# With custom parameters:
|
|
15
|
+
npx create-oikko-mongo <project-name> --roles "user,admin,seller" --port 8000 --pm npm --yes
|
|
16
|
+
|
|
17
|
+
# Fast scaffold without immediate npm install:
|
|
18
|
+
npx create-oikko-mongo <project-name> --yes --no-install
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### CLI Command Options
|
|
22
|
+
|
|
23
|
+
- `[project-name]` (positional): Name of the target directory (default: `my-oikko-app`).
|
|
24
|
+
- `-y, --yes, --default`: Run in non-interactive mode using defaults.
|
|
25
|
+
- `-f, --force`: Overwrite target directory if it already exists.
|
|
26
|
+
- `--port <number>`: HTTP server port (default: `5000`).
|
|
27
|
+
- `--db <uri>`: MongoDB connection URI (default: `mongodb://localhost:27017/<project-name>`).
|
|
28
|
+
- `--roles <list>`: Comma-separated list of roles (e.g. `user, admin, seller`).
|
|
29
|
+
- `--pm <manager>`: Package manager (`npm` | `pnpm` | `yarn` | `bun`, default: `npm`).
|
|
30
|
+
- `--latest`: Forces latest npm versions for all dependencies.
|
|
31
|
+
- `--no-install`: Skips running `npm install`.
|
|
32
|
+
- `-h, --help`: Displays CLI help and exits.
|
|
33
|
+
- `-v, --version`: Displays package version and exits.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Scaffolded Architecture & Project Layout
|
|
38
|
+
|
|
39
|
+
Each project bootstrapped by `create-oikko-mongo` strictly follows a modular enterprise architecture:
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
<project-name>/
|
|
43
|
+
├── src/
|
|
44
|
+
│ ├── app.ts # Express app configuration & middleware pipeline
|
|
45
|
+
│ ├── server.ts # Server bootstrap, DB & unhandled rejection handlers
|
|
46
|
+
│ └── app/
|
|
47
|
+
│ ├── config/ # Config modules
|
|
48
|
+
│ │ ├── db.ts # Mongoose connection logic
|
|
49
|
+
│ │ ├── env.ts # Type-safe environment validation
|
|
50
|
+
│ │ ├── passport.ts # Local & Google OAuth strategies
|
|
51
|
+
│ │ └── redis.config.ts # Redis client & connection
|
|
52
|
+
│ ├── errorHelpers/ # Custom AppError class
|
|
53
|
+
│ │ └── appError.ts
|
|
54
|
+
│ ├── helpers/ # Error parsers (Zod, Mongoose Cast, Duplicate Key)
|
|
55
|
+
│ ├── interfaces/ # Global type declaration merging
|
|
56
|
+
│ │ └── index.d.ts # Express.Request user typing
|
|
57
|
+
│ ├── middlewares/
|
|
58
|
+
│ │ ├── checkAuth.ts # JWT verification & RBAC authorization
|
|
59
|
+
│ │ ├── globalErrorHandler.ts # Centralized HTTP error handler
|
|
60
|
+
│ │ ├── notFound.ts # 404 Route handler
|
|
61
|
+
│ │ ├── requestLogger.ts # Winston HTTP request logger
|
|
62
|
+
│ │ └── validateRequest.ts # Zod request validation middleware
|
|
63
|
+
│ ├── modules/ # Domain business modules
|
|
64
|
+
│ │ ├── auth/ # Login, OAuth, tokens, password recovery
|
|
65
|
+
│ │ ├── otp/ # OTP dispatch & verification
|
|
66
|
+
│ │ └── user/ # User CRUD, profiles, roles
|
|
67
|
+
│ ├── routes/
|
|
68
|
+
│ │ └── index.ts # Application router aggregation
|
|
69
|
+
│ └── utils/
|
|
70
|
+
│ ├── catchAsync.ts # Async try-catch wrapper for controllers
|
|
71
|
+
│ ├── logger.ts # Winston file & console logging
|
|
72
|
+
│ ├── sendEmail.ts # Nodemailer / Resend email service
|
|
73
|
+
│ ├── sendResponse.ts # Standardized API response utility
|
|
74
|
+
│ └── userTokens.ts # JWT token signing & verification
|
|
75
|
+
├── .env # Auto-populated with cryptographically secure secrets
|
|
76
|
+
├── .env.example # Reference environment variables
|
|
77
|
+
├── .gitignore
|
|
78
|
+
├── package.json
|
|
79
|
+
└── tsconfig.json
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## Coding Conventions for Generated Code
|
|
85
|
+
|
|
86
|
+
When an AI Agent writes code for an application created with `create-oikko-mongo`, adhere to these patterns:
|
|
87
|
+
|
|
88
|
+
### 1. Modular Directory Layout
|
|
89
|
+
Each feature lives in `src/app/modules/<featureName>/`:
|
|
90
|
+
- `<feature>.interface.ts`: TypeScript types and enums
|
|
91
|
+
- `<feature>.validation.ts`: Zod validation schemas
|
|
92
|
+
- `<feature>.model.ts`: Mongoose schema and model
|
|
93
|
+
- `<feature>.service.ts`: Business logic & database operations
|
|
94
|
+
- `<feature>.controller.ts`: HTTP request/response handlers wrapped in `catchAsync`
|
|
95
|
+
- `<feature>.route.ts`: Express routes with `validateRequest` and `checkAuth`
|
|
96
|
+
|
|
97
|
+
### 2. Controller Pattern
|
|
98
|
+
Always wrap controllers in `catchAsync` and respond using `sendResponse`:
|
|
99
|
+
```typescript
|
|
100
|
+
import { Request, Response } from "express";
|
|
101
|
+
import httpStatus from "http-status-codes";
|
|
102
|
+
import { catchAsync } from "../../utils/catchAsync";
|
|
103
|
+
import { sendResponse } from "../../utils/sendResponse";
|
|
104
|
+
import { ItemServices } from "./item.service";
|
|
105
|
+
|
|
106
|
+
const createItem = catchAsync(async (req: Request, res: Response) => {
|
|
107
|
+
const result = await ItemServices.createItemService(req.body);
|
|
108
|
+
sendResponse(res, {
|
|
109
|
+
success: true,
|
|
110
|
+
statusCode: httpStatus.CREATED,
|
|
111
|
+
message: "Item created successfully",
|
|
112
|
+
data: result,
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### 3. Error Handling
|
|
118
|
+
Never throw raw strings or generic errors. Throw `AppError`:
|
|
119
|
+
```typescript
|
|
120
|
+
import httpStatus from "http-status-codes";
|
|
121
|
+
import AppError from "../../errorHelpers/appError";
|
|
122
|
+
|
|
123
|
+
if (!item) {
|
|
124
|
+
throw new AppError(httpStatus.NOT_FOUND, "Item not found");
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### 4. Role-Based Access Control
|
|
129
|
+
Enforce RBAC via `checkAuth`:
|
|
130
|
+
```typescript
|
|
131
|
+
import { Router } from "express";
|
|
132
|
+
import { checkAuth } from "../../middlewares/checkAuth";
|
|
133
|
+
import { Role } from "../user/user.interface";
|
|
134
|
+
|
|
135
|
+
router.post("/manage", checkAuth(Role.ADMIN, Role.SUPER_ADMIN), ItemController.manage);
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### 5. Request Validation
|
|
139
|
+
Enforce payload validation using Zod:
|
|
140
|
+
```typescript
|
|
141
|
+
import { validateRequest } from "../../middlewares/validateRequest";
|
|
142
|
+
import { ItemValidation } from "./item.validation";
|
|
143
|
+
|
|
144
|
+
router.post("/", validateRequest(ItemValidation.createItemSchema), ItemController.createItem);
|
|
145
|
+
```
|
package/package.json
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-oikko-mongo",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "Production-ready MERN (MongoDB + Express + TypeScript) enterprise backend scaffolder by Oikko",
|
|
5
5
|
"main": "./bin/index.js",
|
|
6
6
|
"bin": {
|
|
7
|
-
"create-oikko-mongo": "
|
|
7
|
+
"create-oikko-mongo": "bin/index.js"
|
|
8
8
|
},
|
|
9
9
|
"type": "module",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/hassan-nahid/create-oikko-mongo.git"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/hassan-nahid/create-oikko-mongo/issues"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/hassan-nahid/create-oikko-mongo#readme",
|
|
10
18
|
"keywords": [
|
|
11
19
|
"oikko",
|
|
12
20
|
"mern",
|
|
@@ -16,7 +24,10 @@
|
|
|
16
24
|
"boilerplate",
|
|
17
25
|
"starter",
|
|
18
26
|
"scaffolder",
|
|
19
|
-
"cli"
|
|
27
|
+
"cli",
|
|
28
|
+
"ai-agent",
|
|
29
|
+
"llms-txt",
|
|
30
|
+
"cursorrules"
|
|
20
31
|
],
|
|
21
32
|
"author": "Hassan Nahid",
|
|
22
33
|
"license": "MIT",
|
|
@@ -31,6 +42,8 @@
|
|
|
31
42
|
"files": [
|
|
32
43
|
"bin",
|
|
33
44
|
"template",
|
|
34
|
-
"README.md"
|
|
45
|
+
"README.md",
|
|
46
|
+
"AGENTS.md",
|
|
47
|
+
"llms.txt"
|
|
35
48
|
]
|
|
36
49
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Cursor Rules for Oikko MERN Backend
|
|
2
|
+
|
|
3
|
+
You are an expert full-stack developer working on a production MERN enterprise backend.
|
|
4
|
+
|
|
5
|
+
## Architectural Principles
|
|
6
|
+
- Modular Clean Architecture: every domain entity lives in `src/app/modules/<entity>/`.
|
|
7
|
+
- Layered separation: Interface -> Model -> Validation -> Service -> Controller -> Route.
|
|
8
|
+
- Register all domain routes in `src/app/routes/index.ts`.
|
|
9
|
+
|
|
10
|
+
## Strict Code Standards
|
|
11
|
+
1. Controllers:
|
|
12
|
+
- Always wrap asynchronous functions using `catchAsync`.
|
|
13
|
+
- Never use manual `res.status().json()`; always use `sendResponse(res, { success, statusCode, message, data, meta })`.
|
|
14
|
+
2. Error Handling:
|
|
15
|
+
- Throw `AppError(statusCode, message)` from `src/app/errorHelpers/appError.ts`.
|
|
16
|
+
- Never throw raw strings or generic errors.
|
|
17
|
+
3. Validation:
|
|
18
|
+
- Use Zod schemas with `validateRequest` middleware on routes.
|
|
19
|
+
4. Security & RBAC:
|
|
20
|
+
- Protect endpoints using `checkAuth(...allowedRoles)`.
|
|
21
|
+
- Use `Role` enum from `src/app/modules/user/user.interface.ts`.
|
|
22
|
+
5. Configuration:
|
|
23
|
+
- Always import env vars from `src/app/config/env.ts`, never raw `process.env`.
|
|
24
|
+
6. Database:
|
|
25
|
+
- Use Mongoose models with proper TypeScript types (`IUser`, etc.).
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# AI Agent Guidelines & Architecture Rules
|
|
2
|
+
|
|
3
|
+
Welcome AI Coding Assistant! This project is an enterprise MERN (MongoDB + Express + TypeScript) backend bootstrapped with `create-oikko-mongo`.
|
|
4
|
+
|
|
5
|
+
Follow these rules and conventions strictly when reading, generating, or refactoring code in this repository.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Core Architectural Pattern
|
|
10
|
+
|
|
11
|
+
This codebase strictly adheres to the **Modular Clean Architecture** pattern.
|
|
12
|
+
|
|
13
|
+
Every business domain lives in `src/app/modules/<moduleName>/`.
|
|
14
|
+
A complete module contains:
|
|
15
|
+
```
|
|
16
|
+
src/app/modules/<moduleName>/
|
|
17
|
+
├── <moduleName>.interface.ts # TypeScript interfaces, types & enums
|
|
18
|
+
├── <moduleName>.validation.ts # Zod validation schemas
|
|
19
|
+
├── <moduleName>.model.ts # Mongoose Schema & Model definitions
|
|
20
|
+
├── <moduleName>.service.ts # Pure business logic and database operations
|
|
21
|
+
├── <moduleName>.controller.ts # HTTP request/response handling (wrapped in catchAsync)
|
|
22
|
+
└── <moduleName>.route.ts # Express router definitions with middlewares
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Module Registration
|
|
26
|
+
Every new module route MUST be registered in `src/app/routes/index.ts`:
|
|
27
|
+
```typescript
|
|
28
|
+
const moduleRoutes = [
|
|
29
|
+
{ path: "/user", route: UserRoutes },
|
|
30
|
+
{ path: "/auth", route: AuthRoutes },
|
|
31
|
+
{ path: "/otp", route: OtpRoutes },
|
|
32
|
+
// Add new module routes here
|
|
33
|
+
];
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 2. Coding Rules & Best Practices
|
|
39
|
+
|
|
40
|
+
### Rule 1: Always use `catchAsync` in Controllers
|
|
41
|
+
Never use raw `try/catch` inside controllers. Always wrap async controller functions with `catchAsync`:
|
|
42
|
+
```typescript
|
|
43
|
+
import { Request, Response } from "express";
|
|
44
|
+
import httpStatus from "http-status-codes";
|
|
45
|
+
import { catchAsync } from "../../utils/catchAsync";
|
|
46
|
+
import { sendResponse } from "../../utils/sendResponse";
|
|
47
|
+
import { ProductServices } from "./product.service";
|
|
48
|
+
|
|
49
|
+
const createProduct = catchAsync(async (req: Request, res: Response) => {
|
|
50
|
+
const result = await ProductServices.createProductService(req.body);
|
|
51
|
+
sendResponse(res, {
|
|
52
|
+
success: true,
|
|
53
|
+
statusCode: httpStatus.CREATED,
|
|
54
|
+
message: "Product created successfully",
|
|
55
|
+
data: result,
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Rule 2: Always use `sendResponse` for API Responses
|
|
61
|
+
All successful API responses must conform to the unified envelope structure:
|
|
62
|
+
```typescript
|
|
63
|
+
sendResponse(res, {
|
|
64
|
+
success: true,
|
|
65
|
+
statusCode: httpStatus.OK,
|
|
66
|
+
message: "Data retrieved successfully",
|
|
67
|
+
data: result.data,
|
|
68
|
+
meta: result.meta, // Optional pagination meta: { page, limit, total, totalPage }
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Rule 3: Error Handling & `AppError`
|
|
73
|
+
- Never throw generic `Error` or string messages.
|
|
74
|
+
- Always throw `AppError` with a proper HTTP status code from `http-status-codes`:
|
|
75
|
+
```typescript
|
|
76
|
+
import httpStatus from "http-status-codes";
|
|
77
|
+
import AppError from "../../errorHelpers/appError";
|
|
78
|
+
|
|
79
|
+
if (!product) {
|
|
80
|
+
throw new AppError(httpStatus.NOT_FOUND, "Product not found");
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
All errors will be caught and formatted centrally by `src/app/middlewares/globalErrorHandler.ts`.
|
|
84
|
+
|
|
85
|
+
### Rule 4: Request Validation with Zod
|
|
86
|
+
Always validate incoming requests before reaching the controller.
|
|
87
|
+
1. Define schema in `<moduleName>.validation.ts`:
|
|
88
|
+
```typescript
|
|
89
|
+
import { z } from "zod";
|
|
90
|
+
|
|
91
|
+
const createProductSchema = z.object({
|
|
92
|
+
body: z.object({
|
|
93
|
+
title: z.string().min(1, "Title is required"),
|
|
94
|
+
price: z.number().positive("Price must be positive"),
|
|
95
|
+
}),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export const ProductValidation = {
|
|
99
|
+
createProductSchema,
|
|
100
|
+
};
|
|
101
|
+
```
|
|
102
|
+
2. Attach `validateRequest` middleware to the route:
|
|
103
|
+
```typescript
|
|
104
|
+
import { Router } from "express";
|
|
105
|
+
import { validateRequest } from "../../middlewares/validateRequest";
|
|
106
|
+
import { ProductValidation } from "./product.validation";
|
|
107
|
+
import { ProductController } from "./product.controller";
|
|
108
|
+
|
|
109
|
+
const router = Router();
|
|
110
|
+
router.post(
|
|
111
|
+
"/create",
|
|
112
|
+
validateRequest(ProductValidation.createProductSchema),
|
|
113
|
+
ProductController.createProduct
|
|
114
|
+
);
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Rule 5: Authentication & Role-Based Access Control (RBAC)
|
|
118
|
+
Protect routes using `checkAuth` middleware:
|
|
119
|
+
- Unrestricted authenticated access: `checkAuth()`
|
|
120
|
+
- Role-restricted access: `checkAuth(Role.ADMIN, Role.SUPER_ADMIN)`
|
|
121
|
+
```typescript
|
|
122
|
+
import { checkAuth } from "../../middlewares/checkAuth";
|
|
123
|
+
import { Role } from "../user/user.interface";
|
|
124
|
+
|
|
125
|
+
router.delete("/:id", checkAuth(Role.ADMIN, Role.SUPER_ADMIN), ProductController.deleteProduct);
|
|
126
|
+
```
|
|
127
|
+
Access the decoded user token in controllers:
|
|
128
|
+
```typescript
|
|
129
|
+
import { JwtPayload } from "jsonwebtoken";
|
|
130
|
+
|
|
131
|
+
const getMyProducts = catchAsync(async (req: Request, res: Response) => {
|
|
132
|
+
const user = req.user as JwtPayload;
|
|
133
|
+
const result = await ProductServices.getProductsByUser(user.userId);
|
|
134
|
+
// ...
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Rule 6: Accessing Environment Variables
|
|
139
|
+
Never access `process.env.VARIABLE_NAME` directly across the codebase.
|
|
140
|
+
Always import the validated, type-safe configuration from `src/app/config/env.ts`:
|
|
141
|
+
```typescript
|
|
142
|
+
import env from "../config/env";
|
|
143
|
+
|
|
144
|
+
const port = env.PORT;
|
|
145
|
+
const dbUrl = env.DB_URL;
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## 3. Workflow for Adding a New Feature
|
|
151
|
+
|
|
152
|
+
When requested to create a new feature (e.g. `order`):
|
|
153
|
+
1. **Interface**: Create `src/app/modules/order/order.interface.ts`.
|
|
154
|
+
2. **Schema & Model**: Create `src/app/modules/order/order.model.ts` using Mongoose.
|
|
155
|
+
3. **Validation**: Create `src/app/modules/order/order.validation.ts` using Zod.
|
|
156
|
+
4. **Service**: Create `src/app/modules/order/order.service.ts` with business logic and database queries.
|
|
157
|
+
5. **Controller**: Create `src/app/modules/order/order.controller.ts` with handlers wrapped in `catchAsync`.
|
|
158
|
+
6. **Route**: Create `src/app/modules/order/order.route.ts` with validations and auth guards.
|
|
159
|
+
7. **Registration**: Export `OrderRoutes` and mount in `src/app/routes/index.ts`.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# {{PROJECT_NAME}}
|
|
2
|
+
|
|
3
|
+
Enterprise MERN (MongoDB + Express + TypeScript) Backend API generated by **create-oikko-mongo**.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 🚀 Getting Started
|
|
8
|
+
|
|
9
|
+
### 1. Prerequisites
|
|
10
|
+
- Node.js >= 18.0.0
|
|
11
|
+
- MongoDB instance (local or MongoDB Atlas)
|
|
12
|
+
- Redis server (optional, for caching & token blacklisting)
|
|
13
|
+
|
|
14
|
+
### 2. Installation
|
|
15
|
+
```bash
|
|
16
|
+
npm install
|
|
17
|
+
# or pnpm install / yarn install / bun install
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### 3. Environment Setup
|
|
21
|
+
Review and configure your `.env` file (copied automatically from `.env.example` with auto-generated secure secrets):
|
|
22
|
+
```env
|
|
23
|
+
PORT=5000
|
|
24
|
+
DB_URL=mongodb://localhost:27017/{{PROJECT_NAME}}
|
|
25
|
+
NODE_ENV=development
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### 4. Run Development Server
|
|
29
|
+
```bash
|
|
30
|
+
npm run dev
|
|
31
|
+
```
|
|
32
|
+
The server will start listening at `http://localhost:5000`.
|
|
33
|
+
|
|
34
|
+
### 5. Build & Production Run
|
|
35
|
+
```bash
|
|
36
|
+
# Build TypeScript
|
|
37
|
+
npm run build
|
|
38
|
+
|
|
39
|
+
# Start production server
|
|
40
|
+
npm start
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 📁 Architecture & Directory Structure
|
|
46
|
+
|
|
47
|
+
This project follows **Modular Clean Architecture**:
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
src/
|
|
51
|
+
├── app.ts # Express application setup
|
|
52
|
+
├── server.ts # HTTP server bootstrap & DB listeners
|
|
53
|
+
└── app/
|
|
54
|
+
├── config/ # Environment, DB, Passport & Redis configs
|
|
55
|
+
├── errorHelpers/ # AppError class
|
|
56
|
+
├── helpers/ # Error normalization helpers
|
|
57
|
+
├── interfaces/ # Global TypeScript declaration merging
|
|
58
|
+
├── middlewares/ # checkAuth, validateRequest, globalErrorHandler, etc.
|
|
59
|
+
├── modules/ # Business domains (auth, user, otp, etc.)
|
|
60
|
+
├── routes/ # Central route aggregator
|
|
61
|
+
└── utils/ # Utilities (catchAsync, sendResponse, sendEmail, etc.)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## 🛡️ Default API Endpoints
|
|
67
|
+
|
|
68
|
+
- **Auth** (`/api/v1/auth`)
|
|
69
|
+
- `POST /login` - User login
|
|
70
|
+
- `POST /refresh-token` - Refresh access token
|
|
71
|
+
- `POST /logout` - Logout & clear token cookies
|
|
72
|
+
- `POST /forgot-password` - Request password reset
|
|
73
|
+
- `POST /reset-password` - Reset password with token
|
|
74
|
+
- `POST /change-password` - Change password (authenticated)
|
|
75
|
+
- `GET /google` - Google OAuth initiation
|
|
76
|
+
- `GET /google/callback` - Google OAuth callback
|
|
77
|
+
|
|
78
|
+
- **Users** (`/api/v1/user`)
|
|
79
|
+
- `POST /register` - Register a new user
|
|
80
|
+
- `GET /me` - Get profile of authenticated user
|
|
81
|
+
- `GET /all-users` - Retrieve all users (Admin only)
|
|
82
|
+
|
|
83
|
+
- **OTP** (`/api/v1/otp`)
|
|
84
|
+
- `POST /send-otp` - Dispatch OTP to email
|
|
85
|
+
- `POST /verify-otp` - Verify received OTP
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 🤖 AI Agent Guidelines
|
|
90
|
+
|
|
91
|
+
If you or your team use AI coding assistants (e.g. Cursor, Copilot, Claude Code, Antigravity), see [`AGENTS.md`](./AGENTS.md) and [`.cursorrules`](./.cursorrules) for code standards, conventions, and module creation recipes.
|