I’ve got a part of code which repeats few times in my code: The function:
exports.getCategoryProducts = (req, res) => {
db.collection("products")
.where("category", "==", req.params.category)
.limit(10)
.get()
//duplicate code starts
.then((data) => {
let products = [];
data.forEach((doc) => {
products.push({
id: doc.id,
title: doc.data().title,
category: doc.data().category,
description: doc.data().description,
image: doc.data().image,
price: doc.data().price,
rating: doc.data().rating,
});
});
return res.status(200).json(products);
})
.catch((err) => {
console.log(err);
return res.status(500).json({
message: "Something went wrong, please try again later",
});
});
//duplicate code ends
};
How can I extract the part I’ve marked and use it as a function in other API requests?
>Solution :
Create a handler which receives the data as parameter and returns the transformed data
function dataHandler(data) {
return data.map(doc => ({
id: doc.id,
title: doc.data().title,
category: doc.data().category,
description: doc.data().description,
image: doc.data().image,
price: doc.data().price,
rating: doc.data().rating,
}));
}
function getCategoryProducts((req, res) => {
db.collection("products")
.where("category", "==", req.params.category)
.limit(10)
.get()
.then(data => dataHandler(data))
.then(products => {
res.status(200).json(products);
})
.catch(e => {...});
}
And if this code is always called in the context of an express handler, you can even pass res to the dataHandler and if you are always returning the same error, you could also create an standard errorHandler
function dataHandler(data, res) {
res.status(200).json(data.map(doc => {
let dd = doc.data();
return {
id: doc.id,
title: dd.title,
category: dd.category,
description: dd.description,
image: dd.image,
price: dd.price,
rating: dd.rating,
}
}));
}
function errorHandler(err, res) {
console.log(err);
res.status(500).json({
message: "Something went wrong, please try again later",
});
}
function getCategoryProducts((req, res) => {
db.collection("products")
.where("category", "==", req.params.category)
.limit(10)
.get()
.then(data => dataHandler(data, res))
.catch(e => errorHandler(e, res));
}