5 Commits

7 changed files with 87 additions and 8 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
node_modules/
.env
logs/requests.log

View File

@@ -1,6 +1,6 @@
const express = require('express');
const cors = require('cors');
const { logger } = require('./util/logger');
const { logger, requestLogger } = require('./util/logger');
const routes = require('./routes');
const app = express();
@@ -9,6 +9,26 @@ app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
requestLogger.info(
{
ip: req.ip || req.connection.remoteAddress,
method: req.method,
url: req.originalUrl,
headers: req.headers,
body: req.body,
status: res.statusCode,
responseTime: `${Date.now() - start}ms`,
},
'Incoming request'
);
});
next();
});
app.use('/api', routes);
app.get('/health', (_, res) => res.send('server is healthy'));
app.use((err, _req, res, _next) => {

View File

@@ -14,7 +14,8 @@ async function login(req, res) {
const currentTime = new Date().toISOString();
try {
const user = await authService.validateUser(customerNo, password);
if (!user) return res.status(401).json({ error: 'invalid credentials' });
if (!user || !password)
return res.status(401).json({ error: 'invalid credentials' });
const token = generateToken(user.customer_no, '1d');
const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo);
await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [
@@ -34,7 +35,6 @@ async function fetchUserDetails(req, res) {
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ message: 'USER_NOT_FOUND' });
return res.json(user);
} catch (err) {
logger.error(err, 'error occured while fetching user details');
res.status(500).json({ error: 'something went wrong' });
@@ -102,4 +102,11 @@ async function setTransactionPassword(req, res) {
}
}
module.exports = { login, tpin, setTpin, setLoginPassword, setTransactionPassword,fetchUserDetails };
module.exports = {
login,
tpin,
setTpin,
setLoginPassword,
setTransactionPassword,
fetchUserDetails,
};

View File

@@ -95,6 +95,24 @@ async function getBeneficiary(req, res) {
}
}
async function deleteBeneficiary(req, res) {
const { beneficiaryAccountNo } = req.params;
try {
await beneficiaryService.deleteBeneficiary(req.user, beneficiaryAccountNo);
res.status(204).send();
} catch (error) {
if (error.message === 'ACCOUNT_NOT_FOUND') {
logger.warn(
`beneficiary ${beneficiaryAccountNo} does not exist for the customer ${req.user}`
);
return res.status(400).json({ error: 'INVALID_BENEFICIARY_ACCOUNT_NO' });
} else {
logger.error(error, 'error deleting beneficiary');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
}
async function getIfscDetails(req, res) {
const { ifscCode } = req.query;
if (!ifscCode) {
@@ -127,4 +145,5 @@ module.exports = {
addBeneficiary,
getIfscDetails,
getBeneficiary,
deleteBeneficiary,
};

View File

@@ -9,5 +9,9 @@ router.get('/validate/outside-bank', beneficiaryController.validateOutsideBank);
router.get('/ifsc-details', beneficiaryController.getIfscDetails);
router.get('/', beneficiaryController.getBeneficiary);
router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary);
router.delete(
'/:beneficiaryAccountNo',
beneficiaryController.deleteBeneficiary
);
module.exports = router;

View File

@@ -44,6 +44,16 @@ async function getSingleBeneficiary(customerNo, accountNo) {
return result.rows[0];
}
async function deleteBeneficiary(customerNo, beneficiaryAccountNo) {
const queryStr =
'DELETE FROM beneficiaries WHERE customer_no = $1 AND account_no = $2';
const result = await db.query(queryStr, [customerNo, beneficiaryAccountNo]);
if (result.rowCount == 0) {
throw new Error('ACCOUNT_NOT_FOUND');
}
return;
}
async function getAllBeneficiaries(customerNo) {
const queryStr =
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, i.bank_name, i.branch_name FROM beneficiaries b JOIN ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1';
@@ -66,4 +76,5 @@ module.exports = {
validateOutsideBank,
getAllBeneficiaries,
getSingleBeneficiary,
deleteBeneficiary,
};

View File

@@ -1,6 +1,19 @@
const pino = require('pino');
const fs = require('fs');
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const logDir = path.join(__dirname, '../..', 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const requestLoggerStream = pino.destination({
dest: path.join(logDir, 'requests.log'),
sync: false,
});
const logger = pino({
transport: isDev
? {
@@ -15,8 +28,12 @@ const logger = pino({
level: isDev ? 'debug' : 'info',
});
const requestLogger = (req, _res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
};
const requestLogger = pino(
{
level: 'info',
base: null,
},
requestLoggerStream
);
module.exports = { logger, requestLogger };