From 23a3a83debf988e198a5fbf567ec1a6e94e54eb5 Mon Sep 17 00:00:00 2001 From: Kfir Dayan Date: Sun, 9 Jul 2023 00:40:06 +0300 Subject: [PATCH] adding middleware --- .../src/middleware/createTodoMiddleWare.ts | 23 ++++++++++++++++++- todo-service/src/routes/todoRouter.ts | 13 ++++++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/todo-service/src/middleware/createTodoMiddleWare.ts b/todo-service/src/middleware/createTodoMiddleWare.ts index d48bb3c..460fad4 100644 --- a/todo-service/src/middleware/createTodoMiddleWare.ts +++ b/todo-service/src/middleware/createTodoMiddleWare.ts @@ -1,6 +1,7 @@ import { Request, Response, NextFunction } from "express"; import { ApiError } from "../utils/ApiError"; import { DateTime } from "luxon"; +import mongoose from 'mongoose'; const createTodoMiddleWare = async ( req: Request, @@ -48,4 +49,24 @@ const createTodoMiddleWare = async ( next(); }; -export { createTodoMiddleWare }; +const paramIdMiddleware = async ( + req: Request, + res: Response, + next: NextFunction +) => { + // check if it's a valid mongo id + const { id } = req.params; + if (!mongoose.Types.ObjectId.isValid(id)) { + const error = new ApiError( + `id must be a valid mongo id`, + 400, + "Bad Request" + ); + return next(error); + } + next(); + +}; + + +export { createTodoMiddleWare, paramIdMiddleware }; diff --git a/todo-service/src/routes/todoRouter.ts b/todo-service/src/routes/todoRouter.ts index c1c7670..4ea15e5 100644 --- a/todo-service/src/routes/todoRouter.ts +++ b/todo-service/src/routes/todoRouter.ts @@ -1,6 +1,9 @@ import { Router } from "express"; import { TodoController } from "../controllers/todoController"; -import { createTodoMiddleWare } from "../middleware/createTodoMiddleWare"; +import { + createTodoMiddleWare, + paramIdMiddleware, +} from "../middleware/createTodoMiddleWare"; class TodoRouter { router: Router; @@ -14,14 +17,18 @@ class TodoRouter { private setRoutes() { this.router.get("/", this.todoController.getAll); - this.router.get("/:id", this.todoController.getOne); + this.router.get("/:id", paramIdMiddleware, this.todoController.getOne); this.router.post("/", createTodoMiddleWare, this.todoController.createOne); this.router.put( "/:id", createTodoMiddleWare, this.todoController.updateOne ); - this.router.delete("/:id", this.todoController.deleteOne); + this.router.delete( + "/:id", + paramIdMiddleware, + this.todoController.deleteOne + ); this.router.delete("/", this.todoController.removeAll); }