在将新记录插入打字稿中的其他模型之前检查 Sequelize 模型中的值
Check values in a Sequelize models before inserting a new record to other model in typescript
我有如下三个Sequelize模型:
User (userId, userName, moneyInWallet)
Product (productId, productName, price)
Purchase (purchaseId, buyingUser, quantity, dateOfPurchase)
我现在想在打字稿中编写一个 'post' 方法,仅当 'User' 模型中用户的 'moneyInWallet' 更大时,才将记录插入 'Purchase' 模型比来自 'Product' 型号的产品的 'price' 如:
purchaseController.post('/add/',
(req: Request, res: Response) => {
/* logic here*/
})
有人可以帮我解决这个问题吗...
提前致谢!!
只需解码来自 post 请求的数据 how
然后找到用户和产品。检查您的逻辑并创建新的购买。
发回你需要的东西,通常是新物品的 id
它将是这样的:
const {User, Product, Purchase} = require("/path/to/models");
app.use(express.json()); // to decode post body json data
purchaseController.post('/add/',
async (req: Request, res: Response) => {
try{
const {
userId,
productId,
quantity,
} = req.body;
const user = await User.findOne({where: {userId}});
const product = await Product.findOne({where: {productId}})
if(user && product && user.moneyInWallet > product.price * quantity){
const {purchaseId} = await Purchase.create({
//purchaseId - should by autocreated
buyingUser: userId
quantity
// dateOfPurchase - should by autocreated
})
if(purchaseId == undefined){
res.status(500)// or some other bad code
res.send("unable to create purchase record in database")
} else {
res.json({
purchaseId
})
}
} else {
res.send("user product not finded or user don't have enough money")
}
} catch(error){
res.status(500)// or some other bad code
res.send(error.message)
}
})
我有如下三个Sequelize模型:
User (userId, userName, moneyInWallet)
Product (productId, productName, price)
Purchase (purchaseId, buyingUser, quantity, dateOfPurchase)
我现在想在打字稿中编写一个 'post' 方法,仅当 'User' 模型中用户的 'moneyInWallet' 更大时,才将记录插入 'Purchase' 模型比来自 'Product' 型号的产品的 'price' 如:
purchaseController.post('/add/',
(req: Request, res: Response) => {
/* logic here*/
})
有人可以帮我解决这个问题吗...
提前致谢!!
只需解码来自 post 请求的数据 how
然后找到用户和产品。检查您的逻辑并创建新的购买。 发回你需要的东西,通常是新物品的 id
它将是这样的:
const {User, Product, Purchase} = require("/path/to/models");
app.use(express.json()); // to decode post body json data
purchaseController.post('/add/',
async (req: Request, res: Response) => {
try{
const {
userId,
productId,
quantity,
} = req.body;
const user = await User.findOne({where: {userId}});
const product = await Product.findOne({where: {productId}})
if(user && product && user.moneyInWallet > product.price * quantity){
const {purchaseId} = await Purchase.create({
//purchaseId - should by autocreated
buyingUser: userId
quantity
// dateOfPurchase - should by autocreated
})
if(purchaseId == undefined){
res.status(500)// or some other bad code
res.send("unable to create purchase record in database")
} else {
res.json({
purchaseId
})
}
} else {
res.send("user product not finded or user don't have enough money")
}
} catch(error){
res.status(500)// or some other bad code
res.send(error.message)
}
})