delete count cache after bulk action or empty trash

This commit is contained in:
Hongbo Wu 2024-08-14 12:59:52 +08:00
parent 4fcf025611
commit 4bf3e4ba0f
2 changed files with 22 additions and 3 deletions

View file

@ -79,6 +79,7 @@ import {
batchUpdateLibraryItems, batchUpdateLibraryItems,
countLibraryItems, countLibraryItems,
createOrUpdateLibraryItem, createOrUpdateLibraryItem,
deleteCachedTotalCount,
findLibraryItemsByPrefix, findLibraryItemsByPrefix,
SearchArgs, SearchArgs,
searchLibraryItems, searchLibraryItems,
@ -771,6 +772,8 @@ export const bulkActionResolver = authorized<
// if there are less than batchSize items, update them synchronously // if there are less than batchSize items, update them synchronously
await batchUpdateLibraryItems(action, searchArgs, uid, labelIds, args) await batchUpdateLibraryItems(action, searchArgs, uid, labelIds, args)
await deleteCachedTotalCount(uid)
return { success: true } return { success: true }
} }
@ -790,6 +793,8 @@ export const bulkActionResolver = authorized<
return { errorCodes: [BulkActionErrorCode.BadRequest] } return { errorCodes: [BulkActionErrorCode.BadRequest] }
} }
await deleteCachedTotalCount(uid)
return { success: true } return { success: true }
} catch (error) { } catch (error) {
log.error('bulkActionResolver error', error) log.error('bulkActionResolver error', error)
@ -986,6 +991,8 @@ export const emptyTrashResolver = authorized<
state: LibraryItemState.Deleted, state: LibraryItemState.Deleted,
}) })
await deleteCachedTotalCount(uid)
return { return {
success: true, success: true,
} }

View file

@ -1717,9 +1717,10 @@ export const filterItemEvents = (
} }
const totalCountCacheKey = (userId: string, args: SearchArgs) => { const totalCountCacheKey = (userId: string, args: SearchArgs) => {
return `cache:library_items_count:${userId}:${stringToHash( // sort the args to make sure the cache key is consistent
JSON.stringify(args) const sortedArgs = JSON.stringify(args, Object.keys(args).sort())
)}`
return `cache:library_items_count:${userId}:${stringToHash(sortedArgs)}`
} }
export const getCachedTotalCount = async (userId: string, args: SearchArgs) => { export const getCachedTotalCount = async (userId: string, args: SearchArgs) => {
@ -1740,3 +1741,14 @@ export const setCachedTotalCount = async (
const cacheKey = totalCountCacheKey(userId, args) const cacheKey = totalCountCacheKey(userId, args)
await redisDataSource.redisClient?.set(cacheKey, count, 'EX', 600) await redisDataSource.redisClient?.set(cacheKey, count, 'EX', 600)
} }
export const deleteCachedTotalCount = async (userId: string) => {
const keyPattern = `cache:library_items_count:${userId}:*`
const keys = await redisDataSource.redisClient?.keys(keyPattern)
if (!keys || keys.length === 0) {
return
}
console.log('Deleting keys:', keys)
await redisDataSource.redisClient?.del(keys)
}