From f74a0f26cc4ec006e9ac4d55ba4ed7e497f9efbd Mon Sep 17 00:00:00 2001 From: Alie Date: Sat, 6 Jan 2024 12:24:30 +0100 Subject: [PATCH] made the endpoint, works with manual tests --- src/app.ts | 1 + src/controllers/ImageController.ts | 29 +++++++++++++++++++++++++++++ src/services/ImageService.ts | 4 ++++ 3 files changed, 34 insertions(+) diff --git a/src/app.ts b/src/app.ts index 8ae7edd..9c985eb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -15,6 +15,7 @@ app.get("/", (_, res) => { app.get("/images", imageController.getAllImages); app.get("/images/:id", imageController.getImageById); +app.put("/images/:id", imageController.editImage) 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 4b2301e..ac1c207 100644 --- a/src/controllers/ImageController.ts +++ b/src/controllers/ImageController.ts @@ -1,8 +1,37 @@ import { Request, Response } from "express"; import imageService from "../services/ImageService"; import mongoose, { mongo } from "mongoose"; +import { Image } from "../models/ImageModel"; class ImageController { + async editImage(req: Request, res: Response) { + try { + const change: Image = req.body; + const result = await imageService.replaceOne(req.params.id, change); + if (result.matchedCount > 0) { + res.status(204).json(); + } 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 if ( + error instanceof mongo.MongoServerError && + error.code === 11000 + ) { + // Should return 409 Conflict for existing urls + res.status(409).json({ + error: `the image with URL ${error.keyValue.url} already exists`, + }); + } else if (error instanceof mongoose.Error.ValidationError) { + // Should return 400 Bad request for invalid requests + res.status(400).json({ error: error.message }); + } else { + res.status(500).json({ error: "Internal Server Error" }); + } + } + } async getImageById(req: Request, res: Response) { try { const image = await imageService.findById(req.params.id); diff --git a/src/services/ImageService.ts b/src/services/ImageService.ts index 8289ed5..c4b6f7a 100644 --- a/src/services/ImageService.ts +++ b/src/services/ImageService.ts @@ -1,6 +1,10 @@ import imageModel, { Image } from "../models/ImageModel"; class ImageService { + async replaceOne(id: string, newimage: Image) { + const image = await imageModel.updateOne({ _id: id }, newimage); + return image; + } async findById(id: string) { const image = await imageModel.findOne({ _id: id }); return image;