diff --git a/src/modules/words/words.controller.ts b/src/modules/words/words.controller.ts new file mode 100644 index 0000000..9cb0cef --- /dev/null +++ b/src/modules/words/words.controller.ts @@ -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 => { + 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(); diff --git a/src/modules/words/words.service.ts b/src/modules/words/words.service.ts new file mode 100644 index 0000000..65cb9bd --- /dev/null +++ b/src/modules/words/words.service.ts @@ -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 = {}; + public async loadWordById(id: string): Promise { + 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(); diff --git a/src/utils/core/path.ts b/src/utils/core/path.ts index 84238b8..c3b683f 100644 --- a/src/utils/core/path.ts +++ b/src/utils/core/path.ts @@ -38,6 +38,7 @@ class PathManager { package: path.join(this.baseDir, 'package.json'), modules: path.join(this.baseDir, 'src/modules'), uploads: path.join(this.baseDir, 'public/files/uploads'), + words: path.join(this.baseDir, 'private/data/word'), }; return type ? mappings[type] : this.baseDir; @@ -67,6 +68,7 @@ class PathManager { this.get('media'), this.get('temp'), this.get('uploads'), + this.get('words'), ]; pathsToInit.forEach((dirPath) => { @@ -89,6 +91,7 @@ type PathType = | 'package' | 'media' | 'modules' + | 'words' | 'uploads'; const paths = PathManager.getInstance();