83 lines
2.1 KiB
TypeScript
83 lines
2.1 KiB
TypeScript
import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
|
|
import { TemplateManager, Template } from './types';
|
|
import { CloseEyesTemplate, PhotoRestoreTemplate, CosplayRealPersonTemplate } from './n8nTemplates';
|
|
|
|
@Injectable()
|
|
export class TemplateService implements OnModuleInit {
|
|
private readonly logger = new Logger(TemplateService.name);
|
|
|
|
constructor(
|
|
private readonly templateManager: TemplateManager,
|
|
) {}
|
|
|
|
async onModuleInit() {
|
|
// 启动时自动注册所有模板
|
|
await this.initializeTemplates();
|
|
}
|
|
|
|
// 执行模板
|
|
async executeTemplate(
|
|
templateCode: string,
|
|
input: string
|
|
) {
|
|
// 1. 获取模板信息
|
|
const template = this.templateManager.getTemplate(templateCode);
|
|
if (!template) {
|
|
throw new Error(`模板 ${templateCode} 不存在`);
|
|
}
|
|
|
|
// 2. 检查用户积分(如果有积分服务)
|
|
// const hasEnoughCredits = await this.creditService.checkBalance(
|
|
// userId,
|
|
// platform as any,
|
|
// template.creditCost
|
|
// );
|
|
|
|
// if (!hasEnoughCredits) {
|
|
// throw new Error('积分不足');
|
|
// }
|
|
|
|
// 3. 执行模板
|
|
const result = await this.templateManager.executeTemplate(templateCode, input);
|
|
|
|
// 4. 扣除积分(仅在成功时)
|
|
// if (result.success) {
|
|
// await this.creditService.consumeCredits(
|
|
// userId,
|
|
// platform as any,
|
|
// template.creditCost,
|
|
// 'ai_generation' as any,
|
|
// requestId
|
|
// );
|
|
// }
|
|
|
|
return result;
|
|
}
|
|
|
|
// 获取所有模板
|
|
getAllTemplates(): Template[] {
|
|
return this.templateManager.getAllTemplates();
|
|
}
|
|
|
|
// 获取模板详情
|
|
getTemplate(templateCode: string): Template | null {
|
|
return this.templateManager.getTemplate(templateCode);
|
|
}
|
|
|
|
// 初始化模板
|
|
private async initializeTemplates(): Promise<void> {
|
|
this.logger.log('开始初始化模板...');
|
|
|
|
try {
|
|
this.templateManager.registerTemplates([
|
|
new PhotoRestoreTemplate(),
|
|
new CloseEyesTemplate(),
|
|
new CosplayRealPersonTemplate(),
|
|
]);
|
|
} catch (error) {
|
|
this.logger.error('模板初始化失败:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
}
|