Start learning free

LESSON 33 OF 173 · BACKEND: YOUR FIRST API

Reviews for a Product in JavaScript

Practice

Customers can now review a product: a number of stars from 1 to 5 and a short text. A review belongs to one product, so its path goes under the product's path: /products/1/reviews are the reviews of product 1. This is a nested path, and the id in the middle is a path parameter, as in GET /products/1.

The reviews are already in the file, in the object reviews: each key is a product id, and each value is the array of that product's reviews. A product with no reviews has no key, so reviews[productId] is undefined for it. reviews[productId] || [] gives its array, or an empty one: || gives the value on its right when there is nothing on its left. The same object of arrays, with other values:

const tags = { 1: ["sale", "new"] };
console.log(tags[1] || []);   // [ 'sale', 'new' ]
console.log(tags[2] || []);   // []
tags[2] = tags[2] || [];
tags[2].push("gift");
console.log(tags[2]);         // [ 'gift' ]

One path can have a route for each method: GET reads a product's reviews, and POST adds one and answers 201 with it. Both answer 404 when no product has the id. Your code must answer these requests, in this order:

GET /products/1/reviews  →  200  [{"stars": 5, "text": "Great mug"}, {"stars": 4, "text": "A bit small"}]
GET /products/4/reviews  →  200  []
GET /products/99/reviews  →  404  {"error": "Product not found"}
POST /products/2/reviews  {"stars": 4, "text": "Nice paper"}  →  201  {"stars": 4, "text": "Nice paper"}
GET /products/2/reviews  →  200  [{"stars": 4, "text": "Nice paper"}]
POST /products/1/reviews  {"stars": 3, "text": "The handle gets hot"}  →  201  {"stars": 3, "text": "The handle gets hot"}
GET /products/1/reviews  →  200  [{"stars": 5, …}, {"stars": 4, …}, {"stars": 3, "text": "The handle gets hot"}]
POST /products/99/reviews  {"stars": 5, "text": "Love it"}  →  404  {"error": "Product not found"}
GET /products/1  →  200  {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}

Your task: add a GET and a POST route for /products/:productId/reviews. GET answers the product's array of reviews, or []; POST pushes the review to the end of that array and answers 201 with it; both answer 404 when the product doesn't exist.


Assignment
Follow the Coding Tutorial to build the GET route and the POST route on the nested path.


Hint
Find the product first, with the loop and if of the route that reads one product. reviews[productId] || [] never fails on a missing key. Before you push, store that array back under reviews[productId], so a product's first review has an array to go into.


STEP 1 OF 11
    Ctrl + Enter to check

    Shop Reviews in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free