File size: 7,743 Bytes
9026edb
 
 
 
 
 
 
 
 
 
dffd7d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4acc19f
 
dffd7d2
4acc19f
 
dffd7d2
4acc19f
 
dffd7d2
 
 
 
 
 
 
 
 
 
 
 
4acc19f
dffd7d2
 
 
4acc19f
dffd7d2
 
 
 
 
 
4acc19f
 
dffd7d2
4acc19f
 
dffd7d2
 
4acc19f
dffd7d2
 
4acc19f
dffd7d2
 
4acc19f
 
dffd7d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4acc19f
dffd7d2
 
 
 
 
 
 
4acc19f
dffd7d2
 
 
 
 
 
 
 
 
 
 
4acc19f
 
dffd7d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4acc19f
 
dffd7d2
 
 
 
 
 
 
4acc19f
dffd7d2
4acc19f
dffd7d2
 
 
4acc19f
dffd7d2
 
 
 
4acc19f
dffd7d2
 
 
 
 
4acc19f
dffd7d2
4acc19f
dffd7d2
4acc19f
dffd7d2
 
 
 
 
4acc19f
dffd7d2
4acc19f
dffd7d2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
---
title: Streamflix Node API
emoji: 🎬
colorFrom: red
colorTo: purple
sdk: docker
app_file: Dockerfile
pinned: false
---

# πŸš€ NestJS Starter Template

A production-ready NestJS starter template with authentication, Prisma ORM, and best practices built-in. Clone this repo to kickstart any new project without repetitive setup.

## ✨ Features

- **Authentication System** - Complete JWT-based auth for Users and Super Admins
- **Prisma ORM** - Type-safe database access with PostgreSQL
- **Modular Architecture** - Clean separation of concerns with core services
- **Swagger Documentation** - Auto-generated API docs with authentication
- **Security** - Password hashing with bcrypt, JWT tokens, session management
- **TypeScript** - Full type safety throughout the codebase
- **ESLint & Prettier** - Code quality and formatting
- **Husky** - Git hooks for pre-commit checks

## πŸ“ Project Structure

```
src/
β”œβ”€β”€ core/                    # Core business logic services
β”‚   β”œβ”€β”€ base-query-core/     # Base query builder with pagination
β”‚   β”œβ”€β”€ user-core/           # User CRUD operations
β”‚   β”œβ”€β”€ user-credential-core/# User password management
β”‚   β”œβ”€β”€ user-session-core/   # User session management
β”‚   β”œβ”€β”€ super-admin-core/    # Super admin CRUD operations
β”‚   β”œβ”€β”€ super-admin-credential-core/
β”‚   └── super-admin-session-core/
β”œβ”€β”€ modules/                 # Feature modules
β”‚   β”œβ”€β”€ user/               # User module with auth
β”‚   β”‚   └── auth/           # User authentication
β”‚   └── super-admin/        # Super admin module with auth
β”‚       └── auth/           # Super admin authentication
β”œβ”€β”€ shared/                  # Shared utilities
β”‚   β”œβ”€β”€ decorators/         # Custom decorators
β”‚   β”œβ”€β”€ keys/               # Constants and messages
β”‚   β”œβ”€β”€ libs/               # Helper libraries
β”‚   β”œβ”€β”€ modules/            # Shared modules (Prisma, Common)
β”‚   └── types/              # TypeScript types
β”œβ”€β”€ app.module.ts           # Root module
β”œβ”€β”€ main.ts                 # Application entry point
└── swagger-setup.ts        # Swagger configuration
```

## πŸ› οΈ Quick Start

### 1. Clone the Repository

```bash
git clone <repository-url> my-new-project
cd my-new-project
```

### 2. Install Dependencies

```bash
npm install
```

### 3. Configure Environment

```bash
cp .env.example .env
```

Edit `.env` with your configuration:

```env
# Database
DATABASE_URL="postgresql://user:password@localhost:5432/database_name?schema=public"

# JWT Secrets
JWT_ACCESS_SECRET="your-super-secret-access-key"
JWT_REFRESH_SECRET="your-super-secret-refresh-key"

# JWT Expiration
JWT_ACCESS_EXPIRES_IN="24h"
JWT_REFRESH_EXPIRES_IN="7d"

# Swagger
SWAGGER_PASSWORD="admin123"

# Application
PORT=3000
NODE_ENV="development"
```

### 4. Setup Database

```bash
# Generate Prisma Client
npm run prisma:generate

# Push schema to database (development)
npm run prisma:push

# Or create migration (production)
npm run prisma:migrate dev --name init
```

