Skip to content

Commit

Permalink
allow limit and order_by query string parameters in GET /reviews …
Browse files Browse the repository at this point in the history
…endpoint
  • Loading branch information
creme332 committed Oct 8, 2024
1 parent 67f4b13 commit 22cc20d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
2 changes: 1 addition & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ A user can be a client or an administrator.

| Endpoint | Description | Protected | Query string parameters |
|-------------------------------------|-------------------------------------------------------|-----------|-------------------------|
| `GET /api/v1/reviews` | Get all reviews for a particular product by its ID. | No | `sort` |
| `GET /api/v1/reviews` | Get all reviews for a particular product by its ID. | No | `limit`, `order_by` |
| `GET /api/v1/products/[id]/reviews` | Get all reviews for a particular product by its ID. | No |
| `POST /api/v1/reviews` | Create a new review for a product. | Yes |
| `PUT /api/v1/reviews/[id]` | Update the details of a review with the specified ID. | Yes |
Expand Down
32 changes: 25 additions & 7 deletions src/controllers/api/Reviews.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@

use Opis\JsonSchema\{Errors\ErrorFormatter};
use Exception;
use PDO;
use Steamy\Core\Database;
use Steamy\Core\Utility;
use Steamy\Model\Review;

class Reviews
{
use Database;

public static array $routes = [
'GET' => [
Expand All @@ -33,16 +36,31 @@ class Reviews
*/
public function getAllReviews(): void
{
// Retrieve all reviews from the database
$allReviews = Review::getAll();
$query = "SELECT * FROM review";

// Convert reviews to array format
$result = [];
foreach ($allReviews as $Review) {
$result[] = $Review->toArray();
if (!empty($_GET['order_by']) && $_GET['order_by'] === 'created_date') {
$query .= " ORDER BY created_date DESC ";
}

// Return JSON response
if (!empty($_GET['limit'])) {
$limit = filter_var($_GET['limit'], FILTER_SANITIZE_NUMBER_INT);
$query .= " LIMIT " . $limit;
}

$query .= ";";

$con = self::connect();
$stm = $con->prepare($query);
$success = $stm->execute();

if (!$success) {
http_response_code(500);
echo json_encode(['error' => 'Database bad']);
return;
}

$result = $stm->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($result);
}

Expand Down

0 comments on commit 22cc20d

Please sign in to comment.