adding middleware

This commit is contained in:
Kfir Dayan 2023-07-09 00:40:06 +03:00
parent 74f6fdcf0f
commit 23a3a83deb
2 changed files with 32 additions and 4 deletions

View file

@ -1,6 +1,7 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { ApiError } from "../utils/ApiError"; import { ApiError } from "../utils/ApiError";
import { DateTime } from "luxon"; import { DateTime } from "luxon";
import mongoose from 'mongoose';
const createTodoMiddleWare = async ( const createTodoMiddleWare = async (
req: Request, req: Request,
@ -48,4 +49,24 @@ const createTodoMiddleWare = async (
next(); 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 };

View file

@ -1,6 +1,9 @@
import { Router } from "express"; import { Router } from "express";
import { TodoController } from "../controllers/todoController"; import { TodoController } from "../controllers/todoController";
import { createTodoMiddleWare } from "../middleware/createTodoMiddleWare"; import {
createTodoMiddleWare,
paramIdMiddleware,
} from "../middleware/createTodoMiddleWare";
class TodoRouter { class TodoRouter {
router: Router; router: Router;
@ -14,14 +17,18 @@ class TodoRouter {
private setRoutes() { private setRoutes() {
this.router.get("/", this.todoController.getAll); 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.post("/", createTodoMiddleWare, this.todoController.createOne);
this.router.put( this.router.put(
"/:id", "/:id",
createTodoMiddleWare, createTodoMiddleWare,
this.todoController.updateOne this.todoController.updateOne
); );
this.router.delete("/:id", this.todoController.deleteOne); this.router.delete(
"/:id",
paramIdMiddleware,
this.todoController.deleteOne
);
this.router.delete("/", this.todoController.removeAll); this.router.delete("/", this.todoController.removeAll);
} }