Skip to content

Commit

Permalink
fix: refactor wallet module
Browse files Browse the repository at this point in the history
  • Loading branch information
Kpoke committed Jun 5, 2022
1 parent 235c3b2 commit e87d375
Show file tree
Hide file tree
Showing 27 changed files with 584 additions and 390 deletions.
104 changes: 59 additions & 45 deletions __tests__/e2e/__tests__/wallets.test.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,70 @@
const faker = require('faker');
const { sendGetRequest, sendPostRequest, responseStatus: {OK}, assert } = require("../config");
const { getSession } = require("../libs/sessionLibrary");
const { testData } = require("../libs/bootstrap.js");
const {
sendGetRequest,
sendPostRequest,
responseStatus: { OK },
assert,
} = require('../config');
const { getSession } = require('../libs/sessionLibrary');
const { testData } = require('../libs/bootstrap.js');

let bearer = null;
const {apiKey} = testData;
const { apiKey } = testData;
const wallet = testData.wallet.name;
const {password} = testData.wallet;
const { password } = testData.wallet;
const limit = 50;
const url = `/wallets?limit=${limit}`;

describe("Wallets (Wallet API)", function () {
before(async () => {
bearer = await getSession(wallet, password);
});
it('Wallets - Returns 200 response status @wallet @regression', async () => {
const { token } = bearer;
const headers = {
'Authorization': `Bearer ${token}`,
'treetracker-api-key': apiKey,
};
const response = await sendGetRequest(url, headers);
const { status } = response;
assert.equals(status, OK, 'Response status does not equal!');
});
describe.only('Wallets (Wallet API)', function () {
before(async () => {
bearer = await getSession(wallet, password);
});
it('Wallets - Returns 200 response status @wallet @regression', async () => {
const { token } = bearer;
const headers = {
Authorization: `Bearer ${token}`,
'treetracker-api-key': apiKey,
};
const response = await sendGetRequest(url, headers);
const { status } = response;
assert.equals(status, OK, 'Response status does not equal!');
});

it('Wallets - Verify new managed wallet is created successfully @wallet @regression', async () => {
const expectedWallet = `NewWalletByAutoTool_${faker.datatype.number()}`;
let walletCreated = false;
const { token } = bearer;
const headers = {
'Authorization': `Bearer ${token}`,
'treetracker-api-key': apiKey
};
const payload = {
"wallet": expectedWallet
};
const newWalletResponse = await sendPostRequest('/wallets', headers, payload);
const {status} = newWalletResponse;
assert.equals(status, OK, 'Response status does not match!');
it('Wallets - Verify new managed wallet is created successfully @wallet @regression', async () => {
const expectedWallet = `NewWalletByAutoTool_${faker.datatype.number()}`;
let walletCreated = false;
const { token } = bearer;
const headers = {
Authorization: `Bearer ${token}`,
'treetracker-api-key': apiKey,
};
const payload = {
wallet: expectedWallet,
};
const newWalletResponse = await sendPostRequest(
'/wallets',
headers,
payload,
);
const { status } = newWalletResponse;
assert.equals(status, OK, 'Wallet could not be created');

const response = await sendGetRequest(url, headers);
const { wallets } = response.body;
assert.equals(response.status, OK, 'Response status does not match!');
const response = await sendGetRequest(url, headers);
const { wallets } = response.body;
assert.equals(response.status, OK, 'Created Wallet not found');

for (const wallet of wallets) {
if (Object.values(wallet).includes(expectedWallet)) {
walletCreated = true;
break;
}
}
for (const wallet of wallets) {
if (Object.values(wallet).includes(expectedWallet)) {
walletCreated = true;
break;
}
}

assert.equals(walletCreated, true, 'Wallet was not created!', response.body);
})
});
assert.equals(
walletCreated,
true,
'Wallet was not created!',
response.body,
);
});
});
1 change: 0 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"test-watch": "NODE_ENV=test NODE_LOG_LEVEL=info mocha -r dotenv/config dotenv_config_path=.env.test --timeout 10000 --require co-mocha -w -b --ignore './server/repositories/**/*.spec.js' './server/setup.js' './server/**/*.spec.js' './__tests__/seed.spec.js' './__tests__/supertest.js'",
"test-watch-debug": "NODE_ENV=test NODE_LOG_LEVEL=debug DOTENV_CONFIG_PATH=.env.test mocha -r dotenv/config --timeout 10000 --require co-mocha -w -b --ignore './server/repositories/**/*.spec.js' './server/setup.js' './server/**/*.spec.js' './__tests__/seed.spec.js' './__tests__/**/*.spec.js'",
"test-e2e": "NODE_TLS_REJECT_UNAUTHORIZED='0' mocha --config ./__tests__/e2e/.mocharc.js",
"test-e2e-locally": "RUN_E2E_LOCALLY=true DB_SSL=false NODE_ENV=test NODE_LOG_LEVEL=debug NODE_TLS_REJECT_UNAUTHORIZED='0' mocha --config ./__tests__/e2e/.mocharc.js ./server/setup.js",
"test-e2e-locally": "RUN_E2E_LOCALLY=true DB_SSL=false NODE_ENV=test NODE_TLS_REJECT_UNAUTHORIZED='0' mocha --config ./__tests__/e2e/.mocharc.js ./server/setup.js",
"prettier-fix": "prettier ./ --write",
"db-migrate-ci": "cd database; db-migrate up",
"start-db": "docker-compose up"
Expand All @@ -45,7 +45,6 @@
"joi": "^17.2.1",
"jsonwebtoken": "8.1.0",
"knex": "^0.21.5",
"lodash": "^4.17.21",
"loglevel": "^1.6.8",
"morgan": "^1.9.1",
"nodemon": "^2.0.4",
Expand Down
2 changes: 1 addition & 1 deletion server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ app.use(
app.use(express.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(express.json()); // parse application/json

app.use(apiKeyHandler, routes);
app.use(routes);

// Global error handler
app.use(errorHandler);
Expand Down
4 changes: 4 additions & 0 deletions server/database/Session.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ class Session {
return knex;
}

isTransactionInProgress() {
return this.thx !== undefined;
}

async beginTransaction() {
if (this.thx) {
throw new Error('Can not start transaction in transaction');
Expand Down
2 changes: 1 addition & 1 deletion server/handlers/trustHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const Joi = require('joi');
const WalletService = require('../services/WalletService');
const TrustService = require('../services/TrustService');
const Session = require('../database/Session');
const TrustRelationship = require('../models/TrustRelationship');
const TrustRelationship = require('../utils/trust-enums');

const trustGetQuerySchema = Joi.object({
state: Joi.string(),
Expand Down
76 changes: 25 additions & 51 deletions server/handlers/walletHandler.js
Original file line number Diff line number Diff line change
@@ -1,81 +1,55 @@
const Joi = require('joi');
const _ = require('lodash');
const WalletService = require('../services/WalletService');
const TokenService = require('../services/TokenService');
const TrustService = require('../services/TrustService');
const Session = require('../database/Session');

const walletGetQuerySchema = Joi.object({
limit: Joi.number().required(),
offset: Joi.number().min(1).integer(),
offset: Joi.number().integer(),
});

const walletPostSchema = Joi.object({
wallet: Joi.string().required(),
});

const walletGet = async (req, res, next) => {
const walletGet = async (req, res) => {
await walletGetQuerySchema.validateAsync(req.query, { abortEarly: false });
const walletService = new WalletService();

const { limit, offset } = req.query;
const session = new Session();
const walletService = new WalletService(session);
const loggedInWallet = await walletService.getById(res.locals.wallet_id);
const subWallets = await loggedInWallet.getSubWallets();
// at logged in wallets to list of wallets
subWallets.push(loggedInWallet);

let walletsJson = [];

const tokenService = new TokenService(session);
for (const wallet of subWallets) {
const json = await wallet.toJSON();
json.tokens_in_wallet = await tokenService.countTokenByWallet(wallet);
walletsJson.push(json);
}

const numStart = parseInt(offset);
const numLimit = parseInt(limit);
const numBegin = numStart ? numStart - 1 : 0;
const numEnd = numBegin + numLimit;
walletsJson = walletsJson.slice(numBegin, numEnd);

res.status(200).json({
wallets: walletsJson.map((wallet) =>
_.omit(wallet, ['password', 'type', 'salt']),
),
const wallets = await walletService.getAllWallets(req.wallet_id, {
limit,
offset,
});

res.status(200).json({ wallets });
};

const walletGetTrustRelationships = async (req, res, next) => {
const session = new Session();
const trustService = new TrustService(session);
const walletService = new WalletService(session);
const wallet = await walletService.getById(req.params.wallet_id);
const trust_relationships = await wallet.getTrustRelationships(
req.query.state,
req.query.type,
req.query.request_type,
);
const trust_relationships_json = [];
for (const t of trust_relationships) {
const j = await trustService.convertToResponse(t);
trust_relationships_json.push(j);
}
const walletGetTrustRelationships = async (req, res) => {
const trustService = new TrustService();
const trust_relationships = await trustService.getTrustRelationships({
walletId: req.params.wallet_id,
state: req.query.state,
type: req.query.type,
request_type: req.query.request_type,
});
res.status(200).json({
trust_relationships: trust_relationships_json,
trust_relationships,
});
};

const walletPost = async (req, res, next) => {
const walletPost = async (req, res) => {
await walletPostSchema.validateAsync(req.body, { abortEarly: false });
const session = new Session();
const walletService = new WalletService(session);
const loggedInWallet = await walletService.getById(res.locals.wallet_id);
const addedWallet = await loggedInWallet.addManagedWallet(req.body.wallet);

const walletService = new WalletService();
const wallet = await walletService.createWallet(
req.wallet_id,
req.body.wallet,
);

res.status(200).json({
wallet: addedWallet.name,
wallet,
});
};

Expand Down
49 changes: 49 additions & 0 deletions server/models/Trust.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const TrustRepository = require('../repositories/TrustRepository');

class Trust {
constructor(session) {
this.trustRepository = new TrustRepository(session);
}

/*
* Get trust relationships by filters, setting filter to undefined to allow all data
*/
async getTrustRelationships({
walletId,
state,
type,
request_type,
offset,
limit,
}) {
const filter = {
and: [
{
or: [
{
actor_wallet_id: walletId,
},
{
target_wallet_id: walletId,
},
{
originator_wallet_id: walletId,
},
],
},
],
};
if (state) {
filter.and.push({ state });
}
if (type) {
filter.and.push({ type });
}
if (request_type) {
filter.and.push({ request_type });
}
return this.trustRepository.getByFilter(filter, { offset, limit });
}
}

module.exports = Trust;
File renamed without changes.
49 changes: 0 additions & 49 deletions server/models/TrustRelationship.js

This file was deleted.

Loading

0 comments on commit e87d375

Please sign in to comment.