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

186
Visualizações
how to optimize code like reduce code with same functionality
let response = {};
var filters = {
  topfeaturedandotherfields: req.body.topfeaturedandotherfields,
};

if (req.body.minprice && req.body.maxprice && req.body.brandName) {
  var filters = {
    $and: [
      { brandName: { $in: req.body.brandName } },
      { topfeaturedandotherfields: req.body.topfeaturedandotherfields },
      { salePrice: { $gte: req.body.minprice, $lte: req.body.maxprice } },
    ],
  };

  var result = await productService.getAllProductofhomepage(
    filters,
    req.body.ordername,
    req.body.orderby
  );
} else {
  if (req.body.minprice && req.body.maxprice) {
    var filters = {
      $and: [
        { topfeaturedandotherfields: req.body.topfeaturedandotherfields },
        { salePrice: { $gte: req.body.minprice, $lte: req.body.maxprice } },
      ],
    };

    var result = await productService.getAllProductofhomepage(
      filters,
      req.body.ordername,
      req.body.orderby
    );
  }
  if (req.body.brandName) {
    var filters = {
      $and: [
        { brandName: { $in: req.body.brandName } },
        { topfeaturedandotherfields: req.body.topfeaturedandotherfields },
      ],
    };

    var result = await productService.getAllProductofhomepage(
      filters,
      req.body.ordername,
      req.body.orderby
    );
  }
}

if (req.body.limit == true)
  var result = await productService.getAllProductofhomepagewithlimit(filters);
else if (req.body.minprice || req.body.maxprice || req.body.brandName) {
} else {
  var result = await productService.getAllProductofhomepage(
    filters,
    req.body.ordername,
    req.body.orderby
  );
}

if (result.length > 0) {
  response = {
    message: "Home page products successfully retrieved",
    error: false,
    data: result,
  };
} else {
  response = {
    message: "Faild to get products",
    error: true,
    data: {},
  };
}

res.status(200).json(response);

This code is used to filter like to see top feature and bestseller or min and max price and the brand name also in this code sort by order name which could be price or brand name or category also in ascending and descending order so now you can see this code is like if and else but I want to optimize and reduce code

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can make this query quite a lot nicer by just dynamically building the query condition instead of breaking the logic into if/else blocks:

export async function login(req: Request, res: Response): Promise<void> {
    const response = {};
    let filters = {
        topfeaturedandotherfields: req.body.topfeaturedandotherfields,
    };

    if (req.body.minprice || req.body.maxprice) {
        const saleCond = { };
        if (req.body.minprice) {
            saleCond.$gte = req.body.minprice;
        }
        if (req.body.maxprice) {
            saleCond.$lte = req.body.maxprice;
        }
        filters.salePrice = saleCond
    }

    if (req.body.brandName) {
        filters.brandName = {$in: req.body.brandName}
    }

    let result = [];
    if (req.body.limit == true) {
        result = await productService.getAllProductofhomepagewithlimit(filters)
    } else {
        result = await productService.getAllProductofhomepage(filters, req.body.ordername, req.body.orderby);
    }

    res.status(200).json({
        message: result.length ? 'Home page products successfully retrieved' : 'Failed to get products',
        error: result.length === 0,
        data: result,
    });
}

Not only is this much clearer we only removed a redundant DB call that was made in the process.

over 4 years ago · Santiago Trujillo 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