Merge pull request 'Implemented the /images/:id' (#16) from get-id into develop
Reviewed-on: #16
This commit is contained in:
commit
30409e4f3b
|
@ -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