feat:添加文案查询功能

This commit is contained in:
Jerry 2025-10-13 17:12:19 +08:00
parent 426fb886ae
commit 2d3d11be88
2 changed files with 54 additions and 2 deletions

View File

@ -89,4 +89,31 @@ export class WordsController {
throw new HttpException('服务器错误', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post('list')
@ApiOperation({ summary: '获取指定类型下的所有文案名称' })
@ApiBody({
schema: {
type: 'object',
properties: {
type: { type: 'string', example: 'poke' },
},
required: ['type'],
},
})
public async listWords(@Body('type') type: string) {
try {
const names = await this.wordsService.listWordNames(type);
if (names.length === 0) {
throw new HttpException(
`类型 ${type} 下没有可用文案或目录不存在..`,
HttpStatus.NOT_FOUND,
);
}
return names;
} catch (e) {
this.logger.error(`listWords 失败: ${e}`);
throw new HttpException('服务器错误', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -59,7 +59,9 @@ export class WordsService {
}
/**
*
*
* @param type
* @param name
*/
public async loadWord(type: string, name: string): Promise<string[] | null> {
const safeType = this.safePathSegment(type);
@ -91,7 +93,9 @@ export class WordsService {
}
/**
*
*
* @param type
* @param name
*/
public async reloadWord(type: string, name: string): Promise<boolean> {
const safeType = this.safePathSegment(type);
@ -119,6 +123,27 @@ export class WordsService {
}
}
/**
*
* @param type
*/
public async listWordNames(type: string): Promise<string[]> {
const safeType = this.safePathSegment(type);
const dirPath = path.join(this.paths.get('words'), safeType);
try {
const files = await fs.readdir(dirPath, { withFileTypes: true });
const names = files
.filter((f) => f.isFile() && f.name.endsWith('.json'))
.map((f) => f.name.replace(/\.json$/, ''));
this.logger.log(`扫描文案类型 ${safeType} 下的文件: ${names.join(', ')}`);
return names;
} catch (e) {
this.logger.error(`读取文案目录失败: ${safeType}`, e);
return [];
}
}
private safePathSegment(segment: string): string {
// 将不安全字符转义为安全文件名形式
return segment.replace(/[\\\/:*?"<>|]/g, '_');