diff --git a/src/app.ts b/src/app.ts index 43a3f6f..8ae7edd 100644 --- a/src/app.ts +++ b/src/app.ts @@ -14,6 +14,7 @@ app.get("/", (_, res) => { }); app.get("/images", imageController.getAllImages); +app.get("/images/:id", imageController.getImageById); app.post("/images", authControler.authorize, imageController.addImage); app.post("/login", authControler.login); diff --git a/src/controllers/ImageController.ts b/src/controllers/ImageController.ts index 75fca37..4b2301e 100644 --- a/src/controllers/ImageController.ts +++ b/src/controllers/ImageController.ts @@ -3,6 +3,23 @@ import imageService from "../services/ImageService"; import mongoose, { mongo } from "mongoose"; class ImageController { + async getImageById(req: Request, res: Response) { + try { + const image = await imageService.findById(req.params.id); + if (image) { + res.json({ image }); + } else { + res.status(404).json({ error: "Image not found" }); + } + } catch (error: any) { + if (error instanceof mongoose.Error.CastError) { + res.status(400).json({ error: "Invalid Id" }); + } else { + res.status(500).json({ error: "Internal Server Error" }); + } + } + } + async getAllImages(_: Request, res: Response): Promise { try { const images = await imageService.findAll(); diff --git a/src/services/ImageService.ts b/src/services/ImageService.ts index 8691f7d..8289ed5 100644 --- a/src/services/ImageService.ts +++ b/src/services/ImageService.ts @@ -1,6 +1,10 @@ import imageModel, { Image } from "../models/ImageModel"; class ImageService { + async findById(id: string) { + const image = await imageModel.findOne({ _id: id }); + return image; + } async findAll(): Promise { const allImages = await imageModel.find(); return allImages; diff --git a/tests/app.test.ts b/tests/app.test.ts index 4893ae0..91987dd 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -177,3 +177,26 @@ describe("POST /images works properly", () => { expect(res.status).toBe(400); }); }); + +describe("/images/:id works properly", () => { + it("should return 200 for existing ids", async () => { + const list = await request(app).get("/images"); + const id = list.body.images[0]._id; + const res = await request(app).get(`/images/${id}`); + expect(res.status).toBe(200); + }); + + it("should return 404 for non-existing ids", async () => { + const list = await request(app).get("/images"); + const id = "000000000000000000000000"; // this was the least posible to exist ID + if (!(id in list.body.images)) { + const res = await request(app).get(`/images/${id}`); + expect(res.status).toBe(404); + } + }); + + it("should return 400 for malformed ids", async () => { + const res = await request(app).get("/images/98439384"); + expect(res.status).toBe(400); + }); +});