From 2664f774b9f26426e9148ba76a035f5422177903 Mon Sep 17 00:00:00 2001 From: sumanvpacewisdom Date: Mon, 23 Mar 2026 22:25:20 +0530 Subject: [PATCH] Refactor cache handling in various services to improve clarity and efficiency. Updated cache set and delete methods in cacheHelper for session and user data. Simplified cache invalidation logic in EntityHelper and NotificationTemplateHelper by capturing old values before updates. Removed redundant cache invalidation after entity operations to streamline processing. --- src/generics/cacheHelper.js | 4 +- src/services/entity-type.js | 17 ++++---- src/services/entity.js | 82 +++--------------------------------- src/services/notification.js | 19 +++++---- 4 files changed, 29 insertions(+), 93 deletions(-) diff --git a/src/generics/cacheHelper.js b/src/generics/cacheHelper.js index 4a462037c..d31f97a84 100644 --- a/src/generics/cacheHelper.js +++ b/src/generics/cacheHelper.js @@ -484,7 +484,7 @@ const sessions = { if (sessionDetails) { // Cache the session data directly - await this.set(tenantCode, organizationCode, sessionId, sessionDetails) + await this.set(tenantCode, sessionId, sessionDetails) dbFetchedSessions.push(sessionDetails) console.log(`✅ [getSessionKafka] Session ${sessionId} fetched and cached`) } @@ -1322,7 +1322,7 @@ const mentee = { if (usersFromDb && usersFromDb.length > 0) { // Cache each fetched user individually for (const user of usersFromDb) { - await this.set(tenantCode, organizationCode, user.user_id, user) + await this.set(tenantCode, user.user_id, user) } // Add fetched users to result diff --git a/src/services/entity-type.js b/src/services/entity-type.js index eb1b85260..756d6644a 100644 --- a/src/services/entity-type.js +++ b/src/services/entity-type.js @@ -289,11 +289,12 @@ module.exports = class EntityHelper { } // Clear cache for affected models before deletion - await this._clearUserCachesForEntityTypeChange(organizationCode, tenantCode, { - id: entityToDelete.id, - value: entityToDelete.value, - modelNames: entityToDelete.model_names, - }) + await this._clearUserCachesForEntityTypeChange( + organizationCode, + tenantCode, + entityToDelete.model_names ? entityToDelete.model_names[0] : null, + entityToDelete.value + ) // SECOND: Delete from database const deleteCount = await entityTypeQueries.deleteOneEntityType(id, organizationCode, tenantCode) @@ -544,13 +545,13 @@ module.exports = class EntityHelper { }) ) - // 2. Clear entity type caches for unified model strategy + // 2. Clear entity type cache for the specific model + value if (modelName) { clearPromises.push( cacheHelper.entityTypes - .delete(tenantCode, organizationCode, `model:${modelName}:__ALL__`) + .delete(tenantCode, organizationCode, modelName, entityValue) .catch((error) => { - /* Failed to clear unified entity type cache - continue operation */ + /* Failed to clear entity type cache - continue operation */ }) ) } diff --git a/src/services/entity.js b/src/services/entity.js index 6b6d7a416..3dd55a118 100644 --- a/src/services/entity.js +++ b/src/services/entity.js @@ -50,27 +50,6 @@ module.exports = class EntityHelper { } } - // Invalidate entity list caches after creation - if (entity && sanitizedData.entity_type_id) { - // Separate try-catch for each cache deletion to ensure all caches are cleared - try { - await cacheHelper.forms.delete( - tenantCode, - common.SYSTEM, - 'entity_list', - sanitizedData.entity_type_id - ) - } catch (cacheError) { - console.error(`❌ Failed to invalidate entity_list cache after creation:`, cacheError) - } - - try { - await cacheHelper.forms.delete(tenantCode, common.SYSTEM, 'entity_list_all', 'all_entities') - } catch (cacheError) { - console.error(`❌ Failed to invalidate entity_list_all cache after creation:`, cacheError) - } - } - return responses.successResponse({ statusCode: httpStatusCode.created, message: 'ENTITY_CREATED_SUCCESSFULLY', @@ -163,23 +142,6 @@ module.exports = class EntityHelper { } } - // Invalidate entity list caches after update - if (updatedEntity && (updatedEntity.entity_type_id || sanitizedData.entity_type_id)) { - const entityTypeId = updatedEntity.entity_type_id || sanitizedData.entity_type_id - // Separate try-catch for each cache deletion to ensure all caches are cleared - try { - await cacheHelper.forms.delete(tenantCode, common.SYSTEM, 'entity_list', entityTypeId) - } catch (cacheError) { - console.error(`❌ Failed to invalidate entity_list cache after update:`, cacheError) - } - - try { - await cacheHelper.forms.delete(tenantCode, common.SYSTEM, 'entity_list_all', 'all_entities') - } catch (cacheError) { - console.error(`❌ Failed to invalidate entity_list_all cache after update:`, cacheError) - } - } - return responses.successResponse({ statusCode: httpStatusCode.accepted, message: 'ENTITY_UPDATED_SUCCESSFULLY', @@ -387,14 +349,6 @@ module.exports = class EntityHelper { } } - // Invalidate entity list caches after deletion - try { - // Clear all entity list caches since we don't know the entity_type_id after deletion - await cacheHelper.forms.delete(tenantCode, common.SYSTEM, 'entity_list_all', 'all_entities') - } catch (cacheError) { - console.error(`❌ Failed to invalidate entity list cache after deletion:`, cacheError) - } - return responses.successResponse({ statusCode: httpStatusCode.accepted, message: 'ENTITY_DELETED_SUCCESSFULLY', @@ -441,35 +395,13 @@ module.exports = class EntityHelper { filter['entity_type_id'] = entityType } - // Try to get entities from cache first (only cache paginated lists without search) - const cacheKey = `${entityType || 'all'}_page${pageNo}_limit${pageSize}` - let entities = null - - if (!searchText) { - entities = await cacheHelper.forms.get(tenantCode, common.SYSTEM, 'entity_list', cacheKey) - if (entities) { - } - } - - if (!entities) { - // Optimized: Get entities with entity_type details included - eliminates N+1 queries for clients - entities = await entityQueries.getAllEntitiesWithEntityTypeDetails( - filter, - [tenantCode], - pageNo, - pageSize, - searchText - ) - - // Cache the result if no search text (searchable results shouldn't be cached) - if (!searchText && entities) { - try { - await cacheHelper.forms.set(tenantCode, common.SYSTEM, 'entity_list', cacheKey, entities) - } catch (cacheError) { - console.error(`❌ Failed to cache entity list:`, cacheError) - } - } - } + const entities = await entityQueries.getAllEntitiesWithEntityTypeDetails( + filter, + [tenantCode], + pageNo, + pageSize, + searchText + ) if (entities.rows == 0 || entities.count == 0) { return responses.failureResponse({ diff --git a/src/services/notification.js b/src/services/notification.js index 916db26bb..f4f0232ef 100644 --- a/src/services/notification.js +++ b/src/services/notification.js @@ -76,6 +76,11 @@ module.exports = class NotificationTemplateHelper { bodyData['organization_code'] = tokenInformation.organization_code bodyData['updated_by'] = tokenInformation.id + // Fetch original template BEFORE update to capture old code for cache invalidation + const existingTemplates = await notificationTemplateQueries.findTemplatesByFilter(filter) + const existingTemplate = existingTemplates?.[0] + const oldCode = existingTemplate?.code || filter.code + const result = await notificationTemplateQueries.updateTemplate(filter, bodyData, tenantCode) if (result == 0) { return responses.failureResponse({ @@ -85,23 +90,21 @@ module.exports = class NotificationTemplateHelper { }) } - // Delete old cache - const existingTemplates = await notificationTemplateQueries.findTemplatesByFilter(filter) - const existingTemplate = existingTemplates?.[0] - const templateCode = bodyData.code || existingTemplate?.code || filter.code + // Delete cache using old code (captured before update) and new code (if changed) + const newCode = bodyData.code || oldCode try { - if (templateCode) { + if (oldCode) { await cacheHelper.notificationTemplates.delete( tenantCode, tokenInformation.organization_code, - templateCode + oldCode ) } - if (existingTemplate?.code && existingTemplate.code !== templateCode) { + if (newCode && newCode !== oldCode) { await cacheHelper.notificationTemplates.delete( tenantCode, tokenInformation.organization_code, - existingTemplate.code + newCode ) } } catch (cacheError) {