New endpoints
Course: PayTM project - chapter 13
Here, you’ll be writing a bunch of APIs for the core user balances. There are 2 endpoints that we need to implement
1. An endpoint for user to get their balance.
Section titled “1. An endpoint for user to get their balance.”Method: GET Route: /api/v1/account/balance
Response:
Status code - 200
{ balance: 100}Solution
router.get("/balance", authMiddleware, async (req, res) => { const account = await Account.findOne({ userId: req.userId });
res.json({ balance: account.balance })});2. An endpoint for user to transfer money to another account
Section titled “2. An endpoint for user to transfer money to another account”Method: POST Route: /api/v1/account/transfer Body
{ to: string, amount: number}Response:
Status code - 200
{ message: "Transfer successful"}Status code - 400
{ message: "Insufficient balance"}Status code - 400
{ message: "Invalid account"}Bad Solution (doesn’t use transactions)
router.post("/transfer", authMiddleware, async (req, res) => { const { amount, to } = req.body;
const account = await Account.findOne({ userId: req.userId });
if (account.balance < amount) { return res.status(400).json({ message: "Insufficient balance" }) }
const toAccount = await Account.findOne({ userId: to });
if (!toAccount) { return res.status(400).json({ message: "Invalid account" }) }
await Account.updateOne({ userId: req.userId }, { $inc: { balance: -amount } })
await Account.updateOne({ userId: to }, { $inc: { balance: amount } })
res.json({ message: "Transfer successful" })});Good solution (uses txns in db
$1bProblems you might run into
If you run into the problem mentioned above, feel free to proceed with the bad solution. Although, the answer to the issue is in the third toggle above
Final Solution
Section titled “Final Solution”Finally, the account.js file should look like this
$1dExperiment to ensure transactions are working as expected -
Section titled “Experiment to ensure transactions are working as expected -”Try running this code locally. It calls transfer twice on the same account ~almost concurrently
Code
$1fError
