@gaias/basenode 1.0.42 → 1.0.43
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/package.json +2 -3
- package/CLAUDE.md +0 -760
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gaias/basenode",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.43",
|
|
4
4
|
"buildNumber": 251025471,
|
|
5
5
|
"description": "API development framework for NodeJs",
|
|
6
6
|
"author": "FOT",
|
|
@@ -9,8 +9,7 @@
|
|
|
9
9
|
"types": "dist/index.d.ts",
|
|
10
10
|
"files": [
|
|
11
11
|
"dist",
|
|
12
|
-
"README.md"
|
|
13
|
-
"CLAUDE.md"
|
|
12
|
+
"README.md"
|
|
14
13
|
],
|
|
15
14
|
"repository": {
|
|
16
15
|
"type": "git",
|
package/CLAUDE.md
DELETED
|
@@ -1,760 +0,0 @@
|
|
|
1
|
-
# CLAUDE.md
|
|
2
|
-
|
|
3
|
-
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
-
|
|
5
|
-
## Table of Contents
|
|
6
|
-
|
|
7
|
-
- [Project Overview](#project-overview)
|
|
8
|
-
- [Quick Start](#quick-start)
|
|
9
|
-
- [Development Commands](#development-commands)
|
|
10
|
-
- [Database Code Generation](#database-code-generation)
|
|
11
|
-
- [Architecture](#architecture)
|
|
12
|
-
- [Bootstrap System](#bootstrap-system)
|
|
13
|
-
- [Configuration Management](#configuration-management)
|
|
14
|
-
- [Dependency Injection](#dependency-injection)
|
|
15
|
-
- [Controller Pattern](#controller-pattern)
|
|
16
|
-
- [Data Layer](#data-layer)
|
|
17
|
-
- [Validation and Transformation](#validation-and-transformation)
|
|
18
|
-
- [Health Check](#health-check)
|
|
19
|
-
- [Pagination](#pagination)
|
|
20
|
-
- [Caching](#caching)
|
|
21
|
-
- [Distributed Events](#distributed-events)
|
|
22
|
-
- [Leader Election](#leader-election)
|
|
23
|
-
- [API Gateway Integration](#api-gateway-integration)
|
|
24
|
-
- [Error Handling](#error-handling)
|
|
25
|
-
- [Logging](#logging)
|
|
26
|
-
- [TypeScript Configuration](#typescript-configuration)
|
|
27
|
-
- [Project Structure](#project-structure)
|
|
28
|
-
- [Key Dependencies](#key-dependencies)
|
|
29
|
-
- [Entry Point](#entry-point)
|
|
30
|
-
- [Best Practices](#best-practices)
|
|
31
|
-
- [Module References](#module-references)
|
|
32
|
-
- [Publishing](#publishing)
|
|
33
|
-
|
|
34
|
-
## Project Overview
|
|
35
|
-
|
|
36
|
-
`@gaias/basenode` (v1.0.24) is a Node.js API development framework built on Koa, TypeORM, TypeDI, and routing-controllers. It provides a microframework architecture with built-in support for RESTful APIs, WebSocket controllers, database ORM, distributed events via RabbitMQ, Redis caching, and API gateway integration with APISIX.
|
|
37
|
-
|
|
38
|
-
**Requirements:**
|
|
39
|
-
- Node.js: >=18.0.0
|
|
40
|
-
- Yarn: >=1.22.x
|
|
41
|
-
- MariaDB/MySQL: 5.7+ or 8.0+ (for production use)
|
|
42
|
-
- Redis: 6.0+ (optional, for caching and leader election)
|
|
43
|
-
- RabbitMQ: 3.8+ (optional, for distributed events)
|
|
44
|
-
|
|
45
|
-
## Quick Start
|
|
46
|
-
|
|
47
|
-
1. **Install dependencies:**
|
|
48
|
-
```bash
|
|
49
|
-
yarn install
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
2. **Configure database:**
|
|
53
|
-
- Edit `cfg/database.yml` with your MariaDB/MySQL connection details
|
|
54
|
-
- Edit `cfg/redis.yml` for Redis (if using caching)
|
|
55
|
-
- Edit `cfg/rabbitmq.yml` for RabbitMQ (if using distributed events)
|
|
56
|
-
|
|
57
|
-
3. **Set environment variables (optional):**
|
|
58
|
-
```bash
|
|
59
|
-
# Create .env file or export variables
|
|
60
|
-
NODE_ENV=development # Environment: development, production, test
|
|
61
|
-
ENABLE_API_GATEWAY=true # Enable APISIX gateway registration
|
|
62
|
-
API_GATEWAY_HOST_PORT=192.168.1.100:9180 # Gateway admin API address
|
|
63
|
-
DOMAINS=example.com,*.example.com # Allowed domains for gateway
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
4. **Generate database code (optional):**
|
|
67
|
-
```bash
|
|
68
|
-
# Define tables in gen_db.json, then:
|
|
69
|
-
yarn gen:db
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
5. **Run development server:**
|
|
73
|
-
```bash
|
|
74
|
-
yarn dev
|
|
75
|
-
# App starts on http://localhost:3000 (or configured port)
|
|
76
|
-
# Health check: http://localhost:3000/_healthcheck
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
6. **Run tests and linting:**
|
|
80
|
-
```bash
|
|
81
|
-
yarn test
|
|
82
|
-
yarn lint
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
## Development Commands
|
|
86
|
-
|
|
87
|
-
### Running the Application
|
|
88
|
-
```bash
|
|
89
|
-
# Development mode with hot reload
|
|
90
|
-
yarn dev
|
|
91
|
-
|
|
92
|
-
# Development mode with API gateway enabled (production-like)
|
|
93
|
-
yarn devPro
|
|
94
|
-
|
|
95
|
-
# Run compiled example app using ncc
|
|
96
|
-
yarn ncc:run
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
### Building
|
|
100
|
-
```bash
|
|
101
|
-
# Build for publishing (transpiles src/ to dist/)
|
|
102
|
-
yarn prepublish
|
|
103
|
-
|
|
104
|
-
# Build single-file executable with ncc
|
|
105
|
-
yarn ncc:build
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
### Linting
|
|
109
|
-
```bash
|
|
110
|
-
# Type check and lint
|
|
111
|
-
yarn lint
|
|
112
|
-
|
|
113
|
-
# Auto-fix linting issues
|
|
114
|
-
yarn lint:fix
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
### Security
|
|
118
|
-
```bash
|
|
119
|
-
# Run security audit on dependencies
|
|
120
|
-
yarn security
|
|
121
|
-
|
|
122
|
-
# Show audit summary only
|
|
123
|
-
yarn security:summary
|
|
124
|
-
|
|
125
|
-
# Output audit results in JSON format
|
|
126
|
-
yarn security:json
|
|
127
|
-
|
|
128
|
-
# Run enhanced security check with mitigation context (recommended)
|
|
129
|
-
yarn security:check
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
**Security Policy:** See `SECURITY.md` for comprehensive security guidelines, vulnerability reporting procedures, and mitigation strategies. The project includes automated security auditing via `yarn audit` and custom reporting tools.
|
|
133
|
-
|
|
134
|
-
**Vulnerability Mitigation:** See `VULNERABILITY_MITIGATION.md` for detailed information about known vulnerabilities and their mitigation status. The enhanced security check (`yarn security:check`) provides contextual information about mitigated vulnerabilities and exit code 0 when all vulnerabilities are properly mitigated.
|
|
135
|
-
|
|
136
|
-
### Testing
|
|
137
|
-
```bash
|
|
138
|
-
# Run all tests
|
|
139
|
-
yarn test
|
|
140
|
-
|
|
141
|
-
# Run tests in watch mode
|
|
142
|
-
yarn test:watch
|
|
143
|
-
|
|
144
|
-
# Run tests with coverage report
|
|
145
|
-
yarn test:coverage
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
**Testing Framework:** Jest is configured for unit and integration testing. Test files should use `*.test.ts` or `*.spec.ts` naming convention.
|
|
149
|
-
|
|
150
|
-
### Dependency Management
|
|
151
|
-
```bash
|
|
152
|
-
# Check for outdated dependencies
|
|
153
|
-
yarn deps:check
|
|
154
|
-
|
|
155
|
-
# Update dependencies to latest versions
|
|
156
|
-
yarn deps:update
|
|
157
|
-
|
|
158
|
-
# Update dependencies (alternative command)
|
|
159
|
-
yarn upver
|
|
160
|
-
```
|
|
161
|
-
|
|
162
|
-
### Database Code Generation
|
|
163
|
-
|
|
164
|
-
The framework includes automated code generation tools for database entities and repositories:
|
|
165
|
-
|
|
166
|
-
```bash
|
|
167
|
-
# Generate entities from database schema
|
|
168
|
-
yarn gen:db-schema
|
|
169
|
-
|
|
170
|
-
# Generate repository classes from entities
|
|
171
|
-
yarn gen:db-repo
|
|
172
|
-
|
|
173
|
-
# Generate both entities and repositories, then fix linting
|
|
174
|
-
yarn gen:db
|
|
175
|
-
|
|
176
|
-
# Generate index.ts files for all modules
|
|
177
|
-
yarn gen:idx
|
|
178
|
-
```
|
|
179
|
-
|
|
180
|
-
**Important:** Before running database generation:
|
|
181
|
-
1. Ensure MariaDB/MySQL is running and accessible
|
|
182
|
-
2. Configure database connection in `cfg/database.yml`
|
|
183
|
-
3. Define which tables to generate in `gen_db.json` (array of table names)
|
|
184
|
-
|
|
185
|
-
The generators use `typeorm-model-generator` with custom Mustache templates (`tools/repository.mst`) to create:
|
|
186
|
-
- **Entities** in `example/entities/` (or configured output path)
|
|
187
|
-
- **Repositories** in `example/repositories/` with `Repo` suffix
|
|
188
|
-
|
|
189
|
-
Generated repositories extend `BaseRepository<T>` and won't be overwritten if they already exist.
|
|
190
|
-
|
|
191
|
-
### Other Commands
|
|
192
|
-
```bash
|
|
193
|
-
# Generate RSA keys for JWT (stored in ./keys/)
|
|
194
|
-
yarn gen:keys
|
|
195
|
-
|
|
196
|
-
# Update build number
|
|
197
|
-
yarn buildNum
|
|
198
|
-
|
|
199
|
-
# Pre-commit hook (runs linting)
|
|
200
|
-
yarn precommit
|
|
201
|
-
```
|
|
202
|
-
|
|
203
|
-
## Architecture
|
|
204
|
-
|
|
205
|
-
### Bootstrap System
|
|
206
|
-
|
|
207
|
-
The application uses a microframework loader pattern orchestrated by `src/server/bootstrap.ts`. The bootstrap function accepts a `BootstrapOption` that combines multiple loader configurations and sequentially initializes:
|
|
208
|
-
|
|
209
|
-
1. **TypeORM Loader** - Database connection and entity registration
|
|
210
|
-
2. **Redis Loader** - Redis client initialization
|
|
211
|
-
3. **RabbitMQ Loader** - Distributed event system setup
|
|
212
|
-
4. **Koa Loader** - Web server with RESTful and WebSocket controllers
|
|
213
|
-
5. **API Gateway Loader** - APISIX integration for service registration
|
|
214
|
-
|
|
215
|
-
Each loader can be disabled via flags (`disableDatabase`, `disableRedis`, `disableEvent`).
|
|
216
|
-
|
|
217
|
-
### Configuration Management
|
|
218
|
-
|
|
219
|
-
Configuration is managed through YAML files in the `cfg/` directory, loaded by `ConfigManager`:
|
|
220
|
-
|
|
221
|
-
- `application.yml` - App name, version, port, and general settings
|
|
222
|
-
- `database.yml` - MariaDB/MySQL connection configuration
|
|
223
|
-
- `redis.yml` - Redis connection settings (host, port, password, db)
|
|
224
|
-
- `rabbitmq.yml` - RabbitMQ connection URL and settings
|
|
225
|
-
- `logger.yml` - Pino logger configuration (level, pretty print)
|
|
226
|
-
- `apisix.yml` - API gateway settings (admin URL, credentials)
|
|
227
|
-
- `openapiCfg.yml` - OpenAPI/Swagger documentation configuration
|
|
228
|
-
|
|
229
|
-
Configuration files support environment-specific overrides (e.g., `application.development.yml`, `application.production.yml`). The system automatically loads the base config and merges environment-specific settings based on `NODE_ENV`.
|
|
230
|
-
|
|
231
|
-
Access configuration via:
|
|
232
|
-
```typescript
|
|
233
|
-
import { ConfigManager } from '@/libs/configure';
|
|
234
|
-
|
|
235
|
-
const appConfig = ConfigManager.getConfig<ApplicationConfig>('application');
|
|
236
|
-
const dbConfig = ConfigManager.getConfig<DatabaseConfig>('database');
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
### Dependency Injection
|
|
240
|
-
|
|
241
|
-
The framework uses TypeDI for IoC. Services and repositories are decorated with `@Service()` and injected via `@Inject()` or constructor injection. The `Container` is automatically configured during bootstrap.
|
|
242
|
-
|
|
243
|
-
**Simplified Imports via `deps` Module:**
|
|
244
|
-
|
|
245
|
-
The framework provides a unified dependency export module (`src/libs/deps`) with short namespace aliases for cleaner imports. See `src/libs/deps/README.md` for comprehensive documentation.
|
|
246
|
-
|
|
247
|
-
```typescript
|
|
248
|
-
import { rest, di, orm, cv, ct, ws, api, tx } from '@/libs/deps';
|
|
249
|
-
|
|
250
|
-
// Instead of:
|
|
251
|
-
// import { Service } from 'typedi';
|
|
252
|
-
// import { JsonController, Get, Post, Body } from 'routing-controllers';
|
|
253
|
-
// import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
|
|
254
|
-
// import { IsString, IsEmail } from 'class-validator';
|
|
255
|
-
|
|
256
|
-
@rest.JsonController('/users') // routing-controllers
|
|
257
|
-
@di.Service() // typedi
|
|
258
|
-
class UserController {
|
|
259
|
-
@rest.Get('/')
|
|
260
|
-
async getAll() { return []; }
|
|
261
|
-
|
|
262
|
-
@rest.Post('/')
|
|
263
|
-
async create(@rest.Body() data: CreateUserDto) {
|
|
264
|
-
// rest.Body auto-enables excludeExtraneousValues for security
|
|
265
|
-
return {};
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
```
|
|
269
|
-
|
|
270
|
-
**Namespace Aliases:**
|
|
271
|
-
- `ct` = class-transformer
|
|
272
|
-
- `cv` = class-validator
|
|
273
|
-
- `di` = typedi
|
|
274
|
-
- `orm` = typeorm
|
|
275
|
-
- `tx` = typeorm-transactional
|
|
276
|
-
- `rest` = routing-controllers (enhanced with secure Body decorator)
|
|
277
|
-
- `ws` = socket-controllers
|
|
278
|
-
- `api` = routing-controllers-openapi
|
|
279
|
-
|
|
280
|
-
### Controller Pattern
|
|
281
|
-
|
|
282
|
-
**RESTful Controllers** extend `UniversalController` and use `routing-controllers` decorators:
|
|
283
|
-
- `@JsonController()` - Define controller class
|
|
284
|
-
- `@Get()`, `@Post()`, `@Put()`, `@Delete()` - HTTP methods with optional scopes
|
|
285
|
-
- Method signature: `@Method(path, scope?, module?)`
|
|
286
|
-
- `UniversalController` provides CRUD operations for entities via `getUniversalService(Entity)`
|
|
287
|
-
|
|
288
|
-
**WebSocket Controllers** use `socket-controllers`:
|
|
289
|
-
- Use `@OnConnect`, `@OnDisconnect`, `@OnMessage` decorators
|
|
290
|
-
- Registered via `wsControllers` in bootstrap options
|
|
291
|
-
|
|
292
|
-
### Data Layer
|
|
293
|
-
|
|
294
|
-
**Entities** are TypeORM entities with decorators (`@Entity`, `@Column`, `@PrimaryGeneratedColumn`, etc.). Auto-generated from database schema.
|
|
295
|
-
|
|
296
|
-
**Repositories** extend `BaseRepository<Entity>` providing:
|
|
297
|
-
- `find()`, `findOne()`, `findById()`
|
|
298
|
-
- `save()`, `update()`, `delete()`
|
|
299
|
-
|
|
300
|
-
**UniversalService** provides high-level CRUD with transformation:
|
|
301
|
-
- `create()`, `readById()`, `update()`, `remove()`
|
|
302
|
-
- `getAll(VoClass)`, `query(search, options)` - With pagination support
|
|
303
|
-
- Automatic VO transformation using `class-transformer`
|
|
304
|
-
|
|
305
|
-
### Validation and Transformation
|
|
306
|
-
|
|
307
|
-
Use `class-validator` decorators on VO (Value Object) classes wrapped with `@i18n()` for internationalized error messages:
|
|
308
|
-
```typescript
|
|
309
|
-
class UserVo {
|
|
310
|
-
@i18n(IsString)
|
|
311
|
-
@i18n(MaxLength, 50)
|
|
312
|
-
userName: string;
|
|
313
|
-
}
|
|
314
|
-
```
|
|
315
|
-
|
|
316
|
-
**⚠️ Security - URL Validation:**
|
|
317
|
-
Use `@IsSafeUrl()` instead of `@IsUrl()` to avoid CVE-2025-56200 in validator.js:
|
|
318
|
-
```typescript
|
|
319
|
-
import { IsSafeUrl } from '@/libs/validator';
|
|
320
|
-
|
|
321
|
-
class UserVo {
|
|
322
|
-
@IsSafeUrl() // ✅ Secure
|
|
323
|
-
website: string;
|
|
324
|
-
|
|
325
|
-
@IsSafeUrl({ protocols: ['https'] })
|
|
326
|
-
secureUrl: string;
|
|
327
|
-
}
|
|
328
|
-
```
|
|
329
|
-
See `src/libs/validator/README.md` and `SECURITY.md` for details.
|
|
330
|
-
|
|
331
|
-
Transform responses with `@Transform(VoClass)` decorator on controller methods.
|
|
332
|
-
|
|
333
|
-
### Health Check
|
|
334
|
-
|
|
335
|
-
Built-in health check endpoint at `/_healthcheck` provided by `HealthCheckController`:
|
|
336
|
-
|
|
337
|
-
```typescript
|
|
338
|
-
// Basic health check
|
|
339
|
-
GET /_healthcheck
|
|
340
|
-
// Response: { healthy: true, dbAlive: true }
|
|
341
|
-
|
|
342
|
-
// Detailed health check with OS info
|
|
343
|
-
GET /_healthcheck?os=true
|
|
344
|
-
// Response includes system info: hostname, platform, CPU, memory, network
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
The health check automatically:
|
|
348
|
-
- Tests database connectivity
|
|
349
|
-
- Reports server network information
|
|
350
|
-
- Optionally provides OS-level metrics (CPU, memory, uptime)
|
|
351
|
-
|
|
352
|
-
### Pagination
|
|
353
|
-
|
|
354
|
-
Complete pagination solution in `src/libs/pagination` with TypeORM integration:
|
|
355
|
-
|
|
356
|
-
**PaginationIn** - Standardized pagination request parameters:
|
|
357
|
-
```typescript
|
|
358
|
-
class PaginationIn {
|
|
359
|
-
pageIndex?: number; // Page number (starts from 1)
|
|
360
|
-
recordIndex?: number; // Record offset (starts from 0) - for infinite scroll
|
|
361
|
-
pageSize: number = 25; // Items per page
|
|
362
|
-
search?: string; // Search keyword
|
|
363
|
-
sort?: string; // Sort fields (e.g., "!createdAt" for DESC)
|
|
364
|
-
}
|
|
365
|
-
```
|
|
366
|
-
|
|
367
|
-
**PaginationOut** - Pagination response with auto-transformation:
|
|
368
|
-
```typescript
|
|
369
|
-
// Service example
|
|
370
|
-
async search(pagination: PaginationIn): Promise<PaginationOut<UserVo, User>> {
|
|
371
|
-
const qb = this.userRepo.createQueryBuilder('user');
|
|
372
|
-
|
|
373
|
-
// Add search conditions
|
|
374
|
-
if (pagination.search) {
|
|
375
|
-
qb.where('user.name LIKE :search', { search: `%${pagination.search}%` });
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
// Add sorting (auto-converts camelCase to snake_case)
|
|
379
|
-
setSorting(qb, 'user', ...pagination.sort?.split(',') || []);
|
|
380
|
-
|
|
381
|
-
// Calculate pagination
|
|
382
|
-
const total = await qb.getCount();
|
|
383
|
-
const { skip, take } = skipAndTake(total, pagination);
|
|
384
|
-
const data = await qb.skip(skip).take(take).getMany();
|
|
385
|
-
|
|
386
|
-
// Return with auto-transformation to VO
|
|
387
|
-
return new PaginationOut(total, pagination.pageSize, UserVo, data);
|
|
388
|
-
}
|
|
389
|
-
```
|
|
390
|
-
|
|
391
|
-
**Sorting features:**
|
|
392
|
-
- Single/multiple field sorting: `"createdAt"` or `"status,!createdAt"`
|
|
393
|
-
- Descending order: prefix with `!` (e.g., `"!updatedAt"`)
|
|
394
|
-
- Auto-converts camelCase to snake_case for database columns
|
|
395
|
-
- Helper functions: `setSorting()`, `getSorting()`, `skipAndTake()`
|
|
396
|
-
|
|
397
|
-
### Caching
|
|
398
|
-
|
|
399
|
-
Two-level caching system:
|
|
400
|
-
|
|
401
|
-
**L1 Cache** - In-memory with TTL:
|
|
402
|
-
```typescript
|
|
403
|
-
@Get('/path')
|
|
404
|
-
@L1Cache({ ttlSeconds: 60 })
|
|
405
|
-
async method() { }
|
|
406
|
-
```
|
|
407
|
-
|
|
408
|
-
**L2 Cache** - Redis-backed via `CacheService`:
|
|
409
|
-
```typescript
|
|
410
|
-
@Inject()
|
|
411
|
-
private cacheService: CacheService;
|
|
412
|
-
|
|
413
|
-
await this.cacheService.set('key', value, ttl);
|
|
414
|
-
await this.cacheService.get('key');
|
|
415
|
-
```
|
|
416
|
-
|
|
417
|
-
### Distributed Events
|
|
418
|
-
|
|
419
|
-
RabbitMQ-based pub/sub system via `DistributedEvents`:
|
|
420
|
-
|
|
421
|
-
**Publishing events:**
|
|
422
|
-
```typescript
|
|
423
|
-
events.pub('eventName', { data });
|
|
424
|
-
```
|
|
425
|
-
|
|
426
|
-
**Subscribing to events:**
|
|
427
|
-
```typescript
|
|
428
|
-
events.sub(['event.pattern.*']);
|
|
429
|
-
events.on('RemoteEvent', (eventName, data) => { });
|
|
430
|
-
```
|
|
431
|
-
|
|
432
|
-
Event handlers are classes decorated with `@Service()` registered in `eventsHandlers` bootstrap option.
|
|
433
|
-
|
|
434
|
-
### Leader Election
|
|
435
|
-
|
|
436
|
-
Redis-based leader election for distributed systems using the `Leader` service:
|
|
437
|
-
```typescript
|
|
438
|
-
await Container.get(Leader).config({ project: 'ProjectName' }).elect();
|
|
439
|
-
```
|
|
440
|
-
|
|
441
|
-
Emits `elected` and `revoked` events. Useful for scheduled tasks that should only run on one instance.
|
|
442
|
-
|
|
443
|
-
### API Gateway Integration
|
|
444
|
-
|
|
445
|
-
Automatic service registration with APISIX when `ENABLE_API_GATEWAY=true`. Routes are auto-discovered and registered with the gateway on startup.
|
|
446
|
-
|
|
447
|
-
### Error Handling
|
|
448
|
-
|
|
449
|
-
Use `BizError` for business logic errors with i18n support:
|
|
450
|
-
```typescript
|
|
451
|
-
throw new BizError('error.key');
|
|
452
|
-
// or with params
|
|
453
|
-
throw new BizError({ key: 'error.key', param: { name: 'value' } });
|
|
454
|
-
```
|
|
455
|
-
|
|
456
|
-
Use `ValidationHelper.check()` for custom validation logic.
|
|
457
|
-
|
|
458
|
-
### Logging
|
|
459
|
-
|
|
460
|
-
Pino-based logging via `Logger.getLogger(context)`:
|
|
461
|
-
```typescript
|
|
462
|
-
private logger = Logger.getLogger(MyClass);
|
|
463
|
-
this.logger.info('message');
|
|
464
|
-
this.logger.error('error', err);
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
## TypeScript Configuration
|
|
468
|
-
|
|
469
|
-
- Outputs to `temp/` during development
|
|
470
|
-
- Uses path alias `@/*` for `src/*`
|
|
471
|
-
- Decorators enabled (`experimentalDecorators`, `emitDecoratorMetadata`)
|
|
472
|
-
- Strict mode enabled
|
|
473
|
-
|
|
474
|
-
## Project Structure
|
|
475
|
-
|
|
476
|
-
```
|
|
477
|
-
src/
|
|
478
|
-
libs/ # Framework components
|
|
479
|
-
apisix/ # APISIX HTTP client and templates
|
|
480
|
-
cache/ # Two-level caching (L1/L2)
|
|
481
|
-
configure/ # YAML configuration management
|
|
482
|
-
deps/ # Dependency library exports (ct, cv, di, orm, rest, ws, api, tx)
|
|
483
|
-
error/ # Error handling (BizError, ErrorHandler)
|
|
484
|
-
gateway/ # API Gateway integration loader
|
|
485
|
-
generator/ # ID generation (nanoid, snowflake)
|
|
486
|
-
healthcheck/ # Health check endpoint controller
|
|
487
|
-
koa/ # Koa server setup and middleware
|
|
488
|
-
leader/ # Redis-based leader election
|
|
489
|
-
logger/ # Pino logger wrapper
|
|
490
|
-
network/ # Network utilities (local IP detection)
|
|
491
|
-
orm/ # TypeORM extensions (BaseRepository)
|
|
492
|
-
pagination/ # Pagination utilities (PaginationIn/Out, sorting)
|
|
493
|
-
rabbitmq/ # RabbitMQ distributed events
|
|
494
|
-
redis/ # Redis client wrapper
|
|
495
|
-
register/ # API route registration and metadata
|
|
496
|
-
type/ # Type definitions and builders
|
|
497
|
-
universal/ # UniversalController/Service for CRUD
|
|
498
|
-
validator/ # Validation helpers (i18n, SafeUrlValidator)
|
|
499
|
-
server/ # Bootstrap logic
|
|
500
|
-
utils/ # Utilities (JWT, crypto, YAML, transformer)
|
|
501
|
-
|
|
502
|
-
example/ # Example application
|
|
503
|
-
app.ts # Entry point
|
|
504
|
-
controllers/ # RESTful controllers
|
|
505
|
-
wsControllers/ # WebSocket controllers
|
|
506
|
-
entities/ # TypeORM entities (auto-generated)
|
|
507
|
-
repositories/ # Repository classes (auto-generated)
|
|
508
|
-
services/ # Business logic services
|
|
509
|
-
vo/ # Value Objects (DTOs)
|
|
510
|
-
events/ # Distributed event handlers
|
|
511
|
-
|
|
512
|
-
cfg/ # YAML configuration files
|
|
513
|
-
application.yml # App settings (name, version, port)
|
|
514
|
-
database.yml # Database connection
|
|
515
|
-
redis.yml # Redis connection
|
|
516
|
-
rabbitmq.yml # RabbitMQ connection
|
|
517
|
-
logger.yml # Logger settings
|
|
518
|
-
apisix.yml # API gateway settings
|
|
519
|
-
openapiCfg.yml # OpenAPI/Swagger config
|
|
520
|
-
|
|
521
|
-
tools/ # Development tools
|
|
522
|
-
DBSchemaGenerator.ts # Generate entities from DB schema
|
|
523
|
-
RepositoryGenerator.ts # Generate repository classes
|
|
524
|
-
repository.mst # Mustache template for repos
|
|
525
|
-
```
|
|
526
|
-
|
|
527
|
-
## Key Dependencies
|
|
528
|
-
|
|
529
|
-
### Core Framework
|
|
530
|
-
- **Koa** (^3.0.3) - Lightweight web framework
|
|
531
|
-
- **routing-controllers** (^0.11.3) - Decorator-based RESTful API routing
|
|
532
|
-
- **socket-controllers** (^0.3.1) - Decorator-based WebSocket controllers
|
|
533
|
-
- **TypeDI** (^0.10.0) - Dependency injection container
|
|
534
|
-
- **microframework** (^0.6.4) - Loader pattern for modular bootstrap
|
|
535
|
-
|
|
536
|
-
### Data Layer
|
|
537
|
-
- **TypeORM** (^0.3.27) - SQL ORM with full TypeScript support
|
|
538
|
-
- **typeorm-transactional** (^0.5.0) - Declarative transaction management
|
|
539
|
-
- **mysql2** (^3.15.2) - MySQL/MariaDB driver
|
|
540
|
-
- **class-validator** (^0.14.2) - Decorator-based validation
|
|
541
|
-
- **class-transformer** (^0.5.1) - Object-to-class transformation
|
|
542
|
-
|
|
543
|
-
### Caching & Messaging
|
|
544
|
-
- **ioredis** (^5.8.1) - Redis client with clustering support
|
|
545
|
-
- **amqplib** (^0.10.9) - RabbitMQ client for distributed events
|
|
546
|
-
|
|
547
|
-
### API Documentation
|
|
548
|
-
- **routing-controllers-openapi** (^5.0.0) - OpenAPI/Swagger spec generation
|
|
549
|
-
- **class-validator-jsonschema** (^5.1.0) - JSON Schema from validators
|
|
550
|
-
|
|
551
|
-
### Utilities
|
|
552
|
-
- **pino** (^10.0.0) + **pino-pretty** (^11.0.0) - High-performance logger
|
|
553
|
-
- **jsonwebtoken** (^9.0.2) - JWT authentication
|
|
554
|
-
- **lodash** (^4.17.21) - Utility functions
|
|
555
|
-
- **nanoid** (^5.1.6) - Compact unique ID generator
|
|
556
|
-
- **axios** (^1.12.2) - HTTP client
|
|
557
|
-
- **js-yaml** (^4.1.0) - YAML parser for configuration
|
|
558
|
-
|
|
559
|
-
### Recent Dependency Updates & Migration Notes
|
|
560
|
-
|
|
561
|
-
**TypeORM Transaction Management:** The project has migrated from `typeorm-transactional-cls-hooked` to `typeorm-transactional` (v0.5.0). The new library:
|
|
562
|
-
- No longer depends on `cls-hooked`, improving performance and compatibility
|
|
563
|
-
- Provides the same `@Transactional()` decorator API (no code changes needed)
|
|
564
|
-
- Requires `addTransactionalDataSource(dataSource)` during TypeORM initialization
|
|
565
|
-
- Better support for async/await and modern Node.js versions
|
|
566
|
-
|
|
567
|
-
**Repository Injection:** `typeorm-typedi-extensions` has been removed. Use direct TypeDI injection instead:
|
|
568
|
-
```typescript
|
|
569
|
-
// Old way (deprecated)
|
|
570
|
-
// import { OrmRepository } from 'typeorm-typedi-extensions';
|
|
571
|
-
// @OrmRepository(User) private userRepo: Repository<User>;
|
|
572
|
-
|
|
573
|
-
// New way (current)
|
|
574
|
-
@Service()
|
|
575
|
-
class UserService {
|
|
576
|
-
@Inject(() => UserRepo)
|
|
577
|
-
private userRepo: UserRepo;
|
|
578
|
-
}
|
|
579
|
-
```
|
|
580
|
-
|
|
581
|
-
**Security Updates:** The project uses Yarn resolutions to enforce secure versions of transitive dependencies:
|
|
582
|
-
- `validator` (^13.12.0) - Addresses CVE-2025-56200 (mitigated via SafeUrlValidator)
|
|
583
|
-
- `xml2js` (^0.6.2) - Fixes XML parsing vulnerabilities
|
|
584
|
-
- `tmp` (^0.2.4) - Secure temporary file handling
|
|
585
|
-
- `axios` (^1.12.2+) - Latest security patches
|
|
586
|
-
- See `package.json` resolutions and `SECURITY.md` for complete list
|
|
587
|
-
|
|
588
|
-
## Entry Point
|
|
589
|
-
|
|
590
|
-
Example app entry: `example/app.ts`
|
|
591
|
-
|
|
592
|
-
Import and call `bootstrap()` with configuration:
|
|
593
|
-
```typescript
|
|
594
|
-
bootstrap({
|
|
595
|
-
restfulControllers: [...controllers],
|
|
596
|
-
wsControllers: [...wsControllers],
|
|
597
|
-
entities: [...entities],
|
|
598
|
-
eventsHandlers: [...handlers],
|
|
599
|
-
})
|
|
600
|
-
```
|
|
601
|
-
|
|
602
|
-
## Best Practices
|
|
603
|
-
|
|
604
|
-
### Controller Design
|
|
605
|
-
- Extend `UniversalController` for standard CRUD operations
|
|
606
|
-
- Use `@rest.Body()` for request body (auto-enables security filtering)
|
|
607
|
-
- Apply `@Transform(VoClass)` decorator for response transformation
|
|
608
|
-
- Group related endpoints under a single controller
|
|
609
|
-
- Use scopes for role-based access control (e.g., `@Get('/', 'admin')`)
|
|
610
|
-
|
|
611
|
-
### Service Layer
|
|
612
|
-
- Keep controllers thin, business logic in services
|
|
613
|
-
- Use `UniversalService` for common CRUD operations
|
|
614
|
-
- Apply `@Transactional()` decorator for database transactions
|
|
615
|
-
- Inject repositories via TypeDI: `@Inject(() => UserRepo)`
|
|
616
|
-
|
|
617
|
-
### Data Validation
|
|
618
|
-
- Always validate input with `class-validator` decorators
|
|
619
|
-
- Wrap validators with `@i18n()` for internationalized error messages
|
|
620
|
-
- Use `@IsSafeUrl()` instead of `@IsUrl()` to avoid CVE-2025-56200
|
|
621
|
-
- Mark optional fields with `@IsOptional()`
|
|
622
|
-
|
|
623
|
-
### Database Operations
|
|
624
|
-
- Use TypeORM query builder for complex queries
|
|
625
|
-
- Apply pagination with `PaginationIn` and `PaginationOut`
|
|
626
|
-
- Use `setSorting()` helper for dynamic sorting
|
|
627
|
-
- Never concatenate user input into SQL queries (use parameterized queries)
|
|
628
|
-
|
|
629
|
-
### Error Handling
|
|
630
|
-
- Throw `BizError` for business logic errors with i18n keys
|
|
631
|
-
- Let the framework handle routing-controllers validation errors
|
|
632
|
-
- Use `ValidationHelper.check()` for custom validation logic
|
|
633
|
-
- Log errors with context: `this.logger.error('message', error)`
|
|
634
|
-
|
|
635
|
-
### Performance
|
|
636
|
-
- Use L1 cache (`@L1Cache`) for frequently accessed, rarely changing data
|
|
637
|
-
- Use L2 cache (Redis) for shared state across instances
|
|
638
|
-
- Implement pagination for list endpoints
|
|
639
|
-
- Use leader election for scheduled tasks in distributed systems
|
|
640
|
-
|
|
641
|
-
### Security
|
|
642
|
-
- Review `SECURITY.md` before adding dependencies
|
|
643
|
-
- Run `yarn security:report` regularly
|
|
644
|
-
- Never commit sensitive data (use `.env` files)
|
|
645
|
-
- Use `@Authorized()` decorator for protected endpoints
|
|
646
|
-
- Validate all user input, sanitize output
|
|
647
|
-
|
|
648
|
-
## Module References
|
|
649
|
-
|
|
650
|
-
For detailed documentation on specific modules:
|
|
651
|
-
- **deps module**: `src/libs/deps/README.md` - Unified dependency exports
|
|
652
|
-
- **validator**: `src/libs/validator/README.md` - Validation helpers and SafeUrlValidator
|
|
653
|
-
- **apisix**: `src/libs/apisix/README.md` - API gateway integration
|
|
654
|
-
- **gateway**: `src/libs/gateway/README.md` - Gateway loader
|
|
655
|
-
- **generator**: `src/libs/generator/README.md` - ID generation
|
|
656
|
-
- **koa**: `src/libs/koa/README.md` - Koa server setup
|
|
657
|
-
- **network**: `src/libs/network/README.md` - Network utilities
|
|
658
|
-
- **rabbitmq**: `src/libs/rabbitmq/README.md` - Distributed events
|
|
659
|
-
- **register**: `src/libs/register/README.md` - API route registration
|
|
660
|
-
- **type**: `src/libs/type/README.md` - Type utilities
|
|
661
|
-
- **universal**: `src/libs/universal/README.md` - Universal CRUD patterns
|
|
662
|
-
- **Security**: `SECURITY.md` - Comprehensive security guidelines
|
|
663
|
-
|
|
664
|
-
## Publishing
|
|
665
|
-
|
|
666
|
-
This is a private npm package (`UNLICENSED`). Publishing requires authentication:
|
|
667
|
-
```bash
|
|
668
|
-
npm_config__auth=<base64_token> yarn publish --access restricted
|
|
669
|
-
```
|
|
670
|
-
|
|
671
|
-
Before publishing:
|
|
672
|
-
1. Update version in `package.json`
|
|
673
|
-
2. Run `yarn buildNum` to update build number
|
|
674
|
-
3. Run `yarn security:report` to check for vulnerabilities
|
|
675
|
-
4. Run `yarn test` to ensure all tests pass
|
|
676
|
-
5. Run `yarn lint` to check code quality
|
|
677
|
-
6. Update changelog/release notes
|
|
678
|
-
|
|
679
|
-
## Contributing Guidelines
|
|
680
|
-
|
|
681
|
-
### Code Style
|
|
682
|
-
- Follow existing code conventions
|
|
683
|
-
- Use TypeScript strict mode
|
|
684
|
-
- Run `yarn lint:fix` before committing
|
|
685
|
-
- Use meaningful variable and function names
|
|
686
|
-
- Add JSDoc comments for public APIs
|
|
687
|
-
|
|
688
|
-
### Git Workflow
|
|
689
|
-
1. Create feature branch from `develope`
|
|
690
|
-
2. Make changes with descriptive commits
|
|
691
|
-
3. Run tests and linting
|
|
692
|
-
4. Create pull request to `develope` (not `main`)
|
|
693
|
-
5. Wait for code review
|
|
694
|
-
|
|
695
|
-
### Pre-commit Hooks
|
|
696
|
-
The project uses Husky for git hooks:
|
|
697
|
-
- Automatic linting on commit
|
|
698
|
-
- Tests run before push (if configured)
|
|
699
|
-
|
|
700
|
-
### Adding New Dependencies
|
|
701
|
-
1. Check for security vulnerabilities: `npm info <package>`
|
|
702
|
-
2. Add dependency: `yarn add <package>`
|
|
703
|
-
3. Run security audit: `yarn security:report`
|
|
704
|
-
4. Document breaking changes or new features
|
|
705
|
-
|
|
706
|
-
## Troubleshooting
|
|
707
|
-
|
|
708
|
-
### Common Issues
|
|
709
|
-
|
|
710
|
-
**Issue: Database connection fails**
|
|
711
|
-
- Verify `cfg/database.yml` connection string
|
|
712
|
-
- Check MariaDB/MySQL is running
|
|
713
|
-
- Ensure database user has proper permissions
|
|
714
|
-
|
|
715
|
-
**Issue: Redis connection fails**
|
|
716
|
-
- Check Redis is running: `redis-cli ping`
|
|
717
|
-
- Verify `cfg/redis.yml` settings
|
|
718
|
-
- Can disable Redis by setting `disableRedis: true` in bootstrap
|
|
719
|
-
|
|
720
|
-
**Issue: TypeORM entity not found**
|
|
721
|
-
- Ensure entity is registered in bootstrap `entities` array
|
|
722
|
-
- Check entity file has `@Entity()` decorator
|
|
723
|
-
- Verify import path is correct
|
|
724
|
-
|
|
725
|
-
**Issue: Validation errors not showing**
|
|
726
|
-
- Ensure DTO uses `@i18n()` wrapper for validators
|
|
727
|
-
- Check `class-validator` decorators are applied
|
|
728
|
-
- Verify `class-transformer` is properly configured
|
|
729
|
-
|
|
730
|
-
**Issue: Build fails with decorator errors**
|
|
731
|
-
- Check `tsconfig.json` has `experimentalDecorators: true`
|
|
732
|
-
- Ensure `emitDecoratorMetadata: true` is set
|
|
733
|
-
- Verify `reflect-metadata` is imported at app entry
|
|
734
|
-
|
|
735
|
-
## Additional Resources
|
|
736
|
-
|
|
737
|
-
### Framework Documentation
|
|
738
|
-
- [TypeORM Documentation](https://typeorm.io/)
|
|
739
|
-
- [routing-controllers Guide](https://github.com/typestack/routing-controllers)
|
|
740
|
-
- [TypeDI Documentation](https://github.com/typestack/typedi)
|
|
741
|
-
- [class-validator Decorators](https://github.com/typestack/class-validator)
|
|
742
|
-
- [class-transformer Guide](https://github.com/typestack/class-transformer)
|
|
743
|
-
|
|
744
|
-
### Infrastructure
|
|
745
|
-
- [Koa.js Website](https://koajs.com/)
|
|
746
|
-
- [Redis Documentation](https://redis.io/docs/)
|
|
747
|
-
- [RabbitMQ Tutorials](https://www.rabbitmq.com/tutorials)
|
|
748
|
-
- [APISIX Documentation](https://apisix.apache.org/docs/)
|
|
749
|
-
|
|
750
|
-
### Tools
|
|
751
|
-
- [Pino Logger](https://github.com/pinojs/pino)
|
|
752
|
-
- [Jest Testing](https://jestjs.io/)
|
|
753
|
-
- [ESLint Rules](https://eslint.org/docs/rules/)
|
|
754
|
-
|
|
755
|
-
---
|
|
756
|
-
|
|
757
|
-
**Last Updated:** 2025-10-23
|
|
758
|
-
**Framework Version:** 1.0.24
|
|
759
|
-
**Build Number:** 251022024
|
|
760
|
-
**Maintainer:** FOT Team
|