Managing Cart Line Items
Managing Cart Line Items
Welcome back! 👋 In the last lesson you made carts useful by adding line items with a real-world add-or-increment behavior. The route validated inputs, the service enforced business rules like inventory checks, and the repository performed safe writes in a transaction.
In this final lesson, we make the cart feel editable like a real shopping experience. You’ll learn how our API targets a specific cart item row so clients can update quantity or remove an item—without resending product details.
Editing a specific cart item
To update or delete a line item, we address it directly by its cart item ID:
/api/carts/:id/items/:itemId
That means we always deal with two identifiers:
id: the cart UUID (from thecartstable)itemId: the cart item UUID (from thecart_itemstable)
This is important because changing quantity or deleting an item is an operation on the line item row, not on the product itself.
Route: updating and deleting items by ID
The file src/app/api/carts/[id]/items/[itemId]/route.ts contains both endpoints:
PATCHfor updating quantityDELETEfor removing the item
The route follows the same “fail fast” pattern you’ve seen already: validate path params, validate body (for PATCH), call the service, then translate the ServiceResult into an HTTP response.
Route setup and parameter handling:
- This route uses the same response helpers as the rest of the API (
success,error) so responses stay consistent across endpoints. RouteContextagain definesparamsas a Promise, so we alwaysawait context.paramsto readidanditemId.parseJsonis used for PATCH so malformed JSON becomes a clean400, rather than a thrown exception that would force a generic500.
Updating quantity with PATCH
Updating a line item is a “quantity edit.” The client sends { "quantity": number }, and we validate everything before touching the database.
Validating both IDs and parsing the request body:
- Both
idanditemIdare validated up front so invalid URLs are treated as client errors (400) instead of wasting database work. parseJson(req)protects the route from invalid JSON. If the body can’t be parsed, we return a standardized error envelope with an HTTP 400.validateUpdateItemensures the service only receives a clean DTO{ quantity: number }. That way, the service can focus on business rules instead of re-checking types.
