我正在用Express.js制作REST api我有以下快车路线:
/api/customer
我在路由中添加了多个查询参数,如下所示:
/api/customer?name=jake
/api/customer?country=america
/api/customer?name=jake&country=america
/api/customer?name=jake&limit=10
在我的控制器中,我用If来处理所有这些并且有很多情况我觉得这个方法不能扩展,有没有更好的方法来处理这个?
这是我的控制器的代码,我使用Sequelize来查询数据库:
async function getAllCustomer(queryLimit, page) {
const customers = await Customer.findAll({
limit: queryLimit ? parseInt(queryLimit) : null,
offset: page ? parseInt(queryLimit) * parseInt(page) : null
});
return customers;
}
async function getCustomerByFirstName(name, queryLimit, page) {
return await Customer.findAll({
where: {
firstName: name,
}
})
}
async function getCustomerByAddress(address) {
return await Customer.findAll({
where: {
customerAddress: address
}
})
}
async function getCustomerByNameAddress(name, address) {
return await Customer.findAll({
where: {
[Op.and]: [
{firstName: name},
{customerAddress: address}
]
}
})
}
async function getCustomer(req, res) {
const page = req.query.page;
const queryLimit = req.query.limit;
const name = req.query.name;
const address = req.query.address;
let customers;
/* User want to find first names */
if (name && !address) {
const names = name.split(",")
customers = await getCustomerByFirstName(names, queryLimit, page)
res.status(200).send(customers)
return;
}
/* User want to find addresses */
if (!name && address) {
const addresses = address.split(",")
customers = await getCustomerByAddress(addresses, queryLimit, page)
res.status(200).send(customers)
return;
}
/* User want to mix both */
if (name && address) {
const names = name.split(",")
const addresses = address.split(",")
customers = await getCustomerByNameAddress(names, addresses, queryLimit, page)
res.status(200).send(customers)
return;
}
if (!name && !address) {
customers = await getAllCustomer(queryLimit, page)
res.status(200).send(customers)
return;
}
}
你可以这样做:
async function getCustomer(req, res) {
const page = req.query.page;
const queryLimit = req.query.limit;
const name = req.query.name;
const address = req.query.address;
let query = { };
if(name) {
query.firstName = name;
}
if(address) {
query.address = address;
}
let customers = await getCustomers(query, queryLimit, page);
res.status(200).send(customers)
return;
}
async function getCustomers(query, queryLimit, page) {
const customers = await Customer.findAll({
where: query,
limit: queryLimit ? parseInt(queryLimit) : null,
offset: page ? parseInt(queryLimit) * parseInt(page) : null
});
return customers;
}
BTW,在你的代码中,getCustomerByFirstName
,getCustomerByAddress
和getCustomerByNameAddress
函数期望接收name
和address
作为字符串参数,但是你传递的是names
和addresses
数组。这可能会导致错误…