新增文案接口

This commit is contained in:
Jerry 2025-05-20 13:57:36 +08:00
parent 4e5daae3b8
commit cdbe05be1a
3 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,36 @@
import express from 'express';
import WordsService from './words.service';
import response from '../../utils/core/response';
class WordsController {
private readonly router: express.Router;
constructor() {
this.router = express.Router();
this.init();
}
public getRouter(): express.Router {
return this.router;
}
private init(): void {
this.router.get('/getText/:id', this.getText);
}
private getText = async (req: express.Request, res: express.Response): Promise<void> => {
try {
const id = req.params.id;
const texts = await WordsService.loadWordById(id);
if (!texts || texts.length === 0) {
return await response.error(res, `文案${id}不存在或为空..`, 404);
}
const randomIndex = Math.floor(Math.random() * texts.length);
const result = texts[randomIndex];
await response.success(res, result);
} catch (e) {
await response.error(res);
}
};
}
export default new WordsController();

View File

@ -0,0 +1,27 @@
import path from 'path';
import paths from '../../utils/core/path';
import fs from 'fs/promises';
import logger from '../../utils/core/logger';
class WordsService {
private wordCache: Record<string, string[]> = {};
public async loadWordById(id: string): Promise<string[] | null> {
if (this.wordCache[id]) return this.wordCache[id];
const filePath = path.join(paths.get('words'), `${id}.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;
return texts;
} else {
return null;
}
} catch (error) {
logger.error(`Failed to loadWordById: ${id}`);
return null;
}
}
}
export default new WordsService();

View File

@ -38,6 +38,7 @@ class PathManager {
package: path.join(this.baseDir, 'package.json'), package: path.join(this.baseDir, 'package.json'),
modules: path.join(this.baseDir, 'src/modules'), modules: path.join(this.baseDir, 'src/modules'),
uploads: path.join(this.baseDir, 'public/files/uploads'), uploads: path.join(this.baseDir, 'public/files/uploads'),
words: path.join(this.baseDir, 'private/data/word'),
}; };
return type ? mappings[type] : this.baseDir; return type ? mappings[type] : this.baseDir;
@ -67,6 +68,7 @@ class PathManager {
this.get('media'), this.get('media'),
this.get('temp'), this.get('temp'),
this.get('uploads'), this.get('uploads'),
this.get('words'),
]; ];
pathsToInit.forEach((dirPath) => { pathsToInit.forEach((dirPath) => {
@ -89,6 +91,7 @@ type PathType =
| 'package' | 'package'
| 'media' | 'media'
| 'modules' | 'modules'
| 'words'
| 'uploads'; | 'uploads';
const paths = PathManager.getInstance(); const paths = PathManager.getInstance();