Fix history cache when there is cacheConfig (#12788)

This commit is contained in:
J. Nick Koston 2022-05-25 15:39:55 -10:00 committed by GitHub
parent b0e6c41238
commit d0ead1fdb8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -34,7 +34,7 @@ const RECENT_THRESHOLD = 60000; // 1 minute
const RECENT_CACHE: { [cacheKey: string]: RecentCacheResults } = {}; const RECENT_CACHE: { [cacheKey: string]: RecentCacheResults } = {};
const stateHistoryCache: { [cacheKey: string]: CachedResults } = {}; const stateHistoryCache: { [cacheKey: string]: CachedResults } = {};
// Cached type 1 unction. Without cache config. // Cached type 1 function. Without cache config.
export const getRecent = ( export const getRecent = (
hass: HomeAssistant, hass: HomeAssistant,
entityId: string, entityId: string,
@ -103,13 +103,14 @@ export const getRecentWithCache = (
language: string language: string
) => { ) => {
const cacheKey = cacheConfig.cacheKey; const cacheKey = cacheConfig.cacheKey;
const fullCacheKey = cacheKey + `_${cacheConfig.hoursToShow}`;
const endTime = new Date(); const endTime = new Date();
const startTime = new Date(endTime); const startTime = new Date(endTime);
startTime.setHours(startTime.getHours() - cacheConfig.hoursToShow); startTime.setHours(startTime.getHours() - cacheConfig.hoursToShow);
let toFetchStartTime = startTime; let toFetchStartTime = startTime;
let appendingToCache = false; let appendingToCache = false;
let cache = stateHistoryCache[cacheKey + `_${cacheConfig.hoursToShow}`]; let cache = stateHistoryCache[fullCacheKey];
if ( if (
cache && cache &&
toFetchStartTime >= cache.startTime && toFetchStartTime >= cache.startTime &&
@ -123,7 +124,7 @@ export const getRecentWithCache = (
return cache.prom; return cache.prom;
} }
} else { } else {
cache = stateHistoryCache[cacheKey] = getEmptyCache( cache = stateHistoryCache[fullCacheKey] = getEmptyCache(
language, language,
startTime, startTime,
endTime endTime
@ -152,7 +153,7 @@ export const getRecentWithCache = (
]); ]);
fetchedHistory = results[1]; fetchedHistory = results[1];
} catch (err: any) { } catch (err: any) {
delete stateHistoryCache[cacheKey]; delete stateHistoryCache[fullCacheKey];
throw err; throw err;
} }
const stateHistory = computeHistory(hass, fetchedHistory, localize); const stateHistory = computeHistory(hass, fetchedHistory, localize);