mirror of
https://github.com/crystelf/crystelf-core.git
synced 2025-12-05 10:31:56 +00:00
优化文案模块
This commit is contained in:
parent
aad87d4d7e
commit
1c793c3b20
@ -1,5 +1,5 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import fs from 'fs/promises';
|
||||
import * as fs from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { PathService } from '../../core/path/path.service';
|
||||
import { SystemService } from 'src/core/system/system.service';
|
||||
|
||||
@ -1,28 +1,27 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
Inject,
|
||||
UseGuards,
|
||||
Body,
|
||||
} from '@nestjs/common';
|
||||
import { WordsService } from './words.service';
|
||||
import { TokenAuthGuard } from '../../core/tools/token-auth.guard';
|
||||
import { ApiBody, ApiOperation, ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
class WordsDto {
|
||||
@ApiProperty({
|
||||
description: '文案id',
|
||||
example: 'poke',
|
||||
})
|
||||
@ApiProperty({ description: '文案类型', example: 'poke' })
|
||||
type: string;
|
||||
|
||||
@ApiProperty({ description: '文案名称', example: 'poke' })
|
||||
id: string;
|
||||
@ApiProperty({
|
||||
description: '密钥',
|
||||
example: '1111',
|
||||
})
|
||||
}
|
||||
|
||||
class WordsReloadDto extends WordsDto {
|
||||
@ApiProperty({ description: '密钥', example: '1111' })
|
||||
token: string;
|
||||
}
|
||||
|
||||
@ -37,16 +36,15 @@ export class WordsController {
|
||||
/**
|
||||
* 获取随机文案
|
||||
*/
|
||||
@Get('getText/:id')
|
||||
@ApiOperation({
|
||||
summary: '获取随机文案',
|
||||
})
|
||||
async getText(@Param('id') id: string) {
|
||||
@Post('getText')
|
||||
@ApiOperation({ summary: '获取随机文案' })
|
||||
@ApiBody({ type: WordsDto })
|
||||
async getText(@Body() dto: WordsDto) {
|
||||
try {
|
||||
const texts = await this.wordsService.loadWordById(id);
|
||||
const texts = await this.wordsService.loadWord(dto.type, dto.id);
|
||||
if (!texts || texts.length === 0) {
|
||||
throw new HttpException(
|
||||
`文案 ${id} 不存在或为空..`,
|
||||
`文案 ${dto.type}/${dto.id} 不存在或为空..`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
@ -61,15 +59,13 @@ export class WordsController {
|
||||
/**
|
||||
* 重载文案
|
||||
*/
|
||||
@Post('reloadText/:id')
|
||||
@ApiOperation({
|
||||
summary: '重载某条文案',
|
||||
})
|
||||
@Post('reloadText')
|
||||
@ApiOperation({ summary: '重载某条文案' })
|
||||
@UseGuards(TokenAuthGuard)
|
||||
@ApiBody({ type: WordsDto })
|
||||
async reloadWord(@Param('id') id: string, @Param('token') token: string) {
|
||||
@ApiBody({ type: WordsReloadDto })
|
||||
async reloadWord(@Body() dto: WordsReloadDto) {
|
||||
try {
|
||||
const success = await this.wordsService.reloadWord(id);
|
||||
const success = await this.wordsService.reloadWord(dto.type, dto.id);
|
||||
if (success) {
|
||||
return '成功重载..';
|
||||
} else {
|
||||
|
||||
@ -8,7 +8,8 @@ import { AutoUpdateService } from '../../core/auto-update/auto-update.service';
|
||||
export class WordsService {
|
||||
private readonly logger = new Logger(WordsService.name);
|
||||
private wordCache: Record<string, string[]> = {};
|
||||
private readonly clearIntervalMs = 30 * 60 * 1000; // 30min
|
||||
private readonly clearIntervalMs = 240 * 60 * 1000; // 240min
|
||||
private readonly updateMs = 15 * 60 * 1000; // 15min
|
||||
|
||||
@Inject(PathService)
|
||||
private readonly paths: PathService;
|
||||
@ -21,9 +22,6 @@ export class WordsService {
|
||||
this.startAutoUpdate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定时清理缓存
|
||||
*/
|
||||
private startAutoClear() {
|
||||
setInterval(() => {
|
||||
this.logger.log('清理文案缓存..');
|
||||
@ -31,9 +29,6 @@ export class WordsService {
|
||||
}, this.clearIntervalMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定时检查 words 仓库更新
|
||||
*/
|
||||
private startAutoUpdate() {
|
||||
setInterval(async () => {
|
||||
const wordsPath = this.paths.get('words');
|
||||
@ -42,52 +37,56 @@ export class WordsService {
|
||||
wordsPath,
|
||||
'words 仓库',
|
||||
);
|
||||
|
||||
if (updated) {
|
||||
this.logger.log('文案仓库已更新,清理缓存..');
|
||||
this.wordCache = {};
|
||||
}
|
||||
}, this.clearIntervalMs);
|
||||
}, this.updateMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从本地加载文案到内存
|
||||
*/
|
||||
async loadWordById(id: string): Promise<string[] | null> {
|
||||
this.logger.log(`加载文案 ${id}..`);
|
||||
if (this.wordCache[id]) return this.wordCache[id];
|
||||
const filePath = path.join(this.paths.get('words'), `${id}.json`);
|
||||
async loadWord(type: string, name: string): Promise<string[] | null> {
|
||||
const cacheKey = `${type}/${name}`;
|
||||
this.logger.log(`加载文案 ${cacheKey}..`);
|
||||
if (this.wordCache[cacheKey]) return this.wordCache[cacheKey];
|
||||
|
||||
const filePath = path.join(this.paths.get('words'), type, `${name}.json`);
|
||||
try {
|
||||
const content = await fs.readFile(filePath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
if (Array.isArray(parsed)) {
|
||||
const texts = parsed.filter((item) => typeof item === 'string');
|
||||
this.wordCache[id] = texts;
|
||||
this.wordCache[cacheKey] = texts;
|
||||
return texts;
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
this.logger.error(`加载文案失败: ${id}..`, e);
|
||||
this.logger.error(`加载文案失败: ${cacheKey}`, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载 json 到内存
|
||||
* 重载文案
|
||||
*/
|
||||
async reloadWord(id: string): Promise<boolean> {
|
||||
this.logger.log(`重载文案: ${id}..`);
|
||||
const filePath = path.join(this.paths.get('words'), `${id}.json`);
|
||||
async reloadWord(type: string, name: string): Promise<boolean> {
|
||||
const cacheKey = `${type}/${name}`;
|
||||
this.logger.log(`重载文案: ${cacheKey}..`);
|
||||
const filePath = path.join(this.paths.get('words'), type, `${name}.json`);
|
||||
try {
|
||||
const content = await fs.readFile(filePath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
if (Array.isArray(parsed)) {
|
||||
this.wordCache[id] = parsed.filter((item) => typeof item === 'string');
|
||||
this.wordCache[cacheKey] = parsed.filter(
|
||||
(item) => typeof item === 'string',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (e) {
|
||||
this.logger.error(`重载文案失败: ${id}`, e);
|
||||
this.logger.error(`重载文案失败: ${cacheKey}`, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user