Skip to content

Commit

Permalink
implement API gateway for news items
Browse files Browse the repository at this point in the history
  • Loading branch information
IsharaEkanayaka committed Jul 2, 2024
1 parent e66ab52 commit 226989d
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 14 deletions.
35 changes: 35 additions & 0 deletions app/Http/Controllers/Backend/NewsApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Http\Controllers\Backend;

use App\Http\Resources\NewsResource;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Domains\NewsItem\Models\NewsItem;

class NewsApiController extends Controller
{
public function index()
{
$perPage = 20;
$news = NewsItem::latest()->paginate($perPage);

if ($news->count() > 0) {
return NewsResource::collection($news);
} else {
return response()->json(['message' => 'News item not found'], 404);
}
}


public function show($id)
{
$news = NewsItem::find($id);

if ($news) {
return new NewsResource($news);
} else {
return response()->json(['message' => 'News item not found'], 404);
}
}
}
30 changes: 30 additions & 0 deletions app/Http/Resources/NewsResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class NewsResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'author' => $this->author,
'image' => $this->image,
'link_url' => $this->link_url,
'link_caption' => $this->link_caption,
'posted_at' => $this->created_at,
'updated_at' => $this->updated_at,

];
}
}
17 changes: 3 additions & 14 deletions routes/api.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
<?php

use App\Http\Controllers\Backend\NewsApiController;
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

//Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
// return $request->user();
//});
Route::get('/news',[NewsApiController::class,'index']);
Route::get('/news/{id}',[NewsApiController::class,'show']);

0 comments on commit 226989d

Please sign in to comment.