diff --git a/app.js b/app.js index da217be..af317a8 100644 --- a/app.js +++ b/app.js @@ -7,10 +7,12 @@ const { creditAccount, debitAccount } = require('./helpers/transactions'); dotenv.config(); + /** * @param {string} username username of the user * @param {string} password password of the user */ + async function createUser(username, password) { const schema = joi.object({ username: joi.string().required(), @@ -26,17 +28,21 @@ async function createUser(username, password) { const t = await models.sequelize.transaction(); try { + const existingUser = await models.users.findOne({ where: { username } }, { transaction: t }); if (existingUser) { return { success: false, error: 'Account already exists', + }; + } const user = await models.users.create({ username, password: bcrypt.hashSync(password, bcrypt.genSaltSync(10)), - }, { + }, + { transaction: t, }); @@ -52,9 +58,11 @@ async function createUser(username, password) { success: true, message: 'User account created', }; + } catch (error) { await t.rollback(); - return { + return + { success: false, error: 'Internal server error', }; @@ -69,7 +77,8 @@ async function deposit(account_id, amount) { const schema = joi.object({ account_id: joi.number().required(), amount: joi.number().min(1).required(), - }); + } + ); const validation = schema.validate({ account_id, amount }); if (validation.error) { return { @@ -84,7 +93,8 @@ async function deposit(account_id, amount) { amount, purpose: 'deposit', t, - }); + } + ); if (!creditResult.success) { await t.rollback(); @@ -113,7 +123,8 @@ async function withdraw(account_id, amount) { const schema = joi.object({ account_id: joi.number().required(), amount: joi.number().min(1).required(), - }); + } + ); const validation = schema.validate({ account_id, amount }); if (validation.error) { return {