Miao-Yunzai/src/utils/renderer/Renderer.ts

93 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-09-15 08:15:25 +08:00
import template from 'art-template'
import chokidar from 'chokidar'
import path from 'node:path'
import fs from 'node:fs'
2023-09-15 08:15:25 +08:00
export default class Renderer {
2024-06-13 21:01:16 +08:00
id = null
type = null
render = null
dir = './temp/html'
html = {}
watcher = {}
2023-09-15 08:15:25 +08:00
/**
*
* @param data.id ID
* @param data.type
* @param data.render
*/
constructor(data) {
/** 渲染器ID */
this.id = data.id || 'renderer'
/** 渲染器类型 */
this.type = data.type || 'image'
/** 渲染器入口 */
this.render = this[data.render || 'render']
this.createDir(this.dir)
}
2024-06-13 21:01:16 +08:00
/**
*
* @param dirname
* @returns
*/
2023-09-15 08:15:25 +08:00
createDir(dirname) {
if (fs.existsSync(dirname)) {
return true
} else {
if (this.createDir(path.dirname(dirname))) {
fs.mkdirSync(dirname)
return true
}
}
2023-09-15 08:15:25 +08:00
}
2024-06-13 21:01:16 +08:00
/**
*
* @param name
* @param data
* @returns
*/
2023-09-15 08:15:25 +08:00
dealTpl(name, data) {
let { tplFile, saveId = name } = data
let savePath = `./temp/html/${name}/${saveId}.html`
/** 读取html模板 */
if (!this.html[tplFile]) {
this.createDir(`./temp/html/${name}`)
try {
this.html[tplFile] = fs.readFileSync(tplFile, 'utf8')
} catch (error) {
logger.error(`加载html错误${tplFile}`)
return false
}
this.watch(tplFile)
}
2023-09-15 08:15:25 +08:00
data.resPath = `./resources/`
/** 替换模板 */
let tmpHtml = template.render(this.html[tplFile], data)
/** 保存模板 */
fs.writeFileSync(savePath, tmpHtml)
logger.debug(`[图片生成][使用模板] ${savePath}`)
return savePath
}
2024-06-13 21:01:16 +08:00
/**
*
* @param tplFile
* @returns
*/
2023-09-15 08:15:25 +08:00
watch(tplFile) {
if (this.watcher[tplFile]) return
const watcher = chokidar.watch(tplFile)
2024-06-13 21:01:16 +08:00
watcher.on('change', () => {
2023-09-15 08:15:25 +08:00
delete this.html[tplFile]
logger.mark(`[修改html模板] ${tplFile}`)
})
this.watcher[tplFile] = watcher
}
2024-06-13 21:01:16 +08:00
}