A page shows a product's photo with a tag like <img src="/products/1/photo">. The browser sends a GET to that address and draws whatever image comes back. So the shop answers the photo's bytes as they are, not JSON.
Bytes don't say what they are. The answer's Content-Type header tells the browser how to read them: image/png, image/jpeg... res.json always sets it to application/json; for bytes, you set it yourself. res.set(name, value) puts a header on the answer, then res.send sends the body untouched. The status is 200 when you don't set another. For example, a route that answers plain text:
app.get("/robots.txt", (req: Request, res: Response) => {
res.set("Content-Type", "text/plain");
res.send("User-agent: *");
});
The package mime-types knows the type of each file extension. mime.lookup("report.pdf") gives the type for that file name: application/pdf. A row of the photos table has the shape of the type Photo, already at the top of your file: its data is a Uint8Array, the type SQLite's bytes come back in.
After the tests upload two photos, the shop must answer:
POST /products/1/photo (photo: mug.png, 16 bytes) → 201 {"filename": "mug.png", "product_id": 1, "size": 16}
POST /products/3/photo (photo: lamp.jpg, 17 bytes) → 201 {"filename": "lamp.jpg", "product_id": 3, "size": 17}
GET /products/1/photo → 200 Content-Type: image/png, the 16 bytes
GET /products/3/photo → 200 Content-Type: image/jpeg, the 17 bytes
GET /products/2/photo → 404 {"error": "This product has no photo"}
Your task: add GET /products/:productId/photo. Look up the product's row in photos, as a Photo | undefined; with no row, answer 404; otherwise answer the stored bytes with status 200 and the Content-Type for the photo's file name.
Assignment
Follow the Coding Tutorial to add the route that serves a product's photo.
Hintmime-types is already imported, as mime. Set the header before you send: res.set with "Content-Type" first, then res.send with the row's bytes.
Free plan: 30 tutor messages. PRO is unlimited.
