refactor: 统一使用 ResponseUtil 构造 API 响应格式

- 统一 unified-user.controller.ts 的响应格式
- 统一 template.controller.ts 的响应格式
- 统一 content-moderation.controller.ts 的响应格式
- 所有响应现在包含 code、message、data、timestamp、traceId 字段
- 提高响应格式一致性和可追踪性
This commit is contained in:
imeepos
2025-09-05 15:04:52 +08:00
parent da5db8c5b6
commit 082775094e
3 changed files with 100 additions and 199 deletions

View File

@@ -9,6 +9,7 @@ import {
} from '../dto/audit-response.dto'; } from '../dto/audit-response.dto';
import { PlatformAuthGuard } from '../../platform/guards/platform-auth.guard'; import { PlatformAuthGuard } from '../../platform/guards/platform-auth.guard';
import { PlatformType } from '../../entities/platform-user.entity'; import { PlatformType } from '../../entities/platform-user.entity';
import { ResponseUtil, ApiResponse as ApiResponseType } from '../../utils/response.util';
// 模拟当前用户装饰器,实际应从现有项目中导入 // 模拟当前用户装饰器,实际应从现有项目中导入
const CurrentUser = () => { const CurrentUser = () => {
@@ -41,11 +42,7 @@ export class ContentModerationController {
const result = await this.unifiedContentService.auditImage(platform, auditData); const result = await this.unifiedContentService.auditImage(platform, auditData);
return { return ResponseUtil.success(result, '审核提交成功');
code: 200,
message: '审核提交成功',
data: result,
};
} }
@Post(':platform/audit-batch') @Post(':platform/audit-batch')
@@ -68,16 +65,12 @@ export class ContentModerationController {
const successCount = results.filter(r => r.status === 'completed').length; const successCount = results.filter(r => r.status === 'completed').length;
const failureCount = results.length - successCount; const failureCount = results.length - successCount;
return { return ResponseUtil.success({
code: 200, totalCount: results.length,
message: '批量审核提交成功', successCount,
data: { failureCount,
totalCount: results.length, results,
successCount, }, '批量审核提交成功');
failureCount,
results,
},
};
} }
@Get(':platform/result/:taskId') @Get(':platform/result/:taskId')
@@ -91,11 +84,7 @@ export class ContentModerationController {
) { ) {
const result = await this.unifiedContentService.queryAuditResult(platform, taskId); const result = await this.unifiedContentService.queryAuditResult(platform, taskId);
return { return ResponseUtil.success(result, '查询成功');
code: 200,
message: '查询成功',
data: result,
};
} }
@Post(':platform/callback') @Post(':platform/callback')
@@ -106,10 +95,7 @@ export class ContentModerationController {
) { ) {
await this.unifiedContentService.handleAuditCallback(platform, callbackData); await this.unifiedContentService.handleAuditCallback(platform, callbackData);
return { return ResponseUtil.success(null, '回调处理成功');
code: 200,
message: '回调处理成功',
};
} }
@Get('history') @Get('history')
@@ -122,14 +108,10 @@ export class ContentModerationController {
) { ) {
const history = await this.unifiedContentService.getUserAuditHistory(user.userId, limit); const history = await this.unifiedContentService.getUserAuditHistory(user.userId, limit);
return { return ResponseUtil.success({
code: 200, total: history.length,
message: '获取成功', list: history,
data: { }, '获取成功');
total: history.length,
list: history,
},
};
} }
@Get('stats') @Get('stats')
@@ -157,23 +139,19 @@ export class ContentModerationController {
const avgConfidence = stats.reduce((sum: number, item: any) => const avgConfidence = stats.reduce((sum: number, item: any) =>
sum + (parseFloat(item.avgConfidence) || 0), 0) / (stats.length || 1); sum + (parseFloat(item.avgConfidence) || 0), 0) / (stats.length || 1);
return { return ResponseUtil.success({
code: 200, totalAudits,
message: '获取成功', passRate: totalAudits > 0 ? (passCount / totalAudits * 100) : 0,
data: { rejectRate: totalAudits > 0 ? (rejectCount / totalAudits * 100) : 0,
totalAudits, reviewRate: totalAudits > 0 ? (reviewCount / totalAudits * 100) : 0,
passRate: totalAudits > 0 ? (passCount / totalAudits * 100) : 0, averageConfidence: avgConfidence,
rejectRate: totalAudits > 0 ? (rejectCount / totalAudits * 100) : 0, platformStats: stats.map((item: any) => ({
reviewRate: totalAudits > 0 ? (reviewCount / totalAudits * 100) : 0, platform: item.platform,
averageConfidence: avgConfidence, count: parseInt(item.count),
platformStats: stats.map((item: any) => ({ conclusion: item.conclusion,
platform: item.platform, avgConfidence: parseFloat(item.avgConfidence) || 0,
count: parseInt(item.count), })),
conclusion: item.conclusion, }, '获取成功');
avgConfidence: parseFloat(item.avgConfidence) || 0,
})),
},
};
} }
@Get('user-stats') @Get('user-stats')
@@ -186,11 +164,7 @@ export class ContentModerationController {
) { ) {
const stats = await this.unifiedContentService.getUserAuditStats(user.userId, days); const stats = await this.unifiedContentService.getUserAuditStats(user.userId, days);
return { return ResponseUtil.success(stats, '获取成功');
code: 200,
message: '获取成功',
data: stats,
};
} }
@Get('platforms') @Get('platforms')
@@ -198,11 +172,7 @@ export class ContentModerationController {
async getSupportedPlatforms() { async getSupportedPlatforms() {
const platforms = this.unifiedContentService.getSupportedPlatforms(); const platforms = this.unifiedContentService.getSupportedPlatforms();
return { return ResponseUtil.success(platforms, '获取成功');
code: 200,
message: '获取成功',
data: platforms,
};
} }
@Get('check/:taskId') @Get('check/:taskId')
@@ -210,13 +180,9 @@ export class ContentModerationController {
async checkContentApproval(@Param('taskId') taskId: string) { async checkContentApproval(@Param('taskId') taskId: string) {
const isApproved = await this.unifiedContentService.isContentApproved(taskId); const isApproved = await this.unifiedContentService.isContentApproved(taskId);
return { return ResponseUtil.success({
code: 200, taskId,
message: '检查成功', approved: isApproved,
data: { }, '检查成功');
taskId,
approved: isApproved,
},
};
} }
} }

