nestjs-resource-gen
Version:
A CLI tool to generate NestJS resources (controllers, services, DTOs, modules) from entity files
242 lines (179 loc) ⢠5.96 kB
Markdown
# NestJS Resource Generator
A powerful CLI tool that automatically generates complete NestJS resources (controllers, services, DTOs, modules, routes) from entity files. This tool also generates corresponding frontend interfaces and services for Angular applications.
## Features
- š **Automatic Resource Generation**: Creates controllers, services, DTOs, and modules from TypeORM entities
- š **Built-in Authorization**: Generates code with JWT authentication and permission-based authorization
- š **DTO Generation**: Creates Create, Update, and Patch DTOs with validation decorators
- š£ļø **Route Management**: Automatically adds routes to your routing configuration
- š **Permission Integration**: Adds permission items to your permission enum
- šÆ **Frontend Support**: Generates TypeScript interfaces and Angular services
- š¦ **Global Installation**: Install once, use anywhere
## Installation
### Global Installation (Recommended)
```bash
npm install -g nestjs-resource-generator
```
### Local Installation
```bash
npm install nestjs-resource-generator
```
## Usage
### Basic Usage
```bash
nestjs-resource-generator <entity-file-path>
```
### Example
```bash
# Generate resources for a Department entity
nestjs-resource-generator src/database/entities/Department.entity.ts
```
## What Gets Generated
For each entity file, the tool generates:
### Backend Files
- **Controller** (`department.controller.ts`) - REST API endpoints with CRUD operations
- **Service** (`department.service.ts`) - Business logic with repository pattern
- **DTOs** (`department.dto.ts`) - Data Transfer Objects with validation
- **Module** (`department.module.ts`) - NestJS module configuration
- **Routes** (`department.routes.ts`) - Route configuration
### Frontend Files
- **Interface** (`department.interface.ts`) - TypeScript interface
- **Service** (`department.service.ts`) - Angular HTTP service
### Configuration Updates
- Adds entity exports to `entities/index.ts`
- Adds permission items to `PermissionItem.entity.ts`
- Adds route exports to `routes/index.ts`
- Updates `routes.module.ts` with new routes
## Entity File Requirements
Your entity file should follow this structure:
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";
@Entity("departments")
export class Department {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ nullable: true })
description?: string;
@Column()
locationId: number;
}
```
## Generated Code Structure
### Controller Example
```typescript
@Controller()
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class DepartmentController {
constructor(private _departmentService: DepartmentService) {}
@Get("/")
@Serialize(DepartmentDTO)
@CheckPermissions([PermissionAction.READ, PERMISSION_ITEM_NAME.DEPARTMENTS])
async getAllDepartments() {
return await this._departmentService.getAllDepartments();
}
// ... more endpoints
}
```
### Service Example
```typescript
@Injectable({ scope: Scope.REQUEST })
export class DepartmentService {
constructor(
@InjectRepository(Department)
private departmentRepository: Repository<Department>,
private authzService: AuthzService
) {}
async getAllDepartments() {
// Implementation with authorization
}
// ... more methods
}
```
### DTOs Example
```typescript
export class DepartmentDTO {
@Expose()
@IsNumber()
@IsNotEmpty()
id: number;
@Expose()
@IsString()
@IsNotEmpty()
name: string;
@Expose()
@IsString()
@IsOptional()
description?: string;
}
export class DepartmentCreateDTO extends OmitType(DepartmentDTO, ["id"]) {}
export class DepartmentPatchDTO extends PartialType(DepartmentDTO) {}
```
## Project Structure
After running the generator, your project structure will look like:
```
src/
āāā database/
ā āāā entities/
ā āāā Department.entity.ts
ā āāā PermissionItem.entity.ts
ā āāā index.ts
āāā department/
ā āāā dtos/
ā ā āāā department.dto.ts
ā ā āāā index.ts
ā āāā department.controller.ts
ā āāā department.service.ts
ā āāā department.module.ts
āāā routes/
ā āāā department.routes.ts
ā āāā index.ts
ā āāā routes.module.ts
āāā Frontend/
āāā src/
āāā app/
āāā shared/
āāā interfaces/
ā āāā department.interface.ts
ā āāā index.ts
āāā services/
āāā department.service.ts
```
## Next Steps
After generation, you'll need to:
1. **Add the module to app.module.ts**:
```typescript
import { DepartmentModule } from "./department/department.module";
@Module({
imports: [
// ... other imports
DepartmentModule,
],
})
export class AppModule {}
```
2. **Add routes to your main routes module** (usually done automatically)
3. **Update any necessary imports and dependencies**
4. **Test the generated endpoints**
## Requirements
- Node.js >= 16.0.0
- TypeScript
- NestJS project structure
- TypeORM entities
## Dependencies
The generated code assumes you have these packages installed:
```bash
npm install @nestjs/common @nestjs/typeorm @nestjs/mapped-types
npm install class-validator class-transformer
npm install typeorm
```
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Support
If you encounter any issues or have questions, please open an issue on the GitHub repository.