refactor(search): optimize cache clearing logic to only trigger on searchable field changes

This commit is contained in:
Andras Bacsai
2025-09-19 10:22:31 +02:00
parent 575793709b
commit f223623603

View File

@@ -8,16 +8,18 @@ trait ClearsGlobalSearchCache
{ {
protected static function bootClearsGlobalSearchCache() protected static function bootClearsGlobalSearchCache()
{ {
static::saved(function ($model) { static::saving(function ($model) {
// Clear search cache when model is saved // Only clear cache if searchable fields are being changed
$teamId = $model->getTeamIdForCache(); if ($model->hasSearchableChanges()) {
if (filled($teamId)) { $teamId = $model->getTeamIdForCache();
GlobalSearch::clearTeamCache($teamId); if (filled($teamId)) {
GlobalSearch::clearTeamCache($teamId);
}
} }
}); });
static::created(function ($model) { static::created(function ($model) {
// Clear search cache when model is created // Always clear cache when model is created
$teamId = $model->getTeamIdForCache(); $teamId = $model->getTeamIdForCache();
if (filled($teamId)) { if (filled($teamId)) {
GlobalSearch::clearTeamCache($teamId); GlobalSearch::clearTeamCache($teamId);
@@ -25,7 +27,7 @@ trait ClearsGlobalSearchCache
}); });
static::deleted(function ($model) { static::deleted(function ($model) {
// Clear search cache when model is deleted // Always clear cache when model is deleted
$teamId = $model->getTeamIdForCache(); $teamId = $model->getTeamIdForCache();
if (filled($teamId)) { if (filled($teamId)) {
GlobalSearch::clearTeamCache($teamId); GlobalSearch::clearTeamCache($teamId);
@@ -33,6 +35,32 @@ trait ClearsGlobalSearchCache
}); });
} }
private function hasSearchableChanges(): bool
{
// Define searchable fields based on model type
$searchableFields = ['name', 'description'];
// Add model-specific searchable fields
if ($this instanceof \App\Models\Application) {
$searchableFields[] = 'fqdn';
$searchableFields[] = 'docker_compose_domains';
} elseif ($this instanceof \App\Models\Server) {
$searchableFields[] = 'ip';
} elseif ($this instanceof \App\Models\Service) {
// Services don't have direct fqdn, but name and description are covered
}
// Database models only have name and description as searchable
// Check if any searchable field is dirty
foreach ($searchableFields as $field) {
if ($this->isDirty($field)) {
return true;
}
}
return false;
}
private function getTeamIdForCache() private function getTeamIdForCache()
{ {
// For database models, team is accessed through environment.project.team // For database models, team is accessed through environment.project.team