From 34711b47d19be66f5ac3c4f250354089124a872a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20=C5=9E=C3=BCkr=C3=BC=20Kapusuz?= Date: Fri, 19 May 2023 19:20:13 +0300 Subject: [PATCH] refactor: perf improvement (prevent twice settings pulling) --- includes/indices/class-algolia-index.php | 2 ++ .../class-algolia-primary-index-settings.php | 22 ++++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/includes/indices/class-algolia-index.php b/includes/indices/class-algolia-index.php index 07c00d6f..387ac675 100644 --- a/includes/indices/class-algolia-index.php +++ b/includes/indices/class-algolia-index.php @@ -18,6 +18,8 @@ * @since 1.0.0 */ abstract class Algolia_Index { + const AC_INDEX_NOT_EXISTS_EXCEPTION_MSG = 'Index does not exist'; + /** * Default index settings * diff --git a/includes/indices/settings/class-algolia-primary-index-settings.php b/includes/indices/settings/class-algolia-primary-index-settings.php index db1833ac..ac16ba12 100644 --- a/includes/indices/settings/class-algolia-primary-index-settings.php +++ b/includes/indices/settings/class-algolia-primary-index-settings.php @@ -1,6 +1,7 @@ get_index()->get_default_settings(); } + /** + * If the Indice is not found, return empty settings. In that case, a new index is created. + * + * @throws Exception Varius exceptions can be thrown by Algolia Client except for NotFoundException. + * @return array + */ public function get_remote_settings(): array { - if ( ! $this->get_index()->exists() ) { - return []; - } + try { + return $this->get_algolia_index()->getSettings(); + } catch ( NotFoundException $e ) { + // being more strict, catch only index does not exists case. + if ( $e->getMessage() === Algolia_Index::AC_INDEX_NOT_EXISTS_EXCEPTION_MSG ) { + return []; + } - return $this->get_algolia_index()->getSettings(); + throw $e; + } } public function get_settings_needs_sync(): array { @@ -63,7 +75,7 @@ public function push( $overrides = [] ): bool { } try { - $this->get_algolia_index()->setSettings( $settings ); + $this->get_algolia_index()->setSettings( $settings ); // Creates new indice if doesn't exist. } catch ( Exception $e ) { return false; }