Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parse part of .then() as a other function

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading