create-theta-code 1.0.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.
Files changed (68) hide show
  1. package/bin/create.js +9 -0
  2. package/package.json +34 -0
  3. package/src/cli.js +21 -0
  4. package/src/generators/scaffoldProject.js +46 -0
  5. package/src/prompts/getProjectName.js +30 -0
  6. package/src/prompts/getTemplateChoice.js +39 -0
  7. package/src/utils/logger.js +29 -0
  8. package/templates/mongo-js/.env +12 -0
  9. package/templates/mongo-js/.env.example +13 -0
  10. package/templates/mongo-js/.eslintrc.json +24 -0
  11. package/templates/mongo-js/.prettierrc +9 -0
  12. package/templates/mongo-js/README.md +429 -0
  13. package/templates/mongo-js/_env.example +13 -0
  14. package/templates/mongo-js/_gitignore +22 -0
  15. package/templates/mongo-js/package-lock.json +4671 -0
  16. package/templates/mongo-js/package.json +48 -0
  17. package/templates/mongo-js/server.js +67 -0
  18. package/templates/mongo-js/src/config/app.config.js +72 -0
  19. package/templates/mongo-js/src/config/db.config.js +32 -0
  20. package/templates/mongo-js/src/config/env.config.js +49 -0
  21. package/templates/mongo-js/src/config/rateLimiter.config.js +32 -0
  22. package/templates/mongo-js/src/middlewares/auth.middleware.js +20 -0
  23. package/templates/mongo-js/src/middlewares/error.middleware.js +61 -0
  24. package/templates/mongo-js/src/middlewares/notFound.middleware.js +11 -0
  25. package/templates/mongo-js/src/middlewares/requestId.middleware.js +10 -0
  26. package/templates/mongo-js/src/middlewares/requireRole.middleware.js +13 -0
  27. package/templates/mongo-js/src/middlewares/validate.middleware.js +21 -0
  28. package/templates/mongo-js/src/modules/user/user.controller.js +88 -0
  29. package/templates/mongo-js/src/modules/user/user.model.js +45 -0
  30. package/templates/mongo-js/src/modules/user/user.repository.js +47 -0
  31. package/templates/mongo-js/src/modules/user/user.routes.js +32 -0
  32. package/templates/mongo-js/src/modules/user/user.service.js +87 -0
  33. package/templates/mongo-js/src/modules/user/user.validator.js +28 -0
  34. package/templates/mongo-js/src/utils/AppError.js +15 -0
  35. package/templates/mongo-js/src/utils/apiResponse.js +23 -0
  36. package/templates/mongo-js/src/utils/asyncHandler.js +7 -0
  37. package/templates/mongo-js/src/utils/constants.js +16 -0
  38. package/templates/mongo-js/src/utils/jwt.utils.js +40 -0
  39. package/templates/mongo-js/tests/integration/user.routes.test.js +111 -0
  40. package/templates/mongo-js/tests/unit/user.service.test.js +96 -0
  41. package/templates/pg-js/.eslintrc.json +24 -0
  42. package/templates/pg-js/.prettierrc +9 -0
  43. package/templates/pg-js/_env.example +7 -0
  44. package/templates/pg-js/_gitignore +20 -0
  45. package/templates/pg-js/package.json +50 -0
  46. package/templates/pg-js/prisma/schema.prisma +23 -0
  47. package/templates/pg-js/server.js +63 -0
  48. package/templates/pg-js/src/config/app.config.js +48 -0
  49. package/templates/pg-js/src/config/db.config.js +30 -0
  50. package/templates/pg-js/src/config/env.config.js +36 -0
  51. package/templates/pg-js/src/config/rateLimiter.config.js +22 -0
  52. package/templates/pg-js/src/middlewares/auth.middleware.js +32 -0
  53. package/templates/pg-js/src/middlewares/error.middleware.js +50 -0
  54. package/templates/pg-js/src/middlewares/notFound.middleware.js +11 -0
  55. package/templates/pg-js/src/middlewares/validate.middleware.js +21 -0
  56. package/templates/pg-js/src/modules/user/user.controller.js +57 -0
  57. package/templates/pg-js/src/modules/user/user.model.js +20 -0
  58. package/templates/pg-js/src/modules/user/user.repository.js +105 -0
  59. package/templates/pg-js/src/modules/user/user.routes.js +27 -0
  60. package/templates/pg-js/src/modules/user/user.service.js +81 -0
  61. package/templates/pg-js/src/modules/user/user.validator.js +22 -0
  62. package/templates/pg-js/src/utils/AppError.js +14 -0
  63. package/templates/pg-js/src/utils/apiResponse.js +23 -0
  64. package/templates/pg-js/src/utils/asyncHandler.js +7 -0
  65. package/templates/pg-js/src/utils/constants.js +24 -0
  66. package/templates/pg-js/src/utils/jwt.utils.js +39 -0
  67. package/templates/pg-js/tests/integration/user.routes.test.js +95 -0
  68. package/templates/pg-js/tests/unit/user.service.test.js +96 -0
@@ -0,0 +1,429 @@
1
+ # Production-Grade Node.js API Boilerplate
2
+
3
+ A secure, scalable, and production-ready Node.js API built with Express.js, MongoDB, and modern security practices. This boilerplate provides a solid foundation for building enterprise-grade REST APIs with authentication, authorization, rate limiting, and comprehensive error handling.
4
+
5
+ ## ๐Ÿš€ Features
6
+
7
+ ### Core Architecture
8
+ - **Express.js 4** - Fast, unopinionated web framework
9
+ - **MongoDB + Mongoose** - NoSQL database with ODM
10
+ - **ESM Modules** - Modern JavaScript module system
11
+ - **Zod Validation** - Type-safe input validation
12
+ - **JWT Authentication** - Secure token-based auth with refresh tokens
13
+ - **Role-Based Access Control (RBAC)** - Admin/User permissions
14
+
15
+ ### Security & Hardening
16
+ - **Helmet** - Security headers middleware
17
+ - **CORS** - Configurable cross-origin resource sharing
18
+ - **Rate Limiting** - Global and auth-specific rate limits
19
+ - **bcryptjs** - Secure password hashing
20
+ - **HTTP-Only Cookies** - Secure token storage
21
+ - **Input Validation** - Comprehensive request validation
22
+ - **Error Handling** - Centralized error management
23
+
24
+ ### Developer Experience
25
+ - **ESLint + Prettier** - Code linting and formatting
26
+ - **Vitest** - Fast unit and integration testing
27
+ - **Nodemon** - Development auto-restart
28
+ - **Morgan** - HTTP request logging (dev only)
29
+ - **Request ID Tracing** - Correlation ID for debugging
30
+
31
+ ## ๐Ÿ“‹ Prerequisites
32
+
33
+ - **Node.js** >= 18.0.0
34
+ - **MongoDB** >= 4.0 (local or cloud instance)
35
+ - **npm** or **yarn** package manager
36
+
37
+ ## ๐Ÿ› ๏ธ Installation
38
+
39
+ 1. **Create a new project** using the CLI:
40
+ ```bash
41
+ npx create-theta-code my-api
42
+ cd my-api
43
+ ```
44
+
45
+ 2. **Install dependencies**:
46
+ ```bash
47
+ npm install
48
+ ```
49
+
50
+ 3. **Environment Setup**:
51
+ ```bash
52
+ cp .env.example .env
53
+ ```
54
+
55
+ Edit `.env` with your configuration:
56
+ ```env
57
+ NODE_ENV=development
58
+ PORT=3000
59
+ MONGODB_URI=mongodb://localhost:27017/your-database
60
+ JWT_SECRET=your-super-secure-jwt-secret-min-32-chars
61
+ JWT_REFRESH_SECRET=your-super-secure-refresh-secret-min-32-chars
62
+ JWT_EXPIRES_IN=7d
63
+ JWT_REFRESH_EXPIRES_IN=30d
64
+ BCRYPT_SALT_ROUNDS=12
65
+ RATE_LIMIT_WINDOW_MS=900000
66
+ RATE_LIMIT_MAX=100
67
+ AUTH_RATE_LIMIT_MAX=10
68
+ CORS_ORIGIN=http://localhost:3000
69
+ LOG_LEVEL=info
70
+ ```
71
+
72
+ 4. **Start MongoDB** (if running locally):
73
+ ```bash
74
+ mongod
75
+ ```
76
+
77
+ 5. **Run the application**:
78
+ ```bash
79
+ # Development mode
80
+ npm run dev
81
+
82
+ # Production mode
83
+ npm start
84
+ ```
85
+
86
+ ## ๐Ÿงช Testing
87
+
88
+ ```bash
89
+ # Run all tests
90
+ npm test
91
+
92
+ # Run tests with coverage
93
+ npm run test:coverage
94
+
95
+ # Run tests in watch mode
96
+ npx vitest
97
+ ```
98
+
99
+ ## ๐Ÿ“š API Documentation
100
+
101
+ ### Base URL
102
+ ```
103
+ http://localhost:3000/api/v1
104
+ ```
105
+
106
+ ### Authentication
107
+ All protected endpoints require a JWT token in the `Authorization` header or `accessToken` cookie.
108
+
109
+ ### Endpoints
110
+
111
+ #### Health Check
112
+ ```http
113
+ GET /health
114
+ ```
115
+ Returns server health status (no authentication required).
116
+
117
+ **Response:**
118
+ ```json
119
+ {
120
+ "status": "UP",
121
+ "environment": "development",
122
+ "uptime": 123.456,
123
+ "timestamp": "2024-01-01T00:00:00.000Z",
124
+ "memory": {
125
+ "rss": 12345678,
126
+ "heapTotal": 1234567,
127
+ "heapUsed": 987654,
128
+ "external": 12345
129
+ }
130
+ }
131
+ ```
132
+
133
+ #### User Registration
134
+ ```http
135
+ POST /api/v1/users/register
136
+ ```
137
+
138
+ **Request Body:**
139
+ ```json
140
+ {
141
+ "email": "user@example.com",
142
+ "firstName": "John",
143
+ "lastName": "Doe",
144
+ "password": "SecurePass123!"
145
+ }
146
+ ```
147
+
148
+ **Response:**
149
+ ```json
150
+ {
151
+ "success": true,
152
+ "message": "User registered successfully",
153
+ "data": {
154
+ "user": {
155
+ "_id": "...",
156
+ "email": "user@example.com",
157
+ "firstName": "John",
158
+ "lastName": "Doe",
159
+ "role": "user",
160
+ "isActive": true,
161
+ "createdAt": "2024-01-01T00:00:00.000Z",
162
+ "updatedAt": "2024-01-01T00:00:00.000Z"
163
+ }
164
+ },
165
+ "timestamp": "2024-01-01T00:00:00.000Z"
166
+ }
167
+ ```
168
+
169
+ #### User Login
170
+ ```http
171
+ POST /api/v1/users/login
172
+ ```
173
+
174
+ **Request Body:**
175
+ ```json
176
+ {
177
+ "email": "user@example.com",
178
+ "password": "SecurePass123!"
179
+ }
180
+ ```
181
+
182
+ **Response:**
183
+ ```json
184
+ {
185
+ "success": true,
186
+ "message": "Login successful",
187
+ "data": {
188
+ "user": {
189
+ "_id": "...",
190
+ "email": "user@example.com",
191
+ "firstName": "John",
192
+ "lastName": "Doe",
193
+ "role": "user",
194
+ "isActive": true,
195
+ "createdAt": "2024-01-01T00:00:00.000Z",
196
+ "updatedAt": "2024-01-01T00:00:00.000Z"
197
+ }
198
+ },
199
+ "timestamp": "2024-01-01T00:00:00.000Z"
200
+ }
201
+ ```
202
+
203
+ **Note:** Sets `accessToken` and `refreshToken` HTTP-only cookies.
204
+
205
+ #### Get User Profile
206
+ ```http
207
+ GET /api/v1/users/profile
208
+ ```
209
+ **Auth Required:** Bearer token or cookie
210
+
211
+ #### Update User Profile
212
+ ```http
213
+ PUT /api/v1/users/profile
214
+ ```
215
+ **Auth Required:** Bearer token or cookie
216
+
217
+ **Request Body:**
218
+ ```json
219
+ {
220
+ "firstName": "Jane",
221
+ "lastName": "Smith"
222
+ }
223
+ ```
224
+
225
+ #### Get All Users (Admin Only)
226
+ ```http
227
+ GET /api/v1/users/users?limit=10&skip=0
228
+ ```
229
+ **Auth Required:** Bearer token or cookie + Admin role
230
+
231
+ **Query Parameters:**
232
+ - `limit` (optional): Number of users to return (max 100, default 10)
233
+ - `skip` (optional): Number of users to skip (default 0)
234
+
235
+ #### Logout
236
+ ```http
237
+ POST /api/v1/users/logout
238
+ ```
239
+ **Auth Required:** Bearer token or cookie
240
+
241
+ Clears authentication cookies.
242
+
243
+ #### Delete Account
244
+ ```http
245
+ DELETE /api/v1/users/account
246
+ ```
247
+ **Auth Required:** Bearer token or cookie
248
+
249
+ ## ๐Ÿ—๏ธ Project Structure
250
+
251
+ ```
252
+ โ”œโ”€โ”€ bin/
253
+ โ”‚ โ””โ”€โ”€ create.js # CLI script for project generation
254
+ โ”œโ”€โ”€ src/
255
+ โ”‚ โ”œโ”€โ”€ config/
256
+ โ”‚ โ”‚ โ”œโ”€โ”€ app.config.js # Express app factory & middleware
257
+ โ”‚ โ”‚ โ”œโ”€โ”€ db.config.js # MongoDB connection
258
+ โ”‚ โ”‚ โ”œโ”€โ”€ env.config.js # Environment validation (Zod)
259
+ โ”‚ โ”‚ โ””โ”€โ”€ rateLimiter.config.js # Rate limiting configuration
260
+ โ”‚ โ”œโ”€โ”€ middlewares/
261
+ โ”‚ โ”‚ โ”œโ”€โ”€ auth.middleware.js # JWT authentication
262
+ โ”‚ โ”‚ โ”œโ”€โ”€ error.middleware.js # Global error handling
263
+ โ”‚ โ”‚ โ”œโ”€โ”€ notFound.middleware.js # 404 handler
264
+ โ”‚ โ”‚ โ”œโ”€โ”€ requestId.middleware.js # Request correlation ID
265
+ โ”‚ โ”‚ โ”œโ”€โ”€ requireRole.middleware.js # RBAC guard
266
+ โ”‚ โ”‚ โ””โ”€โ”€ validate.middleware.js # Input validation
267
+ โ”‚ โ”œโ”€โ”€ modules/
268
+ โ”‚ โ”‚ โ””โ”€โ”€ user/
269
+ โ”‚ โ”‚ โ”œโ”€โ”€ user.controller.js # HTTP handlers
270
+ โ”‚ โ”‚ โ”œโ”€โ”€ user.model.js # Mongoose schema
271
+ โ”‚ โ”‚ โ”œโ”€โ”€ user.repository.js # Data access layer
272
+ โ”‚ โ”‚ โ”œโ”€โ”€ user.routes.js # Route definitions
273
+ โ”‚ โ”‚ โ”œโ”€โ”€ user.service.js # Business logic
274
+ โ”‚ โ”‚ โ””โ”€โ”€ user.validator.js # Input validation schemas
275
+ โ”‚ โ””โ”€โ”€ utils/
276
+ โ”‚ โ”œโ”€โ”€ AppError.js # Custom error class
277
+ โ”‚ โ”œโ”€โ”€ apiResponse.js # Response formatting
278
+ โ”‚ โ”œโ”€โ”€ asyncHandler.js # Async error wrapper
279
+ โ”‚ โ”œโ”€โ”€ constants.js # Application constants
280
+ โ”‚ โ””โ”€โ”€ jwt.utils.js # JWT utilities
281
+ โ”œโ”€โ”€ tests/
282
+ โ”‚ โ”œโ”€โ”€ integration/
283
+ โ”‚ โ”‚ โ””โ”€โ”€ user.routes.test.js # API integration tests
284
+ โ”‚ โ””โ”€โ”€ unit/
285
+ โ”‚ โ””โ”€โ”€ user.service.test.js # Unit tests
286
+ โ”œโ”€โ”€ .env.example # Environment template
287
+ โ”œโ”€โ”€ .gitignore # Git ignore rules
288
+ โ”œโ”€โ”€ package.json # Dependencies & scripts
289
+ โ”œโ”€โ”€ README.md # This file
290
+ โ””โ”€โ”€ server.js # Application entry point
291
+ ```
292
+
293
+ ## ๐Ÿ”’ Security Features
294
+
295
+ ### Authentication & Authorization
296
+ - **JWT Tokens**: Access and refresh tokens with configurable expiration
297
+ - **HTTP-Only Cookies**: Secure token storage, XSS protection
298
+ - **Password Hashing**: bcryptjs with configurable salt rounds
299
+ - **Role-Based Access**: Admin/User roles with middleware guards
300
+
301
+ ### Input Validation & Sanitization
302
+ - **Zod Schemas**: Type-safe validation for all inputs
303
+ - **Request Size Limits**: 10KB limit on JSON payloads
304
+ - **SQL Injection Protection**: Parameterized queries via Mongoose
305
+
306
+ ### Rate Limiting
307
+ - **Global Limits**: 100 requests per 15 minutes per IP
308
+ - **Auth Limits**: 10 login attempts per 15 minutes per IP
309
+ - **Custom Messages**: Consistent error response format
310
+
311
+ ### Security Headers
312
+ - **Helmet**: Comprehensive security headers
313
+ - **CORS**: Configurable origin allowlist
314
+ - **HSTS**: HTTP Strict Transport Security (production)
315
+
316
+ ### Error Handling
317
+ - **No Data Leaks**: Sensitive information never exposed
318
+ - **Consistent Format**: All errors follow API response schema
319
+ - **Logging**: Request correlation IDs for debugging
320
+
321
+ ## ๐Ÿงช Testing Strategy
322
+
323
+ ### Unit Tests
324
+ - **Service Layer**: Business logic testing with mocked repositories
325
+ - **Middleware**: Authentication, validation, and error handling
326
+ - **Utilities**: JWT, password hashing, and response formatting
327
+
328
+ ### Integration Tests
329
+ - **API Endpoints**: Full request/response cycle testing
330
+ - **Database Operations**: Real database interactions (test DB)
331
+ - **Middleware Chain**: Authentication, validation, and rate limiting
332
+
333
+ ### Test Coverage
334
+ - **Vitest**: Fast, ESM-compatible test runner
335
+ - **Supertest**: HTTP endpoint testing
336
+ - **Coverage Reports**: Detailed coverage analysis
337
+
338
+ ## ๐Ÿš€ Deployment
339
+
340
+ ### Environment Variables
341
+ Ensure all required environment variables are set in production:
342
+
343
+ ```bash
344
+ NODE_ENV=production
345
+ PORT=3000
346
+ MONGODB_URI=mongodb://username:password@host:port/database
347
+ JWT_SECRET=your-production-jwt-secret
348
+ JWT_REFRESH_SECRET=your-production-refresh-secret
349
+ CORS_ORIGIN=https://yourdomain.com
350
+ ```
351
+
352
+ ### Production Checklist
353
+ - [ ] Set `NODE_ENV=production`
354
+ - [ ] Use strong, unique JWT secrets (min 32 characters)
355
+ - [ ] Configure production MongoDB URI
356
+ - [ ] Set secure CORS origins
357
+ - [ ] Enable HTTPS/SSL
358
+ - [ ] Set up monitoring and logging
359
+ - [ ] Configure rate limits appropriately
360
+ - [ ] Set up database backups
361
+ - [ ] Configure firewall rules
362
+
363
+ ### Docker Support (Optional)
364
+ Add a `Dockerfile` and `docker-compose.yml` for containerized deployment:
365
+
366
+ ```dockerfile
367
+ FROM node:18-alpine
368
+ WORKDIR /app
369
+ COPY package*.json ./
370
+ RUN npm ci --only=production
371
+ COPY . .
372
+ EXPOSE 3000
373
+ CMD ["npm", "start"]
374
+ ```
375
+
376
+ ## ๐Ÿ“ˆ Performance Considerations
377
+
378
+ ### Database Optimization
379
+ - **Indexes**: Create indexes on frequently queried fields
380
+ - **Connection Pooling**: MongoDB connection pooling enabled
381
+ - **Query Optimization**: Use Mongoose's built-in query optimization
382
+
383
+ ### Caching Strategy
384
+ - **Response Caching**: Implement Redis for frequently accessed data
385
+ - **Token Caching**: Cache JWT validation results
386
+ - **Rate Limit Caching**: Use Redis for distributed rate limiting
387
+
388
+ ### Monitoring
389
+ - **Health Checks**: `/health` endpoint for load balancer monitoring
390
+ - **Request Tracing**: Correlation IDs for distributed tracing
391
+ - **Performance Metrics**: Response times, error rates, throughput
392
+
393
+ ## ๐Ÿค Contributing
394
+
395
+ 1. Fork the repository
396
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
397
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
398
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
399
+ 5. Open a Pull Request
400
+
401
+ ### Development Guidelines
402
+ - Follow ESLint configuration
403
+ - Write tests for new features
404
+ - Update documentation as needed
405
+ - Use conventional commit messages
406
+ - Ensure all tests pass before submitting PR
407
+
408
+ ## ๐Ÿ“„ License
409
+
410
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
411
+
412
+ ## ๐Ÿ™ Acknowledgments
413
+
414
+ - [Express.js](https://expressjs.com/) - Web framework
415
+ - [MongoDB](https://www.mongodb.com/) - NoSQL database
416
+ - [Mongoose](https://mongoosejs.com/) - MongoDB ODM
417
+ - [JWT.io](https://jwt.io/) - JSON Web Tokens
418
+ - [Zod](https://zod.dev/) - TypeScript-first schema validation
419
+
420
+ ## ๐Ÿ“ž Support
421
+
422
+ For questions or issues:
423
+ - Create an issue on GitHub
424
+ - Check the documentation
425
+ - Review existing issues and solutions
426
+
427
+ ---
428
+
429
+ **Built with โค๏ธ for production-ready Node.js APIs**
@@ -0,0 +1,13 @@
1
+ NODE_ENV=development
2
+ PORT=3000
3
+ MONGODB_URI=mongodb://localhost:27017/theta-app
4
+ JWT_SECRET=your-super-secret-jwt-key-min-32-characters-required
5
+ JWT_REFRESH_SECRET=your-super-secret-refresh-key-min-32-characters-required
6
+ JWT_EXPIRES_IN=7d
7
+ JWT_REFRESH_EXPIRES_IN=30d
8
+ BCRYPT_SALT_ROUNDS=12
9
+ RATE_LIMIT_WINDOW_MS=900000
10
+ RATE_LIMIT_MAX=100
11
+ AUTH_RATE_LIMIT_MAX=10
12
+ CORS_ORIGIN=http://localhost:3000
13
+ LOG_LEVEL=info
@@ -0,0 +1,22 @@
1
+ node_modules/
2
+ .env
3
+ dist/
4
+ build/
5
+ coverage/
6
+ .nyc_output/
7
+ logs/
8
+ *.log
9
+ npm-debug.log*
10
+ yarn-debug.log*
11
+ yarn-error.log*
12
+ .DS_Store
13
+ Thumbs.db
14
+ .vscode/
15
+ .idea/
16
+ *.swp
17
+ *.swo
18
+ *~
19
+ .cache/
20
+ .env.local
21
+ .env.*.local
22
+ .env.test