### 5. Start Development Server

```bash
npm run start:dev
```

## πŸ“š API Documentation

Swagger UI available at: `http://localhost:3000/api`

- **Username:** `admin`
- **Password:** (from `SWAGGER_PASSWORD` in `.env`)

## πŸ” Authentication Endpoints

### User Authentication

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/user/auth/register` | Register new user |
| POST | `/user/auth/login` | Login user |
| POST | `/user/auth/logout` | Logout user |
| POST | `/user/auth/refresh-token` | Refresh access token |
| POST | `/user/auth/profile` | Get user profile |

### Super Admin Authentication

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/super-admin/auth/register` | Register super admin |
| POST | `/super-admin/auth/login` | Login super admin |
| POST | `/super-admin/auth/logout` | Logout super admin |
| POST | `/super-admin/auth/refresh-token` | Refresh access token |
| POST | `/super-admin/auth/profile` | Get super admin profile |

## πŸ“œ Available Scripts

```bash
# Development
npm run start:dev      # Start with hot-reload

# Production
npm run build          # Build the project
npm run start:prod     # Start production server

# Database
npm run prisma:generate  # Generate Prisma Client
npm run prisma:push      # Push schema to DB
npm run prisma:migrate   # Run migrations
npm run prisma:studio    # Open Prisma Studio

# Code Quality
npm run lint           # Run ESLint
npm run format         # Format with Prettier
npm run type-check     # TypeScript type checking

# Testing
npm run test           # Run unit tests
npm run test:e2e       # Run e2e tests
npm run test:cov       # Test coverage
```

## πŸ—„οΈ Database Schema

The starter includes these models:

- **User** - Basic user with email, phone, status
- **UserCredential** - Encrypted password storage
- **UserSession** - Session tracking with IP, user agent, geo
- **SuperAdmin** - Admin user management
- **SuperAdminCredential** - Admin password storage
- **SuperAdminSession** - Admin session tracking

## πŸ”§ Customization

### Adding a New Module

1. Create core service in `src/core/`
2. Create module in `src/modules/`
3. Add to Prisma schema
4. Run `npm run prisma:generate`

### Adding New Auth Type

1. Copy `src/modules/user/auth/` structure
2. Create new JWT strategy
3. Create new guard
4. Update `TOKEN_USER_TYPE` enum

## πŸ›‘οΈ Security Features

- βœ… Password hashing with bcrypt (12 rounds)
- βœ… JWT access & refresh tokens
- βœ… Separate credential tables
- βœ… Session tracking with geo-location
- βœ… Rate limiting with Throttler
- βœ… Swagger protected with basic auth

## πŸ“¦ Tech Stack

- **Framework:** NestJS 11
- **Language:** TypeScript 5.7
- **ORM:** Prisma 7 (with PostgreSQL adapter)
- **Database:** PostgreSQL
- **Auth:** Passport + JWT
- **Docs:** Swagger/OpenAPI
- **Validation:** class-validator
- **Concurrency:** p-limit (latest ESM version)

## ⚑ Prisma 7 Setup

This starter uses **Prisma 7** with the new adapter pattern for better performance and compatibility:

```typescript
// src/shared/modules/prisma/prisma.service.ts
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  constructor() {
    super({
      datasources: {
        db: {
          url: process.env.DATABASE_URL,
        },
      },
    });
  }

  async onModuleInit() {
    await this.$connect();
  }
}
```

### Prisma 7 Key Features Used:
- βœ… Extends `PrismaClient` directly (best practice)
- βœ… `OnModuleInit` for automatic connection
- βœ… Type-safe queries with full TypeScript support
- βœ… Improved connection pooling

## πŸ”„ ESM Package Handling (p-limit)

The starter handles ESM-only packages like `p-limit` (v7+) using dynamic imports:

```typescript
// src/shared/modules/prisma/safe-prisma-call.ts
let prismaConcurrencyLimit: <T>(fn: () => Promise<T>) => Promise<T>;

const initPLimit = (async () => {
  const pLimit = (await import('p-limit')).default;
  prismaConcurrencyLimit = pLimit(concurrencyLimit);
})();

export async function safePrismaCall<T>(fn: () => Promise<T>): Promise<T> {
  await initPLimit;
  return prismaConcurrencyLimit(fn);
}
```

This pattern allows using the latest ESM-only packages in a CommonJS NestJS environment.

## 🀝 Contributing

1. Fork the repository
2. Create feature branch (`git checkout -b feature/amazing`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing`)
5. Open a Pull Request

## πŸ“„ License

This project is [MIT licensed](LICENSE).