Exercise #07 - ShoppingCart
Write a server that manages a shopping cart.
This is the first exercise that involves JSON. Items in the cart
will look like { "model": "something", "quantity": 10 }
.
A cart is just a list of items. Items are appended at the end of the cart.
Only adding items is supported. Expose two routes:
>
GET /cart
POST /cart
The cart starts empty. Don't worry about the same item getting added twice for now.
GET /cart >>> expected [] POST /cart { "model": "first thing", "quantity": 2 } GET /cart >>> expected [ { "model": "first thing", "quantity": 2 } ] POST /cart { "model": "another thing", "quantity": 30 } GET /cart >>> expected [ { "model": "first thing", "quantity": 2 }, { "model": "another thing", "quantity": 30 } ]
If you're unsure on how to proceed, read more on how to setup your Local dev environment to complete the exercises.
Refresh the page to run the tests again.
Reference node.js implementation
const app = require("express")()
const bodyParser = require("body-parser")
app.use(bodyParser.json())
// Mutable state!
let currentCart = []
app.post("/cart", (req, res) => {
const item = req.body
if (item.model && item.quantity)
{
currentCart.push(item)
res.send("ok")
}
else {
throw new Error("Not a valid item")
}
})
app.get("/cart", (req, res) => {
res.json(currentCart)
})
console.log("Starting server...")
app.listen(7879)
Where to get help
Got stuck? Don't worry! Join the discussion on Github (issue #7). It might be that the exercise could be clearer or there's something you really can't wrap your head around. That's totally fine! 🙂
You can also have a look at my solution. No shame in having a peek. 🧐
But do share your thoughts on the exercises, it would be really helpful!