Effective loan processing code in node.js
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const app = express();
app.use(express.json());
const loans = {}; // In-memory storage
// Create a loan
app.post('/loans', (req, res) => {
const { borrower, principal, annualInterestRate, termMonths } = req.body;
if (!borrower || !principal || !annualInterestRate || !termMonths) {
return res.status(400).json({ error: 'Missing required fields' });
}
const id = uuidv4();
const loan = {
id,
borrower,
principal,
annualInterestRate,
termMonths,
createdAt: new Date()
};
loans[id] = loan;
res.status(201).json(loan);
});
// Get loan details
app.get('/loans/:id', (req, res) => {
const loan = loans[req.params.id];
if (!loan) {
return res.status(404).json({ error: 'Loan not found' });
}
res.json(loan);
});
// Calculate and return repayment schedule
app.get('/loans/:id/schedule', (req, res) => {
const loan = loans[req.params.id];
if (!loan) {
return res.status(404).json({ error: 'Loan not found' });
}
const P = loan.principal;
const r = loan.annualInterestRate / 100 / 12;
const n = loan.termMonths;
const monthlyPayment = r === 0
? P / n
: P * r * Math.pow(1 + r, n) / (Math.pow(1 + r, n) - 1);
let balance = P;
const schedule = [];
for (let month = 1; month <= n; month++) {
const interest = balance * r;
const principal = monthlyPayment - interest;
balance -= principal;
schedule.push({
month,
payment: +monthlyPayment.toFixed(2),
principal: +principal.toFixed(2),
interest: +interest.toFixed(2),
balance: +Math.max(balance, 0).toFixed(2)
});
}
res.json(schedule);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Loan API running on port ${PORT}`);
});
A loan request
{
"borrower": "Alice",
"principal": 10000,
"annualInterestRate": 5,
"termMonths": 12
}
Top comments (0)