diff --git a/.changeset/great-ties-join.md b/.changeset/great-ties-join.md new file mode 100644 index 0000000000..52b1e9410e --- /dev/null +++ b/.changeset/great-ties-join.md @@ -0,0 +1,5 @@ +--- +"@scow/mis-server": patch +--- + +平台数据统计缓存函数设置缓存时间变量,并默认为 5 分钟 diff --git a/apps/mis-server/src/entities/QueryCache.ts b/apps/mis-server/src/entities/QueryCache.ts index 24aab7f44f..17d4800404 100644 --- a/apps/mis-server/src/entities/QueryCache.ts +++ b/apps/mis-server/src/entities/QueryCache.ts @@ -38,6 +38,6 @@ export class QueryCache { } this.queryKey = init.queryKey; this.queryResult = init.queryResult; - this.timestamp = new Date(); + this.timestamp = init.timestamp ?? new Date(); } } diff --git a/apps/mis-server/src/utils/cache.ts b/apps/mis-server/src/utils/cache.ts index 1a94077e33..1e4f861655 100644 --- a/apps/mis-server/src/utils/cache.ts +++ b/apps/mis-server/src/utils/cache.ts @@ -13,21 +13,38 @@ import { MySqlDriver, QueryBuilder, SqlEntityManager } from "@mikro-orm/mysql"; import { QueryCache } from "src/entities/QueryCache"; -export const queryWithCache = async ({ em, queryKeys, queryQb }: { +export const queryWithCache = async ({ em, queryKeys, queryQb, cacheOptions }: { em: SqlEntityManager queryKeys: string[], queryQb: QueryBuilder, + cacheOptions?: { + maxAgeMilliseconds?: number, + enabled?: boolean, + }, }) => { + const { maxAgeMilliseconds = 5 * 60 * 1000, enabled = true } = cacheOptions || {}; + + if (!enabled) { + return await queryQb.execute(); + } const queryKey = queryKeys.join(":"); - const queryCache = await em.findOne(QueryCache, { - queryKey, - }); + const queryCache = await em.findOne(QueryCache, { queryKey }); + + const now = new Date(); if (!queryCache) { const newResult = await queryQb.execute(); - const queryCache = new QueryCache({ queryKey, queryResult: newResult }); + const newQueryCache = new QueryCache({ queryKey, queryResult: newResult, timestamp: now }); + await em.persistAndFlush(newQueryCache); + return newResult; + } + + if ((now.getTime() - queryCache.timestamp.getTime()) > maxAgeMilliseconds) { + const newResult = await queryQb.execute(); + queryCache.queryResult = newResult; + queryCache.timestamp = now; await em.persistAndFlush(queryCache); return newResult; } else {