Skip to content

Commit

Permalink
added the ability to get a random image
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaishiyoku committed Oct 22, 2018
1 parent 7c5c6e9 commit 497475f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
24 changes: 24 additions & 0 deletions app/Http/Controllers/Api/v1/ImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Http\Controllers\Controller;
use App\Models\Image;
use App\Http\Controllers\Api\v1\exceptions\InvalidArgumentException;

class ImageController extends Controller
{
Expand All @@ -30,4 +31,27 @@ public function show(Image $image)
{
return response()->json($image);
}

/**
* @param string|null $rating
* @retun \Illuminate\Http\JsonResponse
*/
public function showRandom($rating = null)
{
$availableRatings = collect(explode(',', env('CRAWLER_RATINGS')))->map(function ($rating) {
return strtolower($rating);
})->toArray();

if (!empty($rating) && !in_array(strtolower($rating), $availableRatings)) {
return response('The given rating is invalid.', 422);
}

if ($rating) {
$image = Image::whereRating($rating)->inRandomOrder()->first();
} else {
$image = Image::inRandomOrder()->first();
}

return response()->json($image);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Http\Controllers\Api\v1\exceptions ;

use Exception;

class InvalidArgumentException extends Exception
{

}
1 change: 1 addition & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Route::prefix('v1')->middleware('api')->group(function () {
Route::get('/health_check', 'Api\v1\HomeController@healthCheck');

Route::get('/images/random/{rating?}', 'Api\v1\ImageController@showRandom');
Route::resource('/images', 'Api\v1\ImageController')->only(['index', 'show']);
Route::get('/images/rating/{rating?}', 'Api\v1\ImageController@index');

Expand Down

0 comments on commit 497475f

Please sign in to comment.