create-oikko-mongo 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/README.md +275 -0
- package/bin/index.js +302 -0
- package/package.json +36 -0
- package/template/.env.example +82 -0
- package/template/_gitignore +6 -0
- package/template/package.json +50 -0
- package/template/src/app/config/env.ts +190 -0
- package/template/src/app/config/passport.ts +112 -0
- package/template/src/app/config/r2.config.ts +15 -0
- package/template/src/app/config/redis.config.ts +21 -0
- package/template/src/app/errorHelpers/AppError.ts +16 -0
- package/template/src/app/helpers/handleCastError.ts +10 -0
- package/template/src/app/helpers/handleDuplicateError.ts +12 -0
- package/template/src/app/helpers/handleValidationError.ts +19 -0
- package/template/src/app/helpers/handleZodError.ts +26 -0
- package/template/src/app/interfaces/error.Types.ts +10 -0
- package/template/src/app/interfaces/index.d.ts +8 -0
- package/template/src/app/middlewares/checkAuth.ts +54 -0
- package/template/src/app/middlewares/globalErrorHandler.ts +78 -0
- package/template/src/app/middlewares/notFound.ts +18 -0
- package/template/src/app/middlewares/requestLogger.ts +20 -0
- package/template/src/app/middlewares/validateRequest.ts +21 -0
- package/template/src/app/modules/auth/auth.controller.ts +184 -0
- package/template/src/app/modules/auth/auth.route.ts +27 -0
- package/template/src/app/modules/auth/auth.service.ts +136 -0
- package/template/src/app/modules/auth/auth.validation.ts +53 -0
- package/template/src/app/modules/auth/jwt.ts +16 -0
- package/template/src/app/modules/otp/otp.controller.ts +32 -0
- package/template/src/app/modules/otp/otp.route.ts +12 -0
- package/template/src/app/modules/otp/otp.service.ts +120 -0
- package/template/src/app/modules/otp/otp.validation.ts +27 -0
- package/template/src/app/modules/user/user.constant.ts +1 -0
- package/template/src/app/modules/user/user.controller.ts +55 -0
- package/template/src/app/modules/user/user.interface.ts +41 -0
- package/template/src/app/modules/user/user.model.ts +44 -0
- package/template/src/app/modules/user/user.route.ts +20 -0
- package/template/src/app/modules/user/user.service.ts +79 -0
- package/template/src/app/modules/user/user.validation.ts +77 -0
- package/template/src/app/routes/index.ts +25 -0
- package/template/src/app/utils/catchAsync.ts +10 -0
- package/template/src/app/utils/constants.ts +1 -0
- package/template/src/app/utils/logger.ts +68 -0
- package/template/src/app/utils/queryBuilder.ts +83 -0
- package/template/src/app/utils/sendEmail.ts +62 -0
- package/template/src/app/utils/sendResponse.ts +26 -0
- package/template/src/app/utils/setCookie.ts +34 -0
- package/template/src/app/utils/templates/forgetPassword.ejs +76 -0
- package/template/src/app/utils/templates/otp.ejs +76 -0
- package/template/src/app/utils/templates/resetPassword.ejs +121 -0
- package/template/src/app/utils/userTokens.ts +52 -0
- package/template/src/app.ts +44 -0
- package/template/src/server.ts +66 -0
- package/template/tsconfig.json +14 -0
package/README.md
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
# create-oikko-mongo
|
|
2
|
+
|
|
3
|
+
Production-grade, modular MongoDB, Express, and TypeScript backend scaffolder.
|
|
4
|
+
|
|
5
|
+
`create-oikko-mongo` is a command-line scaffolding tool designed to bootstrap scalable, enterprise-ready REST APIs. It eliminates repetitive backend setup by providing an organized modular architecture, robust authentication strategies, role-based access control, caching layers, and external service integrations out of the box.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Table of Contents
|
|
10
|
+
|
|
11
|
+
- [Overview](#overview)
|
|
12
|
+
- [Quick Start](#quick-start)
|
|
13
|
+
- [CLI Setup Modes](#cli-setup-modes)
|
|
14
|
+
- [Architecture & Directory Structure](#architecture--directory-structure)
|
|
15
|
+
- [Core Capabilities](#core-capabilities)
|
|
16
|
+
- [Authentication & Authorization](#authentication--authorization)
|
|
17
|
+
- [Dynamic Role-Based Access Control](#dynamic-role-based-access-control)
|
|
18
|
+
- [Validation & Error Handling](#validation--error-handling)
|
|
19
|
+
- [Redis Caching & Token Management](#redis-caching--token-management)
|
|
20
|
+
- [Notification & Storage Integrations](#notification--storage-integrations)
|
|
21
|
+
- [Environment Variables](#environment-variables)
|
|
22
|
+
- [Default API Endpoints](#default-api-endpoints)
|
|
23
|
+
- [Scripts & Development](#scripts--development)
|
|
24
|
+
- [Publishing & Distribution](#publishing--distribution)
|
|
25
|
+
- [License](#license)
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Overview
|
|
30
|
+
|
|
31
|
+
Starting a production backend from scratch often requires dozens of boilerplate steps: setting up TypeScript configurations, path aliases, JWT access and refresh token rotations, OAuth providers, input validation layers, and global error pipelines.
|
|
32
|
+
|
|
33
|
+
`create-oikko-mongo` provides:
|
|
34
|
+
|
|
35
|
+
- A completely offline-capable npm package without third-party repository dependencies.
|
|
36
|
+
- Strict TypeScript configuration with zero type leaks.
|
|
37
|
+
- Dynamic code generation (custom roles, environments, and cryptographically secure secrets).
|
|
38
|
+
- Option to automatically resolve and install the latest versions of all dependencies.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Quick Start
|
|
43
|
+
|
|
44
|
+
Initialize a new backend service using your preferred package manager:
|
|
45
|
+
|
|
46
|
+
### Using npm
|
|
47
|
+
```bash
|
|
48
|
+
npm create oikko-mongo@latest my-backend-api
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Using npx
|
|
52
|
+
```bash
|
|
53
|
+
npx create-oikko-mongo@latest my-backend-api
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Using pnpm
|
|
57
|
+
```bash
|
|
58
|
+
pnpm create oikko-mongo my-backend-api
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Using yarn
|
|
62
|
+
```bash
|
|
63
|
+
yarn create oikko-mongo my-backend-api
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Using bun
|
|
67
|
+
```bash
|
|
68
|
+
bun create oikko-mongo my-backend-api
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## CLI Setup Modes
|
|
74
|
+
|
|
75
|
+
When executing the scaffolder, you are prompted to select between two initialization modes:
|
|
76
|
+
|
|
77
|
+
### 1. Default Setup (Recommended)
|
|
78
|
+
Designed for rapid development. Immediately provisions a fully functional API with:
|
|
79
|
+
- Server Port: `5000`
|
|
80
|
+
- MongoDB URI: `mongodb://localhost:27017/<project-name>`
|
|
81
|
+
- Standard Roles: `USER`, `ADMIN`, `SUPER_ADMIN`
|
|
82
|
+
- Cryptographically secure 64-character random secrets for `JWT_ACCESS_SECRET`, `JWT_REFRESH_SECRET`, and session keys.
|
|
83
|
+
|
|
84
|
+
### 2. Custom Setup (Interactive)
|
|
85
|
+
Allows comprehensive customization during initialization:
|
|
86
|
+
- **Project Port**: Custom port definition.
|
|
87
|
+
- **Database Connection**: Custom MongoDB local or cloud URI.
|
|
88
|
+
- **Custom User Roles**: Comma-separated roles (e.g. `user, seller, manager, admin`). The CLI dynamically generates the TypeScript `Role` enum and adjusts validation schemas accordingly.
|
|
89
|
+
- **Package Manager Selection**: Choose between `npm`, `pnpm`, `yarn`, or `bun`.
|
|
90
|
+
- **Dependency Versioning**: Option to install tested stable versions or automatically upgrade all packages to their `latest` npm releases.
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Architecture & Directory Structure
|
|
95
|
+
|
|
96
|
+
The generated codebase follows a strict modular structure. Each feature domain contains its own controllers, services, interfaces, models, routes, and validation schemas:
|
|
97
|
+
|
|
98
|
+
```text
|
|
99
|
+
my-backend-api/
|
|
100
|
+
├── src/
|
|
101
|
+
│ ├── app/
|
|
102
|
+
│ │ ├── config/ # Centralized environment, passport, and redis configuration
|
|
103
|
+
│ │ │ ├── db.ts
|
|
104
|
+
│ │ │ ├── env.ts # Type-safe environment validation
|
|
105
|
+
│ │ │ ├── passport.ts # Passport Google & Local strategies
|
|
106
|
+
│ │ │ └── redis.config.ts # Redis connection and lifecycle management
|
|
107
|
+
│ │ ├── errorHelpers/ # Custom AppError class
|
|
108
|
+
│ │ ├── helpers/ # Error parsers (Zod, Mongoose duplicate key, cast errors)
|
|
109
|
+
│ │ ├── interfaces/ # Global TypeScript declaration merging
|
|
110
|
+
│ │ │ └── index.d.ts
|
|
111
|
+
│ │ ├── middlewares/ # Middleware pipeline
|
|
112
|
+
│ │ │ ├── checkAuth.ts # JWT verification & RBAC guard
|
|
113
|
+
│ │ │ ├── globalErrorHandler.ts # Centralized HTTP error handler
|
|
114
|
+
│ │ │ ├── notFound.ts # 404 handler
|
|
115
|
+
│ │ │ ├── requestLogger.ts # HTTP request logger
|
|
116
|
+
│ │ │ └── validateRequest.ts # Zod schema validator
|
|
117
|
+
│ │ ├── modules/ # Business logic modules
|
|
118
|
+
│ │ │ ├── auth/ # Authentication, token exchange, password reset
|
|
119
|
+
│ │ │ ├── otp/ # One-time password generation & verification
|
|
120
|
+
│ │ │ └── user/ # User CRUD and profile operations
|
|
121
|
+
│ │ ├── routes/ # Central application router
|
|
122
|
+
│ │ │ └── index.ts
|
|
123
|
+
│ │ └── utils/ # Helper utilities
|
|
124
|
+
│ │ ├── catchAsync.ts # Async wrapper for Express handlers
|
|
125
|
+
│ │ ├── logger.ts # Winston logger
|
|
126
|
+
│ │ ├── sendEmail.ts # Nodemailer / Resend transport
|
|
127
|
+
│ │ ├── sendResponse.ts # Standardized JSON response envelope
|
|
128
|
+
│ │ ├── userTokens.ts # Token issue and verification utilities
|
|
129
|
+
│ │ └── templates/ # EJS email notification templates
|
|
130
|
+
│ ├── app.ts # Express application setup
|
|
131
|
+
│ └── server.ts # HTTP server bootstrap and database listeners
|
|
132
|
+
├── .env # Local environment configuration
|
|
133
|
+
├── .env.example # Template environment variables
|
|
134
|
+
├── .gitignore
|
|
135
|
+
├── package.json
|
|
136
|
+
└── tsconfig.json
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## Core Capabilities
|
|
142
|
+
|
|
143
|
+
### Authentication & Authorization
|
|
144
|
+
The template implements a dual-layer authentication system:
|
|
145
|
+
- **JWT Authentication**: Short-lived access tokens and long-lived refresh tokens stored securely in `httpOnly`, `secure`, and `sameSite` cookies, as well as bearer header authorization.
|
|
146
|
+
- **Passport.js Integration**: Pre-configured with `LocalStrategy` (email/password with bcrypt hashing) and `GoogleStrategy` (OAuth 2.0 profile exchange).
|
|
147
|
+
- **Password Reset & Recovery**: Time-limited signed tokens and OTP-based verification workflows.
|
|
148
|
+
|
|
149
|
+
### Dynamic Role-Based Access Control
|
|
150
|
+
Role-based authorization is enforced at the route level via the `checkAuth` middleware:
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import { checkAuth } from "../../middlewares/checkAuth";
|
|
154
|
+
import { Role } from "./user.interface";
|
|
155
|
+
|
|
156
|
+
router.get("/admin-dashboard", checkAuth(Role.ADMIN, Role.SUPER_ADMIN), AdminController.getData);
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
When custom roles are configured during CLI generation, the `Role` enum in `src/app/modules/user/user.interface.ts` is dynamically populated.
|
|
160
|
+
|
|
161
|
+
### Validation & Error Handling
|
|
162
|
+
- **Request Validation**: Powered by Zod schemas validating `body`, `query`, and `params` through a unified middleware.
|
|
163
|
+
- **Standardized Response Envelope**: All API responses conform to a strict schema:
|
|
164
|
+
```json
|
|
165
|
+
{
|
|
166
|
+
"success": true,
|
|
167
|
+
"statusCode": 200,
|
|
168
|
+
"message": "Operation successful",
|
|
169
|
+
"data": {}
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
- **Error Pipeline**: Translates Zod errors, Mongoose validation errors, Mongo duplicate key errors (code 11000), and custom `AppError` exceptions into consistent, client-friendly error structures with actionable error source paths.
|
|
173
|
+
|
|
174
|
+
### Redis Caching & Token Management
|
|
175
|
+
Pre-configured Redis client supports:
|
|
176
|
+
- Fast retrieval for high-traffic read operations.
|
|
177
|
+
- Temporary token blacklisting on logout.
|
|
178
|
+
- In-memory rate limiting and OTP expiration storage.
|
|
179
|
+
|
|
180
|
+
### Notification & Storage Integrations
|
|
181
|
+
- **Email Transports**: Nodemailer with SMTP alongside Resend API support, paired with responsive EJS HTML templates for account verification and password resets.
|
|
182
|
+
- **Object Storage**: Pre-configured wrappers for AWS S3, Cloudflare R2, and Cloudinary.
|
|
183
|
+
- **Payment Processing**: SSLCommerz gateway integration covering payment initiation, IPN validation, success, and cancel callbacks.
|
|
184
|
+
- **Alerts**: Optional Telegram bot notifications for system error logging.
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
## Environment Variables
|
|
189
|
+
|
|
190
|
+
The project includes a `.env` configuration file automatically provisioned by the CLI:
|
|
191
|
+
|
|
192
|
+
| Variable | Description | Default / Example |
|
|
193
|
+
| :--- | :--- | :--- |
|
|
194
|
+
| `PORT` | HTTP server port | `5000` |
|
|
195
|
+
| `NODE_ENV` | Application environment (`development` / `production`) | `development` |
|
|
196
|
+
| `DB_URL` | MongoDB connection string | `mongodb://localhost:27017/<project>` |
|
|
197
|
+
| `JWT_ACCESS_SECRET` | Secret key for access token signing | *Auto-generated 64-character hex* |
|
|
198
|
+
| `JWT_ACCESS_EXPIRES` | Access token lifespan | `1d` |
|
|
199
|
+
| `JWT_REFRESH_SECRET` | Secret key for refresh token signing | *Auto-generated 64-character hex* |
|
|
200
|
+
| `JWT_REFRESH_EXPIRES` | Refresh token lifespan | `30d` |
|
|
201
|
+
| `BCRYPT_SALT_ROUND` | Salt rounds for password hashing | `10` |
|
|
202
|
+
| `SUPER_ADMIN_EMAIL` | Initial super admin email | `superadmin@example.com` |
|
|
203
|
+
| `SUPER_ADMIN_PASSWORD` | Initial super admin password | `SuperAdmin@123456` |
|
|
204
|
+
| `GOOGLE_CLIENT_ID` | Google OAuth Client ID | Optional |
|
|
205
|
+
| `GOOGLE_CLIENT_SECRET` | Google OAuth Client Secret | Optional |
|
|
206
|
+
| `GOOGLE_CALLBACK_URL` | Google OAuth redirect URL | `http://localhost:5000/api/v1/auth/google/callback` |
|
|
207
|
+
| `FRONTEND_URL` | Client application origin for CORS | `http://localhost:3000` |
|
|
208
|
+
| `REDIS_HOST` | Redis server host | `localhost` |
|
|
209
|
+
| `REDIS_PORT` | Redis server port | `6379` |
|
|
210
|
+
| `SMTP_HOST` | SMTP server host | `smtp.gmail.com` |
|
|
211
|
+
| `SMTP_PORT` | SMTP port | `465` |
|
|
212
|
+
| `SMTP_USER` | SMTP username | Optional |
|
|
213
|
+
| `SMTP_PASS` | SMTP application password | Optional |
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## Default API Endpoints
|
|
218
|
+
|
|
219
|
+
### Authentication (`/api/v1/auth`)
|
|
220
|
+
- `POST /login` - Authenticate via credentials and receive token cookies.
|
|
221
|
+
- `POST /refresh-token` - Issue a new access token using a refresh token.
|
|
222
|
+
- `POST /logout` - Clear authentication cookies.
|
|
223
|
+
- `POST /forgot-password` - Request a password reset link or token.
|
|
224
|
+
- `POST /reset-password` - Reset account password with token.
|
|
225
|
+
- `POST /change-password` - Update password for authenticated user.
|
|
226
|
+
- `GET /google` - Initiate Google OAuth handshake.
|
|
227
|
+
- `GET /google/callback` - OAuth redirect handler.
|
|
228
|
+
|
|
229
|
+
### Users (`/api/v1/user`)
|
|
230
|
+
- `POST /register` - Register a new user account.
|
|
231
|
+
- `GET /me` - Retrieve current authenticated user profile.
|
|
232
|
+
- `GET /all-users` - Administrator listing of registered accounts.
|
|
233
|
+
|
|
234
|
+
### OTP (`/api/v1/otp`)
|
|
235
|
+
- `POST /send-otp` - Dispatch one-time password to email.
|
|
236
|
+
- `POST /verify-otp` - Verify submitted OTP code.
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## Scripts & Development
|
|
241
|
+
|
|
242
|
+
Navigate to the project root and use standard npm scripts:
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
# Start development server with file watching via tsx
|
|
246
|
+
npm run dev
|
|
247
|
+
|
|
248
|
+
# Run TypeScript compilation
|
|
249
|
+
npm run build
|
|
250
|
+
|
|
251
|
+
# Start production server
|
|
252
|
+
npm start
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## Publishing & Distribution
|
|
258
|
+
|
|
259
|
+
To publish your own version of this scaffolder to the npm registry:
|
|
260
|
+
|
|
261
|
+
1. Update the `name` and `version` fields in `package.json` if required.
|
|
262
|
+
2. Log in to your npm account:
|
|
263
|
+
```bash
|
|
264
|
+
npm login
|
|
265
|
+
```
|
|
266
|
+
3. Publish to the public registry:
|
|
267
|
+
```bash
|
|
268
|
+
npm publish --access public
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
## License
|
|
274
|
+
|
|
275
|
+
MIT License. Free for open-source and commercial use.
|
package/bin/index.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { intro, outro, text, select, confirm, isCancel, cancel, spinner } from "@clack/prompts";
|
|
4
|
+
import color from "picocolors";
|
|
5
|
+
import fs from "fs-extra";
|
|
6
|
+
import path from "path";
|
|
7
|
+
import crypto from "crypto";
|
|
8
|
+
import { execSync } from "child_process";
|
|
9
|
+
import { fileURLToPath } from "url";
|
|
10
|
+
|
|
11
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
12
|
+
const __dirname = path.dirname(__filename);
|
|
13
|
+
const templateDir = path.resolve(__dirname, "../template");
|
|
14
|
+
|
|
15
|
+
function generateSecureSecret(bytes = 32) {
|
|
16
|
+
return crypto.randomBytes(bytes).toString("hex");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function parseRoles(input) {
|
|
20
|
+
return input
|
|
21
|
+
.split(",")
|
|
22
|
+
.map((r) => r.trim())
|
|
23
|
+
.filter(Boolean)
|
|
24
|
+
.map((r) => {
|
|
25
|
+
const key = r.toUpperCase().replace(/[\s-]+/g, "_");
|
|
26
|
+
const val = r.toLowerCase().replace(/\s+/g, "_");
|
|
27
|
+
return { key, val };
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function main() {
|
|
32
|
+
console.log();
|
|
33
|
+
intro(color.bold(color.bgCyan(color.black(" 🚀 OIKKO • MERN STARTER (MongoDB + Express + TS) "))));
|
|
34
|
+
|
|
35
|
+
// 1. Project Name
|
|
36
|
+
let projectName = process.argv[2];
|
|
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
|
+
});
|
|
49
|
+
|
|
50
|
+
if (isCancel(projectName)) {
|
|
51
|
+
cancel("Operation cancelled.");
|
|
52
|
+
process.exit(0);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const targetDir = path.resolve(process.cwd(), projectName);
|
|
57
|
+
|
|
58
|
+
if (fs.existsSync(targetDir)) {
|
|
59
|
+
const overwrite = await confirm({
|
|
60
|
+
message: `Directory "${projectName}" already exists. Do you want to overwrite it?`,
|
|
61
|
+
initialValue: false,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
if (isCancel(overwrite) || !overwrite) {
|
|
65
|
+
cancel("Operation cancelled.");
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
await fs.emptyDir(targetDir);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 2. Setup Mode Selection
|
|
73
|
+
const setupMode = await select({
|
|
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
|
+
});
|
|
88
|
+
|
|
89
|
+
if (isCancel(setupMode)) {
|
|
90
|
+
cancel("Operation cancelled.");
|
|
91
|
+
process.exit(0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Configuration object
|
|
95
|
+
let port = "5000";
|
|
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";
|
|
118
|
+
|
|
119
|
+
// Custom DB URL
|
|
120
|
+
const dbAnswer = await text({
|
|
121
|
+
message: "MongoDB connection URI:",
|
|
122
|
+
placeholder: `mongodb://localhost:27017/${projectName}`,
|
|
123
|
+
defaultValue: `mongodb://localhost:27017/${projectName}`,
|
|
124
|
+
});
|
|
125
|
+
if (isCancel(dbAnswer)) {
|
|
126
|
+
cancel("Operation cancelled.");
|
|
127
|
+
process.exit(0);
|
|
128
|
+
}
|
|
129
|
+
dbUrl = dbAnswer.trim() || `mongodb://localhost:27017/${projectName}`;
|
|
130
|
+
|
|
131
|
+
// Custom Roles
|
|
132
|
+
const rolesAnswer = await text({
|
|
133
|
+
message: "Define User Roles (comma-separated):",
|
|
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);
|
|
141
|
+
}
|
|
142
|
+
roles = parseRoles(rolesAnswer);
|
|
143
|
+
|
|
144
|
+
// Package Manager
|
|
145
|
+
const pmAnswer = await select({
|
|
146
|
+
message: "Select package manager:",
|
|
147
|
+
options: [
|
|
148
|
+
{ value: "npm", label: "npm" },
|
|
149
|
+
{ value: "pnpm", label: "pnpm" },
|
|
150
|
+
{ value: "yarn", label: "yarn" },
|
|
151
|
+
{ value: "bun", label: "bun" },
|
|
152
|
+
],
|
|
153
|
+
});
|
|
154
|
+
if (isCancel(pmAnswer)) {
|
|
155
|
+
cancel("Operation cancelled.");
|
|
156
|
+
process.exit(0);
|
|
157
|
+
}
|
|
158
|
+
packageManager = pmAnswer;
|
|
159
|
+
|
|
160
|
+
// Dependency Version Strategy
|
|
161
|
+
const versionStrategy = await select({
|
|
162
|
+
message: "Dependency version strategy:",
|
|
163
|
+
options: [
|
|
164
|
+
{
|
|
165
|
+
value: "stable",
|
|
166
|
+
label: "🛡️ Tested & Stable (Recommended)",
|
|
167
|
+
hint: "Uses tested SemVer ranges with caret (^). Prevents breaking changes.",
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
value: "latest",
|
|
171
|
+
label: "⚡ Bleeding Edge (latest)",
|
|
172
|
+
hint: "Forces latest releases from npm registry. May introduce breaking changes.",
|
|
173
|
+
},
|
|
174
|
+
],
|
|
175
|
+
});
|
|
176
|
+
if (isCancel(versionStrategy)) {
|
|
177
|
+
cancel("Operation cancelled.");
|
|
178
|
+
process.exit(0);
|
|
179
|
+
}
|
|
180
|
+
installLatest = versionStrategy === "latest";
|
|
181
|
+
|
|
182
|
+
// Install dependencies now
|
|
183
|
+
const installAnswer = await confirm({
|
|
184
|
+
message: "Run package installation now?",
|
|
185
|
+
initialValue: true,
|
|
186
|
+
});
|
|
187
|
+
if (isCancel(installAnswer)) {
|
|
188
|
+
cancel("Operation cancelled.");
|
|
189
|
+
process.exit(0);
|
|
190
|
+
}
|
|
191
|
+
runInstall = installAnswer;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const s = spinner();
|
|
195
|
+
s.start(`Scaffolding project in ${color.cyan(projectName)}...`);
|
|
196
|
+
|
|
197
|
+
// 1. Copy template files
|
|
198
|
+
await fs.copy(templateDir, targetDir);
|
|
199
|
+
|
|
200
|
+
// 2. Handle gitignore
|
|
201
|
+
const gitignorePath = path.join(targetDir, "_gitignore");
|
|
202
|
+
if (await fs.pathExists(gitignorePath)) {
|
|
203
|
+
await fs.rename(gitignorePath, path.join(targetDir, ".gitignore"));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 3. Update package.json
|
|
207
|
+
const pkgPath = path.join(targetDir, "package.json");
|
|
208
|
+
if (await fs.pathExists(pkgPath)) {
|
|
209
|
+
const pkg = await fs.readJson(pkgPath);
|
|
210
|
+
pkg.name = projectName;
|
|
211
|
+
|
|
212
|
+
if (installLatest) {
|
|
213
|
+
// Update all to "latest"
|
|
214
|
+
for (const dep of Object.keys(pkg.dependencies || {})) {
|
|
215
|
+
pkg.dependencies[dep] = "latest";
|
|
216
|
+
}
|
|
217
|
+
for (const devDep of Object.keys(pkg.devDependencies || {})) {
|
|
218
|
+
pkg.devDependencies[devDep] = "latest";
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
await fs.writeJson(pkgPath, pkg, { spaces: 2 });
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// 4. Dynamically Inject Roles into user.interface.ts
|
|
226
|
+
const userInterfacePath = path.join(targetDir, "src/app/modules/user/user.interface.ts");
|
|
227
|
+
if (await fs.pathExists(userInterfacePath)) {
|
|
228
|
+
let content = await fs.readFile(userInterfacePath, "utf-8");
|
|
229
|
+
|
|
230
|
+
const enumCode = `export enum Role {\n${roles
|
|
231
|
+
.map((r) => ` ${r.key} = "${r.val}"`)
|
|
232
|
+
.join(",\n")}\n}`;
|
|
233
|
+
|
|
234
|
+
content = content.replace(/export enum Role\s*\{[\s\S]*?\}/, enumCode);
|
|
235
|
+
await fs.writeFile(userInterfacePath, content, "utf-8");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// 5. Generate secure secrets and dynamic .env
|
|
239
|
+
const envExamplePath = path.join(targetDir, ".env.example");
|
|
240
|
+
const envDestPath = path.join(targetDir, ".env");
|
|
241
|
+
|
|
242
|
+
if (await fs.pathExists(envExamplePath)) {
|
|
243
|
+
let envContent = await fs.readFile(envExamplePath, "utf-8");
|
|
244
|
+
|
|
245
|
+
const jwtAccessSecret = generateSecureSecret(48);
|
|
246
|
+
const jwtRefreshSecret = generateSecureSecret(48);
|
|
247
|
+
const sessionSecret = generateSecureSecret(24);
|
|
248
|
+
|
|
249
|
+
envContent = envContent
|
|
250
|
+
.replace(/\{\{PORT\}\}/g, port)
|
|
251
|
+
.replace(/\{\{DB_URL\}\}/g, dbUrl)
|
|
252
|
+
.replace(/\{\{JWT_ACCESS_SECRET\}\}/g, jwtAccessSecret)
|
|
253
|
+
.replace(/\{\{JWT_REFRESH_SECRET\}\}/g, jwtRefreshSecret)
|
|
254
|
+
.replace(/\{\{SESSION_SECRET\}\}/g, sessionSecret);
|
|
255
|
+
|
|
256
|
+
await fs.writeFile(envDestPath, envContent, "utf-8");
|
|
257
|
+
await fs.writeFile(envExamplePath, envContent, "utf-8");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
s.stop(color.green(`✓ Scaffolding complete!`));
|
|
261
|
+
|
|
262
|
+
// 6. Install dependencies if requested
|
|
263
|
+
if (runInstall) {
|
|
264
|
+
s.start(
|
|
265
|
+
installLatest
|
|
266
|
+
? `Installing latest packages with ${packageManager} (this may take a moment)...`
|
|
267
|
+
: `Installing dependencies with ${packageManager}...`
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
try {
|
|
271
|
+
const installCmd =
|
|
272
|
+
packageManager === "yarn"
|
|
273
|
+
? "yarn install"
|
|
274
|
+
: packageManager === "pnpm"
|
|
275
|
+
? "pnpm install"
|
|
276
|
+
: packageManager === "bun"
|
|
277
|
+
? "bun install"
|
|
278
|
+
: "npm install";
|
|
279
|
+
|
|
280
|
+
execSync(installCmd, { cwd: targetDir, stdio: "ignore" });
|
|
281
|
+
s.stop(color.green(`✓ Dependencies installed successfully!`));
|
|
282
|
+
} catch (err) {
|
|
283
|
+
s.stop(color.yellow(`⚠ Dependency installation failed. You can install manually.`));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
console.log();
|
|
288
|
+
outro(color.bold(color.green(`🎉 Success! Your Oikko MongoDB project is ready at ./${projectName}`)));
|
|
289
|
+
|
|
290
|
+
console.log(color.cyan("\nNext steps:"));
|
|
291
|
+
console.log(` ${color.white(`cd ${projectName}`)}`);
|
|
292
|
+
if (!runInstall) {
|
|
293
|
+
console.log(` ${color.white(`${packageManager} install`)}`);
|
|
294
|
+
}
|
|
295
|
+
console.log(` ${color.white(`${packageManager} run dev`)}\n`);
|
|
296
|
+
console.log(color.gray("Documentation & Updates: https://github.com/hassan-nahid/oikko-backend-mongo\n"));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
main().catch((err) => {
|
|
300
|
+
console.error(err);
|
|
301
|
+
process.exit(1);
|
|
302
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "create-oikko-mongo",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Production-ready MERN (MongoDB + Express + TypeScript) enterprise backend scaffolder by Oikko",
|
|
5
|
+
"main": "./bin/index.js",
|
|
6
|
+
"bin": {
|
|
7
|
+
"create-oikko-mongo": "./bin/index.js"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"keywords": [
|
|
11
|
+
"oikko",
|
|
12
|
+
"mern",
|
|
13
|
+
"mongodb",
|
|
14
|
+
"express",
|
|
15
|
+
"typescript",
|
|
16
|
+
"boilerplate",
|
|
17
|
+
"starter",
|
|
18
|
+
"scaffolder",
|
|
19
|
+
"cli"
|
|
20
|
+
],
|
|
21
|
+
"author": "Hassan Nahid",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18.0.0"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@clack/prompts": "^0.8.2",
|
|
28
|
+
"fs-extra": "^11.3.0",
|
|
29
|
+
"picocolors": "^1.1.1"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"bin",
|
|
33
|
+
"template",
|
|
34
|
+
"README.md"
|
|
35
|
+
]
|
|
36
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
PORT={{PORT}}
|
|
2
|
+
NODE_ENV=development
|
|
3
|
+
|
|
4
|
+
# Database
|
|
5
|
+
DB_URL={{DB_URL}}
|
|
6
|
+
|
|
7
|
+
# JWT Secrets (Auto-generated by Oikko CLI)
|
|
8
|
+
JWT_ACCESS_SECRET={{JWT_ACCESS_SECRET}}
|
|
9
|
+
JWT_ACCESS_EXPIRES=1d
|
|
10
|
+
JWT_REFRESH_SECRET={{JWT_REFRESH_SECRET}}
|
|
11
|
+
JWT_REFRESH_EXPIRES=30d
|
|
12
|
+
|
|
13
|
+
# Bcrypt
|
|
14
|
+
BCRYPT_SALT_ROUND=10
|
|
15
|
+
|
|
16
|
+
# Super Admin Initial Credentials
|
|
17
|
+
SUPER_ADMIN_EMAIL=superadmin@example.com
|
|
18
|
+
SUPER_ADMIN_PASSWORD=SuperAdmin@123456
|
|
19
|
+
|
|
20
|
+
# Google OAuth
|
|
21
|
+
GOOGLE_CLIENT_ID=your-google-client-id
|
|
22
|
+
GOOGLE_CLIENT_SECRET=your-google-client-secret
|
|
23
|
+
GOOGLE_CALLBACK_URL=http://localhost:{{PORT}}/api/v1/auth/google/callback
|
|
24
|
+
|
|
25
|
+
# Express Session
|
|
26
|
+
EXPRESS_SESSION_SECRET={{SESSION_SECRET}}
|
|
27
|
+
|
|
28
|
+
# Frontend URLs
|
|
29
|
+
FRONTEND_URL=http://localhost:3000
|
|
30
|
+
APP_DASHBOARD_URL=http://localhost:5173
|
|
31
|
+
STUDENT_PORTAL_URL=http://localhost:5174
|
|
32
|
+
|
|
33
|
+
# SSLCommerz Payment Gateway
|
|
34
|
+
SSL_STORE_ID=your_store_id
|
|
35
|
+
SSL_STORE_PASS=your_store_password
|
|
36
|
+
SSL_PAYMENT_API=https://sandbox.sslcommerz.com/gwprocess/v4/api.php
|
|
37
|
+
SSL_VALIDATION_API=https://sandbox.sslcommerz.com/validator/api/validationserverAPI.php
|
|
38
|
+
SSL_SUCCESS_BACKEND_URL=http://localhost:{{PORT}}/api/v1/payment/success
|
|
39
|
+
SSL_FAIL_BACKEND_URL=http://localhost:{{PORT}}/api/v1/payment/fail
|
|
40
|
+
SSL_CANCEL_BACKEND_URL=http://localhost:{{PORT}}/api/v1/payment/cancel
|
|
41
|
+
SSL_IPN_URL=http://localhost:{{PORT}}/api/v1/payment/validate-payment
|
|
42
|
+
SSL_SUCCESS_FRONTEND_URL=http://localhost:3000/payment/success
|
|
43
|
+
SSL_FAIL_FRONTEND_URL=http://localhost:3000/payment/fail
|
|
44
|
+
SSL_CANCEL_FRONTEND_URL=http://localhost:3000/payment/cancel
|
|
45
|
+
|
|
46
|
+
# Cloudinary
|
|
47
|
+
CLOUDINARY_CLOUD_NAME=your_cloudinary_name
|
|
48
|
+
CLOUDINARY_API_KEY=your_cloudinary_api_key
|
|
49
|
+
CLOUDINARY_API_SECRET=your_cloudinary_api_secret
|
|
50
|
+
|
|
51
|
+
# SMTP Email
|
|
52
|
+
SMTP_HOST=smtp.gmail.com
|
|
53
|
+
SMTP_PORT=465
|
|
54
|
+
SMTP_USER=your_email@gmail.com
|
|
55
|
+
SMTP_PASS=your_app_password
|
|
56
|
+
SMTP_FROM=your_email@gmail.com
|
|
57
|
+
|
|
58
|
+
# Resend Email
|
|
59
|
+
RESEND_API_KEY=re_your_resend_api_key
|
|
60
|
+
RESEND_FROM=noreply@example.com
|
|
61
|
+
|
|
62
|
+
# Redis
|
|
63
|
+
REDIS_HOST=localhost
|
|
64
|
+
REDIS_PORT=6379
|
|
65
|
+
REDIS_USERNAME=default
|
|
66
|
+
REDIS_PASSWORD=
|
|
67
|
+
|
|
68
|
+
# Cloudflare R2
|
|
69
|
+
R2_ACCOUNT_ID=your_r2_account_id
|
|
70
|
+
R2_ACCESS_KEY_ID=your_r2_access_key
|
|
71
|
+
R2_SECRET_ACCESS_KEY=your_r2_secret_key
|
|
72
|
+
R2_BUCKET_NAME=your_bucket_name
|
|
73
|
+
R2_PUBLIC_URL=https://pub-your_bucket.r2.dev
|
|
74
|
+
|
|
75
|
+
# MIM SMS
|
|
76
|
+
MIMSMS_USERNAME=your_username
|
|
77
|
+
MIMSMS_APIKEY=your_api_key
|
|
78
|
+
MIMSMS_SENDER=your_sender_id
|
|
79
|
+
|
|
80
|
+
# Telegram (Optional)
|
|
81
|
+
TELEGRAM_BOT_TOKEN=
|
|
82
|
+
TELEGRAM_CHAT_ID=
|