I am coding an e-commerce site with Node.js.
I noticed some code repeating while creating the routes but I couldn't find how to get rid of it.
men route is given below:
router.get(`/parent-category-selection`,(req, res, next) => {
categoryRequest.getAllParentCategories('mens', (error, data) => {
if(!error){
res.render('category/parentCategorySelection', {parentCategories:data});
}else {
res.render('error', {message:'An error occured.'})
}
})
})
women route is given below:
router.get(`/parent-category-selection`,(req, res, next) => {
categoryRequest.getAllParentCategories('womens', (error, data) => {
if(!error){
res.render('category/parentCategorySelection', {parentCategories:data});
}else {
res.render('error', {message:'An error occured.'})
}
})
})
routes in app.js:
app.use('/', indexRouter);
app.use('/men', menRouter)
app.use('/women',womenRouter)
app.use('/product',productRouter)
I want routes like /women/parent-category-selection and /men/parent-category-selection without code repetition.
How can I achieve that as you see above router functions are so similar I should find a way to bind gender information to the router like app.use('/:gender', genderRouter {gender:gender}). Any help ?
One pattern you could use is a higher order function, which is a function that returns a function. In this case, it is used to create an express middleware function. For example:
const parentCategorySelectionHandler = (gender) => (req, res) =>
categoryRequest.getAllParentCategories(gender, (error, data) => {
if (!error) {
res.render("category/parentCategorySelection", {
parentCategories: data,
});
} else {
res.render("error", { message: "An error occured." });
}
});
Which can be used like this:
router.get(`/parent-category-selection`, parentCategorySelectionHandler("men"));
If you wanted to get the gender from the URL, as you suggested, you could change it to the following.
middleware
const parentCategorySelectionHandler = (req, res) =>
categoryRequest.getAllParentCategories(req.params.gender, (error, data) => {
if (!error) {
res.render("category/parentCategorySelection", {
parentCategories: data,
});
} else {
res.render("error", { message: "An error occured." });
}
});
usage
router.get(`/parent-category-selection/:gender`, parentCategorySelectionHandler);
Then you'd need to change how you add the men/women routes in app.js since this one route would cover both of those genders.
Related
I a trying to implement a rest API for our project then I go for node js and express. I have built all the models and controllers. I faced an issue while trying to handle an error. Errorhandler function doesn't receive all the properties of error that caught in try/catch block. I can not read its name in a handler but I can use its name in the controller. Could you please help me?
const errorHandler = (err, req, res, next) => {
console.log(`Error in method:${req.method}: ${err.stack}`.bgRed);
let error = { ...err };
console.log(`Error handler: ${err.name}`);
res.status(error.statusCode || 500).json({
success: false,
data: error.message || 'Server Error',
});
};
module.exports = errorHandler;
controller
const mongoose = require('mongoose');
const Product = require('../models/Product');
const ErrorResponse = require('../utils/error');
const routeName = 'PRODUCT';
// #desc getting single product via id
// #route GET api/v1/products
// #acces public
exports.getProdcut = async (req, res, next) => {
try {
const product = await Product.findById(req.params.id);
if (!product) {
return next(
new ErrorResponse(`Product not found with id:${req.params.id}`, 404)
);
}
res.status(200).json({
success: true,
data: product,
});
} catch (err) {
console.log(err.name);
console.log('ERRO APPEND');
next(new ErrorResponse(`Product not found with id:${req.params.id}`, 404));
}
};
Assuming that errorHandler is part of your middleware that is somewhere after getProdcut, you can try just throwing the error and Express will automatically detect that for you, because error handling middleware such as yours accepts 4 parameters. So the following would work:
const getProdcut = async (req, res, next) => {
try {
// ...
} catch (err) {
throw err;
}
};
const errorHandler = (err, req, res, next) => {
if (err) {
console.log('hello from the error middleware');
console.log(err.name);
}
else {
// next() or some other logic here
}
}
app.use('/yourRoute', getProdcut, errorHandler);
And inside of your errorHandler you should have access to the error object.
Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.
https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling
I am writing a middleware function that looks for validation errors and if the error is found gives out a certain output else continues the program flow. I have two functions with the exact code but they check for different schemas.
My first function runs without any exception. However, when I try to execute the second function I get an error in the console.
const validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body);
if (error) {
const msg = error.details.map((el) => el.message).join(",");
throw new ExpressError(msg, 400);
} else {
next();
}
};
const validateReview = (req, res, next) => {
const { error } = reviewSchema.validate(req.body);
if (error) {
const msg = error.details.map((el) => el.message).join(",");
throw new ExpressError(msg, 400);
} else {
next(); //this is the point where the exception occurs
}
};
It is only inside the validateReview function where next middleware function is not recognised as a valid function.
The problem was not with the next() middleware but instead it was with the route as I was wrapping the route with the validateReview function.
I was doing something like this :
app.post(
"/campgrounds/:id/reviews",
validateReview(
catchAsync(async (req, res) => {
//my Logic here
})
));
Whereas , I should have been doing something like this :
app.post(
"/campgrounds/:id/reviews",
validateReview,
catchAsync(async (req, res) => {
//my logic here
})
);
hi if you want to use a middileware
exports.middileware = (req,res,next)=>{
try{
//middileware logic
next();
}catch(err){
//print the error
})
}
}
and call the exported middileware file in requires file to check the middileware function
const { middileware } = require('path');
and use like this
router.get('/routename',middleware,nextfunction) //router you can choose as you like get,post,patch anything
try this out
I got this error when I omitted "req" and "res" in the function's parameters. When I added them, the error disappeared. Since I was using typescript, the first scenario looked like this:
function traceRoute(next){
console.log(routeTrace);
next();
}
Corrected to:
function traceRoute(req, res, next){
console.log(routeTrace);
next();
}
I'm having some problems using 2 middlewares inside the same function, already tried to search for all internet and didn't find a useful solution.
validator file
module.exports = {
create: async (req, res, next) => {
await celebrate(options.create)(req, res, next);
return res.status(500).json({ message: 'middleware 2'});
},
}
routes file
routes.post('/user', UserValidator.Create ,UserController.create);
The celebrate lib filters some basic validations like string lenght, null values, etc. And the celebrate() function returns another function with the (req, res, next) params.
When the celebrate returns the validation error, it stills continues to execute the code, so it tries to execute the next return and I get an error because the return has already been sent.
When using separate middlewares in the routes, it works normally:
routes.post('/user', celebrate(...), middleware2 ,UserController.create);
I also tried this way but the same thing happens, but now without an error, just returning the middleware2 result.
module.exports = {
create: async (req, res, next) => {
await celebrate(options.create)(req, res, () => {
return res.status(500).json({ message: 'middleware 2'});
});
},
Is there a way to fix this?
u should try this structure
// API
app.post('/something', Middleware.validate, Controller.create)
//Middleware
const validate = (req, res, done) => {
const errorArray = []
const body = req.body
// identifier is required, Validating as String, and length range.
if (!_.isString(body.identifier) || body.identifier.length < 2 || body.identifier.length > 10) {
errorArray.push({
field: 'identifier',
error: 70000,
message: 'Please provide only valid \'identifier\' as string, length must be between 2 and 10.'
})
}
if (!_.isEmpty(errorArray)) {
return errorArray
}
done()
}
module.exports = {
validate
}
// Controller
const create = function (req, res) {
return // your functionality
}
module.exports = {
create
}
In my POST route, im finding two documents from my database, each one with model.findOne. Then I´m trying to take from that one of it´s key/value pair and save it into a variable.
I´ve tried window.______ method, ive tried global._____, but nothing seems to work. I´ve ignored the "var" keyword, but whatever I do, I cant access these variables anywhere else.
app.post("/match", (req, res, next) => {
Team.findOne({name: req.body.team1}, (err, team) => {
if(err) {
console.log(err);
} else {
let eloOne = team.elo; // <-- here is the problem part
}
});
Team.findOne({name: req.body.team2}, (err, team2) => {
if (err) {
console.log(err)
} else {
let eloTwo = team2.elo; // <-- here is the problem part
}
});
console.log(eloOne) // <-- here i want to use the variables
console.log(eloTwo)
}); // please dont kill me for this code, I've started programing recently
Here is the code.
app.post("/match", (req, res, next) => {
Team.findOne({name: req.body.team1}, (err, team) => {
if(err) {
console.log(err);
} else {
let eloOne = team.elo; // <-- here is the problem part
Team.findOne({name: req.body.team2}, (err, team2) => {
if (err) {
console.log(err)
} else {
let eloTwo = team2.elo; // <-- here is the problem part
console.log(eloOne) // <-- here i want to use the variables
console.log(eloTwo)
res.send(' request complete')
}
});
}
});
});
I suggest to use 'async await' or promise atleast.
Use promise.all as it will be doing both the network calls in parallel, and hence increase the performance.
app.post("/match", async (req, res, next) => {
try {
const [team, team2 ] = await Promise.all([Team.findOne({name: req.body.team1}).exec(), Team.findOne({name: req.body.team2}).exec()]),
eloOne = team.elo,
eloTwo = team2.elo;
console.log(eloOne)
console.log(eloTwo)
} catch(error) {
console.log(error);
}
});
Ok so I am currently learning more node.js and decided to try out some basic middleware in a small api I created. I was wondering how I would wrap a successfull request. This is my approach.
Example Controller
exports.getTask = async function (req, res, next) {
try {
const task = await db.Task.findOne(
{
where: {
id: req.params.taskId,
userId: req.params.userId
}
});
if (task) {
req.locals.data = task;
res.status(httpStatus.OK);
next();
}
res.status(httpStatus.NOT_FOUND);
next();
} catch (err) {
next(err);
}
};
Middleware
exports.success = function(req, res, next) {
const success = res.statusCode < 400;
const successResponse = {
timestamp: new Date().toUTCString(),
success: success,
status: res.statusCode
};
if (success) {
successResponse.data = req.locals.data;
}
res.send(successResponse);
next();
};
I dont think its very good having to set req.locals.data for every requst and then calling next res.status(status) maybe I just approached the situation the wrong way?
How could you make this better?
In this case, probably using the express middleware concept (calling next()) will be an overkill.
I'd approach this by creating an abstraction for the success path. Consider something like this:
const resWithSuccess = (req, res, data) => {
res.json({
data: data,
timestamp: new Date().toUTCString(),
// success: res.statusCode < 400, // --> actually you don't need this,
// since it will always be true
// status: res.statusCode // --> or whatever else "meta" info you need
});
};
Then, as soon as you need to respond with success, go for it:
exports.getTask = async function (req, res, next) {
// .... bla bla
if (task) {
resWithSuccess(tank);
}
};
PS: ... and you can use the express middleware concept (calling next()) for the error path.