Skip to content

Commit

Permalink
Feat: Model Fix, Fetch Transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
ubongedem78 committed Jan 17, 2024
1 parent 8b34d80 commit 5f7dd14
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 2 deletions.
18 changes: 18 additions & 0 deletions src/controllers/transaction.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { fetUserTransactions } = require("../utils/transaction.Util");

const getAllUserTransactions = async (req, res, next) => {
const { userId } = req.params;
try {
const transactions = await fetUserTransactions(userId);

return res.status(200).json({
msg: "Transactions fetched successfully",
transactions,
});
} catch (error) {
console.log(error);
next();
}
};

module.exports = { getAllUserTransactions };
6 changes: 4 additions & 2 deletions src/model/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,11 @@ const Transaction = sequelize.define("Transaction", {
},
creditWalletId: {
type: UUID,
allowNull: false,
allowNull: true,
},
debitWalletId: {
type: UUID,
allowNull: true,
},
});

Expand All @@ -192,7 +193,8 @@ User.prototype.compareTransactionPin = async function (transactionPin) {
return isMatch;
};

Wallet.belongsTo(User, { foreignKey: "userId", onDelete: "cascade" });
User.hasOne(Wallet, { foreignKey: "userId" });
Wallet.belongsTo(User, { foreignKey: "userId" });
Transaction.belongsTo(Wallet, {
as: "creditWallet",
foreignKey: "creditWalletId",
Expand Down
5 changes: 5 additions & 0 deletions src/routes/transaction.route.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
const express = require("express");
const router = express.Router();
const {
getAllUserTransactions,
} = require("../controllers/transaction.controller");

router.get("/transactions/:userId", getAllUserTransactions);

module.exports = router;
32 changes: 32 additions & 0 deletions src/utils/transaction.Util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { User, Transaction, Wallet } = require("../model/model");
const { Op } = require("sequelize");
const { NotFoundError } = require("../errors");
async function fetUserTransactions(userId) {
const user = await User.findByPk(userId, {
include: {
model: Wallet,
attributes: ["id"],
},
});

if (!user) {
throw new NotFoundError("User not found");
}

const transactions = await Transaction.findAll({
where: {
[Op.or]: [
{
creditWalletId: user.Wallet.id,
},
{
debitWalletId: user.Wallet.id,
},
],
},
});
console.log(transactions);
return transactions;
}

module.exports = { fetUserTransactions };

0 comments on commit 5f7dd14

Please sign in to comment.