added the images/id endpoint and the tests for it
Unit Tests with docker compose / unit-test (pull_request) Successful in 3m37s
Details
Unit Tests with docker compose / unit-test (pull_request) Successful in 3m37s
Details
This commit is contained in:
parent
265761766f
commit
df99e9470c
|
@ -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);
|
||||
|
||||
|
|
|
@ -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<void> {
|
||||
try {
|
||||
const images = await imageService.findAll();
|
||||
|
|
|
@ -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<Image[]> {
|
||||
const allImages = await imageModel.find();
|
||||
return allImages;
|
||||
|
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue