adding middleware
This commit is contained in:
parent
74f6fdcf0f
commit
23a3a83deb
2 changed files with 32 additions and 4 deletions
|
@ -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 };
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue