gpt4 book ai didi

javascript - API -> 创建可重用函数 getAll

转载 作者:行者123 更新时间:2023-12-02 21:18:05 25 4
gpt4 key购买 nike

亲爱的,
我只是想知道是否可以创建一个以 SQL 查询作为参数并继续处理请求的函数。考虑两个函数:

async addExpense(req, res){
const addExpense ='INSERT INTO budget.expenses_category_assigned_to_user VALUES(DEFAULT, $1, $2)'

if(!req.body.name){
return res.status(400).send({message: 'Expense cannot be added. Name is missing'})
}

const queryValues = [
req.user.id,
req.body.name
]

try{
await db.query(addExpense, queryValues)
return res.status(200).json({message: 'Expense has been successfully added'})
}catch(err){
return res.status(400).send({message: err})
}
}
async addPaymentMethod(req, res){
const addQuery = 'INSERT INTO budget.payment_methods_assigned_to_user VALUES (DEFAULT, $1, $2)'

if(!req.body.name){
return res.status(400).send({message: 'Payment method has not been added'})
}

try{
const queryParams = [
req.user.id,
req.body.name
]

await db.query(addQuery, queryParams)
return res.status(200).send({message: `${req.body.name} has been added`})
}catch(err){
return res.status(400).send({message: err})
}
}

尽管存在一些差异,但它们可以轻松标准化,并且唯一可以更改的参数是 query 和 queryValues。
请您告知是否可以在 Node 和 postgres 中创建这样的函数:

foo(query, queryParams){
action
}

它将继续处理请求并可以重用于多个端点?
这个想法是避免冗余并保留 REST API 功能

最佳答案

感谢您的澄清,确实我误解了您的问题。我的想法基本上如下

  • 将查询分离成单独的
  • 根据从端点入口函数传入的参数“table”,在“addOne”函数中调用相应的查询
  • 使用“addOne”函数中定义的正确参数在端点中调用“addOne”函数

希望这能回答你的问题


async addExpense(req, res){
addOne(req, res, 'Expense')
}

async addPaymentMethod(req, res){
addOne(req, res, 'Payment method')
}

async function addOne(req, res, table) {

if(!req.body.name){
return res.status(400).send({message: 'Expense cannot be added. Name is missing'})
}

try{
switch (table) {
case 'Expense':
await addExpensesQuery(req)
break;
case 'Payment method':
await addPaymentQuery(req)
break;
default:
throw new Error('Unsupported operation')
}
return res.status(200).json({message: `${table} has been successfully added`})
}catch(err){
return res.status(400).send({message: err})
}
}

function addExpensesQuery (req) {
const addExpense ='INSERT INTO budget.expenses_category_assigned_to_user VALUES(DEFAULT, $1, $2)'
const queryValues = [
req.user.id,
req.body.name
]
return db.query(addExpense, queryValues)
}

function addPaymentQuery (req) {
const addQuery = 'INSERT INTO budget.payment_methods_assigned_to_user VALUES (DEFAULT, $1, $2)'
const queryValues = [
req.user.id,
req.body.name
]
return db.query(addQuery, queryValues)
}

关于javascript - API -> 创建可重用函数 getAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com