So I was trying to make one function which to do crud operation for all routes but found out once i call one route with that function it doesnt work with any other routes and will only get post put or delete item that are in the first route in my code.
My base router
function baseRouter(Model, outputName) {
router
.route("/")
.get((req, res, next) => {
getAllData(res, Model, outputName + "s");
})
.post((req, res, next) => {
let data = new Model(req.body);
addData(res, data, outputName);
});
router
.route("/:id")
.get((req, res, next) => {
getDataById(req, res, Model, outputName);
})
.put((req, res, next) => {
let data = req.body;
updateDataById(req, res, Model, data, outputName);
})
.delete((req, res, next) => {
deleteDataById(req, res, Model, outputName);
});
return router;
}
module.exports = baseRouter;
The code from which i am calling every routes
const router = require("express").Router();
//all models
const UserModel = require("../models/user.model");
const ContactModel = require("../models/contact.model");
const LinksModel = require("../models/links.model");
const EducationModel = require("../models/education.model");
const SkillModel = require("../models/skills.model");
const ProjectModel = require("../models/projects.model");
//router
const baseRouter = require("./baseRoute");
// all routes crud operation
router.use("/contact", baseRouter(ContactModel, "Contact"));
router.use("/link", baseRouter(LinksModel, "Link"));
router.use("/education", baseRouter(EducationModel, "Education"));
router.use("/skill", baseRouter(SkillModel, "Skill"));
router.use("/project", baseRouter(ProjectModel, "Project"));
module.exports = router;
I hope i explained my question properly.
try passing the router instance and name string to your
function baseRouter(router, name, Model, outputName) {...}
add it to the routes path in that function
.route(`${name}/`)
and
.route(`${name}/:id`)
and call it in your router index as
baseRouter(router, "contact", ContactModel, "Contact"));
you don't have to return it in the function because you're defining the routes for the router instance directly and might be able to use the "contact" once and capitalize it where you need it
you instantiate your router in the router index and return it to your app index if you want after you've passed all your defined routes the same way