Skip to content

Commit

Permalink
API endpoint updates
Browse files Browse the repository at this point in the history
  • Loading branch information
NuwanJ committed Oct 21, 2024
1 parent 4882bc7 commit ca4f37d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
20 changes: 15 additions & 5 deletions app/Http/Controllers/API/EventApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,29 @@
use App\Domains\Event\Models\Event;
use App\Http\Controllers\Controller;
use App\Http\Resources\EventResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class EventApiController extends Controller
{
public function index()
public function index(Request $request)
{
try {
$perPage = 20;
$event = Event::where('enabled', 1)->orderBy('start_at', 'desc')->paginate($perPage);
$query = Event::where('enabled', 1)->orderBy('start_at', 'desc');
$event_type_filter = $request->event_type;

if (in_array($event_type_filter, Event::eventTypeMap()) && $request->has('event_type')) {
$eventTypeId = array_search($request->event_type, Event::eventTypeMap());

// Note: This is not the best way, but easiest way to filter JSON content
$query = $query->where('event_type', 'LIKE', "%\"$eventTypeId\"%");
}

$events = $query->paginate(20);

return EventResource::collection($event);
return EventResource::collection($events);
} catch (\Exception $e) {
Log::error('Error in EventApiController@index', ['error' => $e->getMessage()]);
Log::error('Error in EventApiController@index', $e);
return response()->json(['message' => 'An error occurred while fetching events'], 500);
}
}
Expand Down
7 changes: 7 additions & 0 deletions app/Http/Resources/EventResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Http\Resources;

use App\Domains\Auth\Models\User;
use App\Domains\Event\Models\Event;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\URL;

Expand All @@ -16,6 +17,11 @@ class EventResource extends JsonResource
*/
public function toArray($request)
{
$eventTypeList = Event::eventTypeMap();
$eventTypes = array_map(function ($id) use ($eventTypeList) {
return isset($eventTypeList[$id]) ? $eventTypeList[$id] : null;
}, $this->event_type);

return [
'id' => $this->id,
'title' => $this->title,
Expand All @@ -24,6 +30,7 @@ public function toArray($request)
'image' => URL::to($this->thumbURL()),
'start_at' => $this->start_at,
'end_at' => $this->end_at,
'event_type' => $eventTypes,
'location' => $this->location,
'link_url' => $this->link_url,
'link_caption' => $this->link_caption,
Expand Down

0 comments on commit ca4f37d

Please sign in to comment.