externelize entity template to tpl file
This commit is contained in:
parent
d5825644a4
commit
ed2388d7f6
@ -2,16 +2,19 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { ConfigService } from './config.service';
|
import { ConfigService } from './config.service';
|
||||||
import { DataSource, DataSourceOptions, TableColumn } from 'typeorm';
|
import { DataSource, DataSourceOptions, TableColumn } from 'typeorm';
|
||||||
|
import { ModuleUpdaterService } from './module-updater.service';
|
||||||
|
import { TemplateService } from './template.service'; // <-- 1. IMPORT TemplateService
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { promises as fsPromises } from 'fs';
|
import { promises as fsPromises } from 'fs';
|
||||||
import { ModuleUpdaterService } from './module-updater.service';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class EntityGeneratorService {
|
export class EntityGeneratorService {
|
||||||
constructor(private readonly configService: ConfigService,
|
constructor(
|
||||||
private readonly moduleUpdaterService: ModuleUpdaterService) {}
|
private readonly configService: ConfigService,
|
||||||
|
private readonly moduleUpdaterService: ModuleUpdaterService,
|
||||||
|
private readonly templateService: TemplateService, // <-- 2. INJECT TemplateService
|
||||||
|
) {}
|
||||||
|
|
||||||
public async generate(tableName: string): Promise<TableColumn[] | null> {
|
public async generate(tableName: string): Promise<TableColumn[] | null> {
|
||||||
console.log(`Generating entity for table: ${tableName}...`);
|
console.log(`Generating entity for table: ${tableName}...`);
|
||||||
@ -35,14 +38,28 @@ export class EntityGeneratorService {
|
|||||||
const columns = table.columns;
|
const columns = table.columns;
|
||||||
console.log(`Found ${columns.length} columns in table "${tableName}".`);
|
console.log(`Found ${columns.length} columns in table "${tableName}".`);
|
||||||
|
|
||||||
const entityContent = this.createEntityTemplate(tableName, columns);
|
|
||||||
|
|
||||||
const singularName = this.toSingular(tableName);
|
const singularName = this.toSingular(tableName);
|
||||||
|
|
||||||
// --- THIS IS THE FIX ---
|
|
||||||
// Define className here so it can be used below.
|
|
||||||
const className = this.toPascalCase(singularName);
|
const className = this.toPascalCase(singularName);
|
||||||
// --- END OF FIX ---
|
|
||||||
|
const props = columns
|
||||||
|
.map((col) => {
|
||||||
|
const typeormDecorator = this.getDecorator(col);
|
||||||
|
const validationDecorators = this.getValidationDecorators(col);
|
||||||
|
const tsType = this.mapDbToTsType(col.type);
|
||||||
|
const nullable = col.isNullable ? ' | null' : '';
|
||||||
|
const defaultValue = col.default ? ` = ${this.formatDefaultValue(col)}` : '';
|
||||||
|
const allDecorators = [typeormDecorator, validationDecorators].filter(Boolean).join('\n ');
|
||||||
|
return `\n ${allDecorators}\n ${col.name}: ${tsType}${nullable}${defaultValue};\n`;
|
||||||
|
})
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
// 4. Render the external template
|
||||||
|
const entityContent = this.templateService.render('nestjs/entity.ts.tpl', {
|
||||||
|
tableName: tableName,
|
||||||
|
className: className,
|
||||||
|
props: props,
|
||||||
|
});
|
||||||
|
// --- END OF REFACTOR ---
|
||||||
|
|
||||||
const entityFileName = `${singularName}.entity.ts`;
|
const entityFileName = `${singularName}.entity.ts`;
|
||||||
const serverRoot = path.resolve(process.cwd(), config.server.path);
|
const serverRoot = path.resolve(process.cwd(), config.server.path);
|
||||||
@ -53,11 +70,9 @@ export class EntityGeneratorService {
|
|||||||
fs.writeFileSync(outputPath, entityContent);
|
fs.writeFileSync(outputPath, entityContent);
|
||||||
console.log(`✅ Entity created successfully at: ${outputPath}`);
|
console.log(`✅ Entity created successfully at: ${outputPath}`);
|
||||||
|
|
||||||
// Now the call will work correctly
|
|
||||||
await this.moduleUpdaterService.addEntityToTypeOrm(className, outputPath);
|
await this.moduleUpdaterService.addEntityToTypeOrm(className, outputPath);
|
||||||
|
|
||||||
return columns;
|
return columns;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ An error occurred:', error.message);
|
console.error('❌ An error occurred:', error.message);
|
||||||
return null;
|
return null;
|
||||||
@ -69,31 +84,6 @@ export class EntityGeneratorService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private createEntityTemplate(tableName: string, columns: TableColumn[]): string {
|
|
||||||
const className = this.toPascalCase(this.toSingular(tableName));
|
|
||||||
|
|
||||||
const props = columns
|
|
||||||
.map((col) => {
|
|
||||||
const typeormDecorator = this.getDecorator(col);
|
|
||||||
const validationDecorators = this.getValidationDecorators(col);
|
|
||||||
const tsType = this.mapDbToTsType(col.type);
|
|
||||||
const nullable = col.isNullable ? ' | null' : '';
|
|
||||||
const defaultValue = col.default ? ` = ${this.formatDefaultValue(col)}` : '';
|
|
||||||
|
|
||||||
const allDecorators = [typeormDecorator, validationDecorators].filter(Boolean).join('\n ');
|
|
||||||
|
|
||||||
return `\n ${allDecorators}\n ${col.name}: ${tsType}${nullable}${defaultValue};\n`;
|
|
||||||
})
|
|
||||||
.join('');
|
|
||||||
|
|
||||||
return `import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
|
||||||
import { IsString, IsNumber, IsBoolean, IsDate, IsOptional } from 'class-validator';
|
|
||||||
|
|
||||||
@Entity({ name: '${tableName}' })
|
|
||||||
export class ${className} {${props}
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getValidationDecorators(column: TableColumn): string {
|
private getValidationDecorators(column: TableColumn): string {
|
||||||
if (column.isPrimary && column.isGenerated) {
|
if (column.isPrimary && column.isGenerated) {
|
||||||
|
|||||||
9
src/templates/nestjs/entity.ts.tpl
Normal file
9
src/templates/nestjs/entity.ts.tpl
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
// dvbooking-cli/src/templates/nestjs/entity.ts.tpl
|
||||||
|
|
||||||
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||||
|
import { IsString, IsNumber, IsBoolean, IsDate, IsOptional } from 'class-validator';
|
||||||
|
|
||||||
|
@Entity({ name: '{{tableName}}' })
|
||||||
|
export class {{className}} {
|
||||||
|
{{props}}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user