add TypesenseService

This commit is contained in:
2026-02-10 15:27:55 +01:00
parent 05ff869183
commit 4acb8ad001
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Models\Events;
use Illuminate\Support\Facades\Cache;
use Typesense\Client;
class TypesenseService
{
protected Client $client;
public function __construct()
{
$this->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);
}
}
}