Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

59
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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));
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda