Skip to content

Commit

Permalink
chore(controller):integrate account controller with db
Browse files Browse the repository at this point in the history
Connect account controller and existing account routes to read values from the database

[Finishes #165424094]
  • Loading branch information
tolulope-od committed Apr 17, 2019
1 parent 5b893cd commit 4fc701f
Show file tree
Hide file tree
Showing 6 changed files with 303 additions and 134 deletions.
127 changes: 127 additions & 0 deletions server/controllers/AccountController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import dotenv from 'dotenv';
import { isEmpty } from '../validation/authValidation';
import Model from '../db';

dotenv.config();

const accounts = new Model(`accounts`);

export default class AccountController {
/**
* @description Create a new account
* @param {Object} req The request object
* @param {Object} res The response object
* @route POST /api/v1/accounts
* @returns {Object} status code, data and message properties
* @access private Client only
*/
static async createAccount(req, res) {
const { type } = req.body;
const { id, firstName, lastName, email } = req.decoded;
if (req.decoded.type === 'client') {
const accountNumber = Math.floor(Math.random() * 10 ** 10);
const newAccount = await accounts.create(
['accountNumber', 'owner', 'ownerEmail', 'type', 'status', 'balance'],
[`${accountNumber}, ${id}, '${email}', '${type}', 'active', 0.0`]
);
const data = {
accountNumber: newAccount[0].accountnumber,
firstName,
lastName,
email,
type: newAccount[0].type,
openingBalance: newAccount[0].balance
};
return res.status(201).json({
status: 201,
data: [data],
message: 'Account created successfully'
});
}
return res.status(401).json({
status: 401,
error: 'Only clients can create accounts'
});
}

/**
* @description Edit an account status
* @param {Object} req The request object
* @param {Object} res The response object
* @route PATCH /api/v1/accounts/:accountNumber
* @returns {Object} status code, data and message properties
* @access private Staff only
*/
static async editAccountStatus(req, res) {
const { accountNumber } = req.params;
const { status } = req.body;
if (req.decoded.type !== 'staff') {
return res.status(401).json({
status: 401,
error: 'You are not authorized to carry out that action'
});
}
const accountToEdit = await accounts.select(
['*'],
[`accountnumber=${parseInt(accountNumber, 10)}`]
);
if (isEmpty(accountToEdit)) {
return res.status(404).json({
status: 404,
error: 'Account does not exist'
});
}

if (accountToEdit[0].status === status) {
return res.status(409).json({
status: 409,
error: `Account is already ${status}`
});
}

accounts.update([`status='${status}'`], [`accountnumber=${parseInt(accountNumber, 10)}`]);
const data = {
accountNumber: accountToEdit[0].accountnumber,
status,
owner: accountToEdit[0].owner,
ownerEmail: accountToEdit[0].owneremail
};
return res.status(200).json({
status: 200,
data: [data]
});
}

/**
* @description Delete a single account
* @param {Object} req The request object
* @param {Object} res The response object
* @route Get /api/v1/accounts/:accountNumber
* @returns {Object} status code, data and message properties
* @access private Staff only
*/
static async deleteAccount(req, res) {
const { accountNumber } = req.params;
if (req.decoded.type === 'staff') {
const accountToDelete = await accounts.select(
['*'],
[`accountnumber=${parseInt(accountNumber, 10)}`]
);
if (isEmpty(accountToDelete)) {
return res.status(404).json({
status: 404,
error: 'Account does not exist'
});
}
await accounts.delete(['*'], [`accountnumber=${accountToDelete[0].accountnumber}`]);
return res.status(200).json({
status: 200,
message: 'Account deleted successfully'
});
}
return res.status(401).json({
status: 401,
error: 'You are not authorized to delete an account'
});
}
}
24 changes: 24 additions & 0 deletions server/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,30 @@ export default class Model {
}
}

async update(params, constraints) {
try {
const result = await this.pool.query(
`UPDATE ${this.table} SET ${params} WHERE ${constraints}`
);
debug(result.rowCount);
return result.rowCount;
} catch (err) {
return debug(err.message);
}
}

async delete(params, constraint) {
try {
const result = await this.pool.query(
`DELETE FROM ${this.table} ${params} WHERE ${constraint}`
);
debug(result);
return result;
} catch (err) {
return debug(err.message);
}
}

static initConn() {
const { USER, HOST, DATABASE, PASSWORD, DB_PORT } = process.env;
const poolSettings = {
Expand Down
9 changes: 5 additions & 4 deletions server/db/seeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const createTable = async () => {
type VARCHAR NOT NULL,
status VARCHAR NOT NULL,
balance NUMERIC NOT NULL,
ownerEmail TEXT NOT NULL,
createdOn TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(owner) REFERENCES users(id) ON DELETE CASCADE
);
Expand All @@ -72,10 +73,10 @@ const createTable = async () => {
VALUES('olegunnar@manutd.com', 'Ole', 'Solksjaer', '${userPass}', 'Old Trafford, Manchester', '/uploads/avatar/ole.jpg', 08739084, 'client', false);
INSERT INTO users (email, firstName, lastName, password, address, avatar, phoneNumber, type, isAdmin)
VALUES('kyloren@vader.com', 'Kylo', 'Ren', '${adminPass}', 'Tatooine, Planet C53', '/uploads/avatar/kylo.jpg', 08939084, 'staff', true);
INSERT INTO accounts (accountNumber, owner, type, status, balance)
VALUES(5563847290, 2, 'current', 'active', 349876358.08);
INSERT INTO accounts (accountNumber, owner, type, status, balance)
VALUES(8897654324, 3, 'savings', 'dormant', 7665435.97);
INSERT INTO accounts (accountNumber, owner, ownerEmail, type, status, balance)
VALUES(5563847290, 2, 'thor@avengers.com', 'current', 'active', 349876358.08);
INSERT INTO accounts (accountNumber, owner, ownerEmail, type, status, balance)
VALUES(8897654324, 3, 'olegunnar@manutd.com', 'savings', 'dormant', 7665435.97);
INSERT INTO transactions (type, accountNumber, owner, cashier, amount, oldBalance, newBalance)
VALUES('credit', 8897654324, 3, 4, 400500.0, 7264935.97, 7665435.97);
INSERT INTO transactions (type, accountNumber, owner, cashier, amount, oldBalance, newBalance)
Expand Down
Loading

0 comments on commit 4fc701f

Please sign in to comment.