我有一部分代碼在我的代碼中重復了幾次:函式:
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
};
如何提取我標記的部分并將其用作其他 API 請求中的函式?
uj5u.com熱心網友回復:
創建一個處理程式,它接收資料作為引數并回傳轉換后的資料
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 => {...});
}
如果始終在快速處理程式的背景關系中呼叫此代碼,您甚至可以傳遞res給dataHandler并且如果您總是回傳相同的錯誤,您還可以創建一個標準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(e, 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418652.html
標籤:
