Skip to content

Commit

Permalink
add getReviewByID, send appropriate errors when review attributes are…
Browse files Browse the repository at this point in the history
… invalid in createReview
  • Loading branch information
creme332 committed May 22, 2024
1 parent 2d97d7f commit 2d7ec81
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/controllers/api/Reviews.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class Reviews
public static array $routes = [
'GET' => [
'/api/v1/reviews' => 'getAllReviews',
'/api/v1/reviews/{id}' => 'getReviewByID',
'/api/v1/products/{id}/reviews' => 'getAllReviewsForProduct',
],
'POST' => [
Expand Down Expand Up @@ -45,6 +46,26 @@ public function getAllReviews(): void
echo json_encode($result);
}

public function getReviewByID(): void
{
$id = (int)Utility::splitURL()[3];

// Retrieve all reviews from the database
$review = Review::getByID($id);

// Check if product exists
if ($review === null) {
// review not found, return 404
http_response_code(404);
echo json_encode(['error' => 'Review not found']);
return;
}

// Return JSON response
echo json_encode($review->toArray());
}


/**
* Get all reviews for a particular product by its ID.
*/
Expand Down Expand Up @@ -106,6 +127,14 @@ public function createReview(): void
(int)$postData['rating']
);

$errors = $newReview->validate();

if (!empty($errors)) {
http_response_code(400);
echo json_encode(['error' => ($errors)]);
return;
}

// Save the new review to the database
if ($newReview->save()) {
// Review created successfully, return 201 Created
Expand Down

0 comments on commit 2d7ec81

Please sign in to comment.