Ajuda - Querys no nodejs
Fala pessoal! estou com um problema nos meus treinamentos, estou tentando fazer uma requisição por query no nodejs e estou passando vários parametros.
ex: quero que verifique todas as transações de uma carteira digital por id, tipo das transações, categoria entre determinada data inicio e final.
seria algo .base/ :id / ?type=Deposito & category=2 & startdate=2022-05-20 & enddate=2022-06-20
basicamente gostaria que me retornasse a todas as transações do tipo X na carteira Y, com as categorias Z no periodo da data que solicitei.
eu fiz algo mais ou menos assim:
async reportWallet({
id, type, category, startDate, endDate,
}) {
try {
const filter = {
where: { wallet_id: id },
attributes: ['id', 'type', 'value', 'expiry_date', 'category_id', 'wallet_id'],
};
if (type !== undefined) {
filter.where.type = type;
const reportWallet = await Transaction.findAll(filter);
return reportWallet;
}
if (category !== undefined) {
filter.where.category_id = category;
const reportWallet = await Transaction.findAll(filter);
return reportWallet;
}
if (startDate !== undefined) {
filter.where.expiry_date = { [Op.and]: [{ [Op.gte]: startDate }] };
let reportAccount = await Transaction.findAll(filter);
if (endDate !== undefined) {
filter.where.expiry_date = { [Op.and]: [{ [Op.gte]: startDate }, { [Op.lte]: endDate }] };
reportAccount = await Transaction.findAll(filter);
return reportAccount;
}
return reportAccount;
}
const reportWallet = await Transaction.findAll(filter);
return reportWallet;
} catch (error) {
throw apiError404;
}
}
Gostaria de saber se tem alguma forma de arrecadar os dados sem conflitos, pois se passo + que 2 parametros ele não me retorna corretamente
A forma que você está fazendo a verificação de cada parâmetro no seu código pode levar a resultados inesperados quando mais de um parâmetro é passado.
Uma solução seria criar um objeto where com os filtros necessários de acordo com os parâmetros passados, e depois passá-lo para o método findAll. Algo mais ou menos assim:
const where = { wallet_id: id };
if (type !== undefined) {
where.type = type;
}
if (category !== undefined) {
where.category_id = category;
}
if (startDate !== undefined) {
if (endDate !== undefined) {
where.expiry_date = { [Op.and]: [{ [Op.gte]: startDate }, { [Op.lte]: endDate }] };
} else {
where.expiry_date = { [Op.gte]: startDate };
}
}
const filter = {
where,
attributes: ['id', 'type', 'value', 'expiry_date', 'category_id', 'wallet_id'],
};
const reportWallet = await Transaction.findAll(filter);
Dessa forma, apenas os filtros necessários são adicionados ao objeto where, e todos os parâmetros passados serão considerados na consulta.