I want to reuse a code snippet which will save me A WHOLE LOT OF TIME. I want to make POST, DELETE, PATCH and GET requests modular.
I have a js File which defines the basic route for each module (mod) and since I'm using 23 modules, which will all function the same way, I'd like to take this shortcut. Heres the "Basic Route File"
let route = "";
let mod = undefined;
router.get("/" + route, verify, async (req, res) => {
const id = req.query.id;
let data;
if (id) {
data = await mod.findOne({_id: id});
} else {
data = await mod.find({});
}
if (data)
return res.status(200).json({status: 404, message: "The data can't be found!", data: []});
else
return res.status(200).json({status: 200, message: "Found data!", data: data});
});
router.post("/" + route, verify, async (req, res) => {
let data = new mod(req.body);
data = await data.save();
if (data)
return res.status(200).json({status: 404, message: "The data can't be found!", data: []});
else
return res.status(200).json({status: 200, message: "Found data!", data: data});
});
router.patch("/" + route, verify, async (req, res) => {
const id = req.query.id;
let data;
if (id) {
data = await mod.updateOne({_id: id}, {$set: req.body});
}
if (!data)
return res.status(200).json({status: 404, message: "The data can't be found!", data: []});
else
return res.status(200).json({status: 200, message: "Found data and updated!", data: data});
});
router.delete("/" + route, verify, async (req, res) => {
const id = req.query.id;
let data;
if (id) {
data = await mod.deleteOne({_id: id});
}
if (!data)
return res.status(200).json({status: 404, message: "The data can't be found!", data: []});
else
return res.status(200).json({status: 200, message: "Found data and deleted!", data: data});
});
module.exports = function(proute, pmodule){
route = proute;
module = pmodule;
return router;
};
And in one of the other router files I tell each route which module they are using and what they are called.
router.use(yukir("disc-server", DiscServer));
router.use(yukir("disc-user", User));
router.use(yukir("autochannel", AutoChannel));
The thing is I don't get any errors but a 404 error so the route can't be found, which is really strange. Can someone help me with that?
Your problem is that strings in Javascript are pass by value, not pass by reference, so at the time the calls to the router methods are made, route and mod are the empty string and undefined respectively. The router functions thus always register the route at "/". Wrap your route definition code inside the factory function and you'll be fine.