-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
163 lines (140 loc) · 4.78 KB
/
app.js
File metadata and controls
163 lines (140 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Import necessary modules
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
// ✅ Import SQS utility
const { sendToSQS } = require('./utils/sqsClient');
// Create Express app
const app = express();
const PORT = process.env.PORT || 3000;
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/transactionhistory';
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('MongoDB connected');
Transaction.find({})
.then(transactions => {
console.log('Transactions:', transactions);
})
.catch(err => {
console.error('Error fetching transactions:', err);
});
})
.catch(err => {
console.error('Error connecting to MongoDB:', err);
});
// MongoDB Schema
const transactionSchema = new mongoose.Schema({
type: String,
amount: Number,
balance: Number,
timestamp: { type: Date, default: Date.now }
});
const Transaction = mongoose.model('Transaction', transactionSchema);
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/styles.css', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'styles.css'));
});
// ✅ Credit API
app.post('/credit', async (req, res) => {
const { amount } = req.body;
if (amount < 0) {
return res.status(400).send('Please enter a valid amount');
}
try {
const newTransaction = new Transaction({ type: 'Credit', amount });
await newTransaction.save();
const transactions = await Transaction.find();
const totalCredit = transactions.reduce((acc, curr) => curr.type === 'Credit' ? acc + curr.amount : acc, 0);
const totalDebit = transactions.reduce((acc, curr) => curr.type === 'Debit' ? acc + curr.amount : acc, 0);
const totalBalance = totalCredit - totalDebit;
newTransaction.balance = totalBalance;
await newTransaction.save();
// ✅ Send message to SQS
console.log('📤 Attempting to send SQS message...');
await sendToSQS({
type: 'CREDIT',
payload: {
transactionId: newTransaction._id,
amount: newTransaction.amount,
balance: newTransaction.balance,
timestamp: newTransaction.timestamp
}
});
res.send(`Credit successful. Amount: ${amount}`);
console.log(`Credit Transaction: Amount = ${amount}, New Balance = ${newTransaction.balance}`);
} catch (error) {
console.error('Credit error:', error);
res.status(500).send('Internal Server Error');
}
});
// ✅ Debit API
app.post('/debit', async (req, res) => {
const { amount } = req.body;
if (amount < 0) {
return res.status(400).send('Please enter a valid amount');
}
try {
const transactions = await Transaction.find();
const totalCredit = transactions.reduce((acc, curr) => curr.type === 'Credit' ? acc + curr.amount : acc, 0);
const totalDebit = transactions.reduce((acc, curr) => curr.type === 'Debit' ? acc + curr.amount : acc, 0);
const totalBalance = totalCredit - totalDebit;
if (amount > totalBalance) {
return res.status(400).send('Insufficient balance');
}
const newTransaction = new Transaction({ type: 'Debit', amount });
await newTransaction.save();
newTransaction.balance = totalBalance - amount;
await newTransaction.save();
// ✅ Send message to SQS
await sendToSQS({
type: 'DEBIT',
payload: {
transactionId: newTransaction._id,
amount: newTransaction.amount,
balance: newTransaction.balance,
timestamp: newTransaction.timestamp
}
});
res.send(`Debit successful. Amount: ${amount}`);
console.log(`Debit Transaction: Amount = ${amount}, New Balance = ${newTransaction.balance}`);
} catch (error) {
console.error('Debit error:', error);
res.status(500).send('Internal Server Error');
}
});
// Balance API
app.get('/balance', async (req, res) => {
try {
const transactions = await Transaction.find();
const latestTransaction = transactions[transactions.length - 1];
const balance = latestTransaction ? latestTransaction.balance : 0;
res.send(`Total Balance: ${balance}`);
} catch (error) {
res.status(500).send('Internal Server Error');
}
});
// Transaction history API
app.get('/history', async (req, res) => {
try {
const transactions = await Transaction.find().sort({ timestamp: 'desc' });
res.json(transactions);
} catch (error) {
res.status(500).send('Internal Server Error');
}
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});