Start learning free

LESSON 104 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

When the Other API Fails in TypeScript

Practice

Other services break: a bug, a full disk, a deploy gone wrong. The supplier then answers 500 Internal Server Error, with JSON like {"error": "The supplier is down"}. That JSON has no stock. as SupplierStock doesn't check it while the code runs, so data.stock is undefined, and your route answers 200 with the stock missing, as if nothing was wrong.

Check the status before you trust the answer. Your route is a gateway: a server that passes requests on to another server. When the server behind it fails, a gateway answers 502 Bad Gateway. Here is the idea in a weather app:

const response = await fetch(WEATHER + "/today/" + name);
if (response.status !== 200) {
  return res.status(502).json({ error: "The weather service is not answering" });
}
const data = await response.json() as Weather;

502 tells the client that the problem is behind your shop: not in its request (a 4xx), and not a crash of your shop (a 500). Keep the 404 check first, so the Teapot still gets its 404; then "not 200" catches every other failure.

The check switches the supplier off for one request with POST /check/supplier-down, a page that only exists in the tests. Your shop must answer:

GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/1/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}

Your task: in the /products/:productId/supplier-stock route, below the 404 check, answer "The supplier is not answering" with 502 whenever the supplier's status is not 200.


Assignment
Follow the Coding Tutorial to answer a clear 502 when the supplier fails, instead of a 200 with the stock missing.


Hint
The new if goes between the 404 block and const data = await response.json() as SupplierStock;. Inside it, return res.status(502).json(...), like the 404 answer does.


STEP 1 OF 2
    Ctrl + Enter to check

    Svc Supplier Down in TypeScript

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