From 4acb8ad00137a6d65dcd02eee51870509ede99ce Mon Sep 17 00:00:00 2001 From: Giovanni-Josserand Date: Tue, 10 Feb 2026 15:27:55 +0100 Subject: [PATCH] add TypesenseService --- app/Services/TypesenseService.php | 132 ++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 app/Services/TypesenseService.php diff --git a/app/Services/TypesenseService.php b/app/Services/TypesenseService.php new file mode 100644 index 0000000..667c7af --- /dev/null +++ b/app/Services/TypesenseService.php @@ -0,0 +1,132 @@ +client = new Client([ + 'api_key' => env('TYPESENSE_API_KEY'), + 'nodes' => [ + [ + 'host' => env('TYPESENSE_CONNECTION'), + 'port' => '8108', + 'protocol' => 'http', + ], + ], + ]); + } + + private function ensureCollectionsExist(): void + { + static $checked = false; + + if ($checked) { + return; + } + + try { + $collections = $this->client->collections->retrieve(); + $names = array_column($collections, 'name'); + + if (!in_array('events', $names)) { + $this->client->collections->create([ + 'name' => 'events', + 'fields' => [ + ['name' => 'name', 'type' => 'string'], + ['name' => 'description', 'type' => 'string'], + ], + ]); + } + + if (!in_array('users', $names)) { + $this->client->collections->create([ + 'name' => 'users', + 'fields' => [ + ['name' => 'name', 'type' => 'string'], + ['name' => 'lastname', 'type' => 'string'], + ['name' => 'validate', 'type' => 'bool'], + ], + ]); + } + + $checked = true; + } catch (\Throwable $e) { + report($e); // log l'erreur, mais ne stoppe pas l'exécution + } + } + + public function upsertEvent(Events $event): void + { + $this->ensureCollectionsExist(); + + try { + $this->client->collections['events'] + ->documents + ->upsert([ + 'id' => (string) $event->id, + 'name' => $event->name, + 'description' => $event->description, + ]); + } catch (\Throwable $e) { + report($e); + } + } + + public function deleteEvent(int $eventId): void + { + $this->ensureCollectionsExist(); + + try { + $this->client->collections['events'] + ->documents[(string) $eventId] + ->delete(); + } catch (\Throwable $e) { + report($e); + } + } + + public function upsertUser(User $user): void + { + $this->ensureCollectionsExist(); + + if (!$user->validate) { + $this->deleteUser($user->id); + return; + } + + try { + $this->client->collections['users'] + ->documents + ->upsert([ + 'id' => (string) $user->id, + 'name' => $user->name, + 'lastname' => $user->lastname, + 'validate' => true, + ]); + } catch (\Throwable $e) { + report($e); + } + } + + public function deleteUser(int $userId): void + { + $this->ensureCollectionsExist(); + + try { + $this->client->collections['users'] + ->documents[(string) $userId] + ->delete(); + } catch (\Throwable $e) { + report($e); + } + } +}