View File

@@ -98,17 +98,14 @@ export class TemplateController {
const template = await this.templateFactory.createTemplate(templateId); const template = await this.templateFactory.createTemplate(templateId);
const result = await template.execute(imageUrl); const result = await template.execute(imageUrl);
return { return ResponseUtil.success({
success: true, templateId,
data: { templateCode: template.code,
templateId, templateName: template.name,
templateCode: template.code, inputUrl: imageUrl,
templateName: template.name, outputUrl: result,
inputUrl: imageUrl, creditCost: template.creditCost,
outputUrl: result, }, '执行成功');
creditCost: template.creditCost,
},
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Template execution failed', error.message || 'Template execution failed',
@@ -328,17 +325,14 @@ export class TemplateController {
imageUrls, imageUrls,
); );
return { return ResponseUtil.success({
success: true, templateId,
data: { totalCount: imageUrls.length,
templateId, results: imageUrls.map((inputUrl, index) => ({
totalCount: imageUrls.length, inputUrl,
results: imageUrls.map((inputUrl, index) => ({ outputUrl: results[index],
inputUrl, })),
outputUrl: results[index], }, '批量执行成功');
})),
},
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Batch execution failed', error.message || 'Batch execution failed',
@@ -399,10 +393,7 @@ export class TemplateController {
async getImageTemplates() { async getImageTemplates() {
try { try {
const templates = await this.templateFactory.getImageTemplates(); const templates = await this.templateFactory.getImageTemplates();
return { return ResponseUtil.success(templates, '获取图片模板列表成功');
success: true,
data: templates,
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Failed to fetch image templates', error.message || 'Failed to fetch image templates',
@@ -424,10 +415,7 @@ export class TemplateController {
async getVideoTemplates() { async getVideoTemplates() {
try { try {
const templates = await this.templateFactory.getVideoTemplates(); const templates = await this.templateFactory.getVideoTemplates();
return { return ResponseUtil.success(templates, '获取视频模板列表成功');
success: true,
data: templates,
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Failed to fetch video templates', error.message || 'Failed to fetch video templates',
@@ -477,13 +465,10 @@ export class TemplateController {
limit, limit,
); );
return { return ResponseUtil.success({
success: true, userTags,
data: { recommendedTemplates: templates,
userTags, }, '模板推荐成功');
recommendedTemplates: templates,
},
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Failed to recommend templates', error.message || 'Failed to recommend templates',
@@ -511,20 +496,17 @@ export class TemplateController {
try { try {
const template = await this.templateFactory.createTemplate(templateId); const template = await this.templateFactory.createTemplate(templateId);
return { return ResponseUtil.success({
success: true, id: templateId,
data: { code: template.code,
id: templateId, name: template.name,
code: template.code, description: template.description,
name: template.name, creditCost: template.creditCost,
description: template.description, version: template.version,
creditCost: template.creditCost, tags: template.tags,
version: template.version, inputExample: template.input,
tags: template.tags, outputExample: template.output,
inputExample: template.input, }, '获取模板详情成功');
outputExample: template.output,
},
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Template not found', error.message || 'Template not found',
@@ -617,26 +599,23 @@ export class TemplateController {
const executions = await queryBuilder.getMany(); const executions = await queryBuilder.getMany();
return { return ResponseUtil.success(executions.map((execution) => ({
success: true, taskId: execution.id,
data: executions.map((execution) => ({ templateId: execution.templateId,
taskId: execution.id, templateName: execution.template?.name,
templateId: execution.templateId, templateCode: execution.template?.code,
templateName: execution.template?.name, type: execution.type,
templateCode: execution.template?.code, status: execution.status,
type: execution.type, progress: execution.progress,
status: execution.status, inputImageUrl: execution.inputImageUrl,
progress: execution.progress, outputUrl: execution.outputUrl,
inputImageUrl: execution.inputImageUrl, thumbnailUrl: execution.thumbnailUrl,
outputUrl: execution.outputUrl, creditCost: execution.creditCost,
thumbnailUrl: execution.thumbnailUrl, startedAt: execution.startedAt,
creditCost: execution.creditCost, completedAt: execution.completedAt,
startedAt: execution.startedAt, executionDuration: execution.executionDuration,
completedAt: execution.completedAt, createdAt: execution.createdAt,
executionDuration: execution.executionDuration, })), '获取用户执行任务列表成功');
createdAt: execution.createdAt,
})),
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Failed to fetch user executions', error.message || 'Failed to fetch user executions',
@@ -685,10 +664,7 @@ export class TemplateController {
const template = this.templateRepository.create(createTemplateDto); const template = this.templateRepository.create(createTemplateDto);
const savedTemplate = await this.templateRepository.save(template); const savedTemplate = await this.templateRepository.save(template);
return { return ResponseUtil.success(savedTemplate, '模板创建成功');
success: true,
data: savedTemplate,
};
} catch (error) { } catch (error) {
if (error instanceof HttpException) { if (error instanceof HttpException) {
throw error; throw error;
@@ -754,10 +730,7 @@ export class TemplateController {
where: { id: templateId }, where: { id: templateId },
}); });
return { return ResponseUtil.success(updatedTemplate, '模板更新成功');
success: true,
data: updatedTemplate,
};
} catch (error) { } catch (error) {
if (error instanceof HttpException) { if (error instanceof HttpException) {
throw error; throw error;
@@ -787,10 +760,7 @@ export class TemplateController {
await this.templateRepository.delete(templateId); await this.templateRepository.delete(templateId);
return { return ResponseUtil.success(null, '模板删除成功');
success: true,
message: 'Template deleted successfully',
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Failed to delete template', error.message || 'Failed to delete template',
@@ -817,10 +787,7 @@ export class TemplateController {
throw new HttpException('Template not found', HttpStatus.NOT_FOUND); throw new HttpException('Template not found', HttpStatus.NOT_FOUND);
} }
return { return ResponseUtil.success(template, '获取模板详情成功');
success: true,
data: template,
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Template not found', error.message || 'Template not found',
@@ -864,18 +831,7 @@ export class TemplateController {
const [templates, total] = await queryBuilder.getManyAndCount(); const [templates, total] = await queryBuilder.getManyAndCount();
return { return ResponseUtil.paginated(templates, total, page, limit, '获取模板列表成功');
success: true,
data: {
templates,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
},
},
};
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
error.message || 'Failed to fetch templates', error.message || 'Failed to fetch templates',

View File

@@ -83,16 +83,12 @@ export class UnifiedUserController {
}, },
}, },
}) })
async register(@Body() registerDto: PlatformLoginDto) { async register(@Body() registerDto: PlatformLoginDto): Promise<ApiResponseType<any>> {
const result = await this.unifiedUserService.register( const result = await this.unifiedUserService.register(
registerDto.platform, registerDto.platform,
registerDto, registerDto,
); );
return { return ResponseUtil.success(result, '注册成功');
code: 200,
message: '注册成功',
data: result,
};
} }
@Get('profile') @Get('profile')
@@ -122,13 +118,9 @@ export class UnifiedUserController {
}, },
}) })
@ApiResponse({ status: 401, description: '未授权访问' }) @ApiResponse({ status: 401, description: '未授权访问' })
async getProfile(@Request() req) { async getProfile(@Request() req): Promise<ApiResponseType<any>> {
const userInfo = await this.unifiedUserService.getUserInfo(req.user.userId); const userInfo = await this.unifiedUserService.getUserInfo(req.user.userId);
return { return ResponseUtil.success(userInfo, '获取成功');
code: 200,
message: '获取成功',
data: userInfo,
};
} }
@Put('profile') @Put('profile')
@@ -149,16 +141,13 @@ export class UnifiedUserController {
}, },
}) })
@ApiResponse({ status: 401, description: '未授权访问' }) @ApiResponse({ status: 401, description: '未授权访问' })
async updateProfile(@Request() req, @Body() updateDto: UserInfoUpdateDto) { async updateProfile(@Request() req, @Body() updateDto: UserInfoUpdateDto): Promise<ApiResponseType<null>> {
await this.unifiedUserService.updateUserInfo( await this.unifiedUserService.updateUserInfo(
req.user.platform, req.user.platform,
req.user.userId, req.user.userId,
updateDto, updateDto,
); );
return { return ResponseUtil.success(null, '更新成功');
code: 200,
message: '更新成功',
};
} }
@Post('bind-platform') @Post('bind-platform')
@@ -180,16 +169,13 @@ export class UnifiedUserController {
}) })
@ApiResponse({ status: 401, description: '未授权访问' }) @ApiResponse({ status: 401, description: '未授权访问' })
@ApiResponse({ status: 409, description: '平台账号已绑定其他用户' }) @ApiResponse({ status: 409, description: '平台账号已绑定其他用户' })
async bindPlatform(@Request() req, @Body() bindDto: PlatformBindDto) { async bindPlatform(@Request() req, @Body() bindDto: PlatformBindDto): Promise<ApiResponseType<null>> {
await this.unifiedUserService.bindPlatform( await this.unifiedUserService.bindPlatform(
req.user.userId, req.user.userId,
bindDto.platform, bindDto.platform,
bindDto, bindDto,
); );
return { return ResponseUtil.success(null, '绑定成功');
code: 200,
message: '绑定成功',
};
} }
@Delete('unbind-platform/:platform') @Delete('unbind-platform/:platform')
@@ -214,12 +200,9 @@ export class UnifiedUserController {
async unbindPlatform( async unbindPlatform(
@Request() req, @Request() req,
@Param('platform') platform: PlatformType, @Param('platform') platform: PlatformType,
) { ): Promise<ApiResponseType<null>> {
await this.unifiedUserService.unbindPlatform(req.user.userId, platform); await this.unifiedUserService.unbindPlatform(req.user.userId, platform);
return { return ResponseUtil.success(null, '解绑成功');
code: 200,
message: '解绑成功',
};
} }
@Get('platforms') @Get('platforms')
@@ -249,12 +232,8 @@ export class UnifiedUserController {
}, },
}, },
}) })
async getSupportedPlatforms() { async getSupportedPlatforms(): Promise<ApiResponseType<any[]>> {
const platforms = this.unifiedUserService.getSupportedPlatforms(); const platforms = this.unifiedUserService.getSupportedPlatforms();
return { return ResponseUtil.success(platforms, '获取成功');
code: 200,
message: '获取成功',
data: platforms,
};
} }
} }