From 3990b5ba37db3ee4938b6623239bd19d49401b58 Mon Sep 17 00:00:00 2001 From: anime Date: Thu, 2 Jan 2025 18:21:14 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=94=AF=E6=8C=81=E6=9B=B4=E5=8A=A0?= =?UTF-8?q?=E7=AE=80=E5=8D=95=E7=9A=84=E7=9A=84=E7=BC=93=E5=AD=98=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=AF=BB=E5=8F=96=E5=92=8C=E5=86=99=E5=85=A5=E6=96=B9?= =?UTF-8?q?=E5=BC=8F):=20=E5=B0=9D=E8=AF=95=E4=BB=8E=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E4=B8=AD=E8=8E=B7=E5=8F=96=E6=95=B0=E6=8D=AE=EF=BC=8C=E5=A6=82?= =?UTF-8?q?=E6=9E=9C=E6=B2=A1=E6=9C=89=E5=88=99=E5=B0=9D=E8=AF=95=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=95=B0=E6=8D=AE=E5=B9=B6=E5=86=99=E5=85=A5=E7=BC=93?= =?UTF-8?q?=E5=AD=98=EF=BC=8C=E6=9C=80=E7=BB=88=E8=BF=94=E5=9B=9E=E6=89=80?= =?UTF-8?q?=E9=9C=80=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/cache/cache_manager.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lib/cache/cache_manager.js b/lib/cache/cache_manager.js index f35a1fe1..88dfb8a4 100644 --- a/lib/cache/cache_manager.js +++ b/lib/cache/cache_manager.js @@ -2,6 +2,40 @@ import BLOG from '@/blog.config' import FileCache from './local_file_cache' import MemoryCache from './memory_cache' +/** + * 尝试从缓存中获取数据,如果没有则尝试获取数据并写入缓存,最终返回所需数据 + * @param key + * @param getDataFunction + * @param getDataArgs + * @returns {Promise<*|null>} + */ +export async function getOrSetDataWithCache(key, getDataFunction, ...getDataArgs) { + return getOrSetDataWithCustomCache(key, null, getDataFunction, ...getDataArgs) +} + + +/** + * 尝试从缓存中获取数据,如果没有则尝试获取数据并自定义写入缓存,最终返回所需数据 + * @param key + * @param customCacheTime + * @param getDataFunction + * @param getDataArgs + * @returns {Promise<*|null>} + */ +export async function getOrSetDataWithCustomCache(key, customCacheTime, getDataFunction, ...getDataArgs) { + const dataFromCache = await getDataFromCache(key) + if (dataFromCache) { + console.log('[缓存-->>API]:', key) + return dataFromCache + } + const data = await getDataFunction(...getDataArgs) + if (data) { + console.log('[API-->>缓存]:', key) + await setDataToCache(key, data, customCacheTime) + } + return data || null +} + /** * 为减少频繁接口请求,notion数据将被缓存 * @param {*} key