Files
SAE-BUT2-backend/app/Http/Controllers/SearchController.php
T

84 lines
2.3 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Typesense\Client;
use Exception;
use App\Models\Events;
class SearchController extends Controller
{
protected Client $client;
public function __construct()
{
$this->client = new Client([
'api_key' => 'xyz',
'nodes' => [
[
'host' => env('TYPESENSE_CONNECTION'),
'port' => '8108',
'protocol' => 'http',
],
],
]);
}
private function createEventsCollection()
{
try {
$collections = $this->client->collections->retrieve();
if (!in_array('events', array_column($collections, 'name'))) {
$this->client->collections->create([
'name' => 'events',
'fields' => [
['name' => 'name', 'type' => 'string'],
['name' => 'description', 'type' => 'string'],
],
]);
}
} catch (Exception $e) {
throw new Exception("Error while creating the events collection : " . $e->getMessage());
}
}
private function indexEvents()
{
try {
$events = Events::all();
foreach ($events as $event) {
$this->client->collections['events']->documents->upsert([
'id' => (string) $event->id,
'name' => $event->name,
'description' => $event->description,
]);
}
} catch (Exception $e) {
throw new Exception("Error while indexing events : " . $e->getMessage());
}
}
public function searchEvents(Request $request)
{
try {
$this->createEventsCollection();
$this->indexEvents();
$query = $request->input('query', '');
$searchResults = $this->client->collections['events']->documents->search([
'q' => $query,
'query_by' => 'name,description',
]);
return response()->json($searchResults);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}