0

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!!

Harika Putta
  • 63
  • 1
  • 8

1 Answers1

1

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

Robert
  • 2,538
  • 1
  • 9
  • 17
  • It would be a bit faster to use `Promise.all()` to fetch the user and product concurrently. `const [user, product] = await Promise.all([ User.findOne({where: {userId}}), Product.findOne({where: {productId}}), ])` – doublesharp Oct 24 '20 at 15:42
  • @doublesharp yes. i know but if some one ask about help with this, i think is better to not complicate solution. – Robert Oct 24 '20 at 15:44
  • Makes sense, I was just adding more info in the comments if they wanted it. You do have a bug in your answer, it's missing 'await' before `Purchase.create()`. – doublesharp Oct 24 '20 at 16:11
  • @robert, Thank you for your reply. I tried it and getting the following error. Could you please help me with it? `Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().` – Harika Putta Oct 25 '20 at 18:41
  • @robert, Thanks for your constant help. But, I am getting this error now `Cannot read property 'moneyInWallet' of null` at the line `if(user && product && user.moneyInWallet > product.price * quantity).` – Harika Putta Oct 25 '20 at 19:19
  • this is not possible. if user is null then user.moneyInWallet is never checked. [read](https://stackoverflow.com/questions/5891754/javascript-conditional-order-evaluation) – Robert Oct 25 '20 at 19:28