From 9d1b563d485676bf0e0ef6780fee257d32536c39 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Fri, 15 Dec 2023 22:11:48 +0200 Subject: [PATCH] Add cache for parsed characters --- src/endpoints/characters.js | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/endpoints/characters.js b/src/endpoints/characters.js index f21c29a5f..367fbdf82 100644 --- a/src/endpoints/characters.js +++ b/src/endpoints/characters.js @@ -22,8 +22,25 @@ const { importRisuSprites } = require('./sprites'); let characters = {}; +// KV-store for parsed character data +const characterDataCache = new Map(); + +/** + * Reads the character card from the specified image file. + * @param {string} img_url - Path to the image file + * @param {string} input_format - 'png' + * @returns {Promise} - Character card data + */ async function charaRead(img_url, input_format) { - return characterCardParser.parse(img_url, input_format); + const stat = fs.statSync(img_url); + const cacheKey = `${img_url}-${stat.mtimeMs}`; + if (characterDataCache.has(cacheKey)) { + return characterDataCache.get(cacheKey); + } + + const result = characterCardParser.parse(img_url, input_format); + characterDataCache.set(cacheKey, result); + return result; } /** @@ -32,6 +49,12 @@ async function charaRead(img_url, input_format) { */ async function charaWrite(img_url, data, target_img, response = undefined, mes = 'ok', crop = undefined) { try { + // Reset the cache + for (const key of characterDataCache.keys()) { + if (key.startsWith(img_url)) { + characterDataCache.delete(key); + } + } // Read the image, resize, and save it as a PNG into the buffer const image = await tryReadImage(img_url, crop);