Your shop doesn't make what it sells: it buys from a supplier, and the supplier has its own API, at the address stored in SUPPLIER. To tell a customer how many of a product the supplier still has, a route of your shop asks the supplier first. While it handles one request, your shop sends one of its own: it is now the client of another API.
The tool is the one your scripts used, await fetch(url). A function that uses await must be async, and as Weather tells TypeScript the shape of the JSON. Here it is inside a route of a weather app, which asks a weather service:
app.get("/cities/:name/weather", async (req: Request, res: Response) => {
const name = req.params.name;
const url = WEATHER + "/today/" + name;
const response = await fetch(url);
const data = await response.json() as Weather;
res.json({ city: name, temperature: data.temp });
});
Two details matter. A path parameter arrives as text: Number(req.params.productId) makes it a number, so your JSON says 1 and not "1"; + turns it back into text when it joins the address. And look at response.status before you use the answer: when the other API says 404, its JSON doesn't have the key you want. data.stock is then undefined, and your route answers 200 with the stock missing, as if all went well.
The supplier answers GET /stock/<id> with JSON like {"id": 1, "stock": 120}, and it doesn't sell the Teapot (id 6). Your shop must answer:
GET /products/1/supplier-stock → 200 {"product_id": 1, "supplier_stock": 120}
GET /products/2/supplier-stock → 200 {"product_id": 2, "supplier_stock": 0}
GET /products/4/supplier-stock → 200 {"product_id": 4, "supplier_stock": 500}
GET /products/6/supplier-stock → 404 {"error": "The supplier doesn't sell this product"}
Your task: add the route GET /products/:productId/supplier-stock, with an async function. It asks the supplier for /stock/<id>, answers 404 with an error when the supplier doesn't sell the product, and otherwise passes the supplier's stock on as supplier_stock.
Assignment
Follow the Coding Tutorial to build the route that asks the supplier how many of a product it still has.
Hint
Build the address with SUPPLIER + "/stock/" + productId. Check response.status right after the request, before you read data.stock.
Free plan: 30 tutor messages. PRO is unlimited.
