Harika Putta
Harika Putta

Reputation: 63

Check values in a Sequelize models before inserting a new record to other model in typescript

I have three Sequelize models as follows:

User (userId, userName, moneyInWallet)
Product (productId, productName, price)
Purchase (purchaseId, buyingUser, quantity, dateOfPurchase)

I now wanted to write a 'post' method in typescript to insert a record into 'Purchase' model only if the 'moneyInWallet' of a user in 'User' model is greater than 'price' of the product from 'Product' model like:

purchaseController.post('/add/',
    (req: Request, res: Response) => {
/* logic here*/
})

Can someone please help me with this...

Thanks in advance!!

Upvotes: 0

Views: 321

Answers (1)

Robert
Robert

Reputation: 2763

just decode your data from post req how

then find user and product. check your logic and create new Purchase. send back what you need usually id of new item

it will be something like this:


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)
      }
})

Upvotes: 1

Related Questions