diff --git a/__tests__/bundle-transfer-create-accept.spec.js b/__tests__/bundle-transfer-create-accept.spec.js index 5f05396a..1d6b5dac 100644 --- a/__tests__/bundle-transfer-create-accept.spec.js +++ b/__tests__/bundle-transfer-create-accept.spec.js @@ -81,7 +81,7 @@ describe('Create and accept a bundle transfer', () => { .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body.transfers).lengthOf(1); - pendingTransfer = res.body.transfers[0]; + [pendingTransfer] = res.body.transfers; expect(pendingTransfer) .property('destination_wallet') .eq(seed.walletB.name); diff --git a/__tests__/bundle-transfer-decline.spec.js b/__tests__/bundle-transfer-decline.spec.js index dd803a9c..34598fee 100644 --- a/__tests__/bundle-transfer-decline.spec.js +++ b/__tests__/bundle-transfer-decline.spec.js @@ -81,7 +81,7 @@ describe('Create and decline a bundle transfer', () => { .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body.transfers).lengthOf(1); - pendingTransfer = res.body.transfers[0]; + [pendingTransfer] = res.body.transfers; expect(pendingTransfer) .property('destination_wallet') .eq(seed.walletB.name); diff --git a/__tests__/e2e/__tests__/sendTokens/managingWalletMovesTokensBetweenWallets.test.js b/__tests__/e2e/__tests__/sendTokens/managingWalletMovesTokensBetweenWallets.test.js index e3bb39a2..058c484c 100644 --- a/__tests__/e2e/__tests__/sendTokens/managingWalletMovesTokensBetweenWallets.test.js +++ b/__tests__/e2e/__tests__/sendTokens/managingWalletMovesTokensBetweenWallets.test.js @@ -34,13 +34,13 @@ const headers = (token) => { }; }; -const payload = (walletA, walletB) => { +const payload = (senderWallet, receiverWalletB) => { return { bundle: { bundle_size: 1, }, - sender_wallet: walletA, - receiver_wallet: walletB, + sender_wallet: senderWallet, + receiver_wallet: receiverWalletB, claim: false, }; }; diff --git a/__tests__/e2e/__tests__/wallets.test.js b/__tests__/e2e/__tests__/wallets.test.js index e81f73ab..bc058a1b 100644 --- a/__tests__/e2e/__tests__/wallets.test.js +++ b/__tests__/e2e/__tests__/wallets.test.js @@ -53,8 +53,9 @@ describe('Wallets (Wallet API)', function () { const { wallets } = response.body; assert.equals(response.status, OK, 'Created Wallet not found'); - for (const wallet of wallets) { - if (Object.values(wallet).includes(expectedWallet)) { + for (let i = 0; i < wallets.length; i += 1) { + const w = wallets[i]; + if (Object.values(w).includes(expectedWallet)) { walletCreated = true; break; } diff --git a/__tests__/e2e/config.js b/__tests__/e2e/config.js index 854faf47..741ac4c4 100644 --- a/__tests__/e2e/config.js +++ b/__tests__/e2e/config.js @@ -1,11 +1,13 @@ require('dotenv').config(); +const supertest = require('supertest'); +const { expect } = require('chai'); +const responseStatus = require('http-status-codes'); const server = process.env.RUN_E2E_LOCALLY ? require('../../server/app') : `https://${process.env.ENVIRONMENT}-k8s.treetracker.org/wallet`; -const request = require('supertest')(server); -const { expect } = require('chai'); -const responseStatus = require('http-status-codes'); + +const request = supertest(server); const assert = require('./libs/assertionLibrary.js'); const seed = require('./database/seed.js'); diff --git a/__tests__/e2e/database/seed.js b/__tests__/e2e/database/seed.js index 8b75572f..34123d6a 100644 --- a/__tests__/e2e/database/seed.js +++ b/__tests__/e2e/database/seed.js @@ -1,70 +1,71 @@ /* * seed data to DB for testing */ -const uuid = require("uuid"); +const log = require('loglevel'); +const uuid = require('uuid'); const { v4: uuidV4 } = require('uuid'); -const knex = require("./knex"); +const knex = require('./knex'); -const apiKey = "FORTESTFORTESTFORTESTFORTESTFORTEST"; +const apiKey = 'FORTESTFORTESTFORTESTFORTESTFORTEST'; const wallet = { id: uuid.v4(), - name: "walletA", - password: "test1234", + name: 'walletA', + password: 'test1234', passwordHash: - "31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1", - salt: "TnDe2LDPS7VaPD9GQWL3fhG4jk194nde", - type: "p", + '31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1', + salt: 'TnDe2LDPS7VaPD9GQWL3fhG4jk194nde', + type: 'p', }; const walletB = { id: uuid.v4(), - name: "walletB", - password: "test1234", + name: 'walletB', + password: 'test1234', passwordHash: - "31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1", - salt: "TnDe2LDPS7VaPD9GQWL3fhG4jk194nde", - type: "p", + '31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1', + salt: 'TnDe2LDPS7VaPD9GQWL3fhG4jk194nde', + type: 'p', }; const walletC = { id: uuid.v4(), - name: "walletC", - password: "test1234", + name: 'walletC', + password: 'test1234', passwordHash: - "31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1", - salt: "TnDe2LDPS7VaPD9GQWL3fhG4jk194nde", - type: "p", + '31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1', + salt: 'TnDe2LDPS7VaPD9GQWL3fhG4jk194nde', + type: 'p', }; const walletTrustD = { id: uuid.v4(), - name: "walletD", - password: "test1234", + name: 'walletD', + password: 'test1234', passwordHash: - "31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1", - salt: "TnDe2LDPS7VaPD9GQWL3fhG4jk194nde", - type: "p", + '31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1', + salt: 'TnDe2LDPS7VaPD9GQWL3fhG4jk194nde', + type: 'p', }; const walletTrustE = { id: uuid.v4(), - name: "walletE", - password: "test1234", + name: 'walletE', + password: 'test1234', passwordHash: - "31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1", - salt: "TnDe2LDPS7VaPD9GQWL3fhG4jk194nde", - type: "p", + '31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1', + salt: 'TnDe2LDPS7VaPD9GQWL3fhG4jk194nde', + type: 'p', }; const managingWallet = { id: uuid.v4(), - name: "managingWallet", - password: "test1234", + name: 'managingWallet', + password: 'test1234', passwordHash: - "31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1", - salt: "TnDe2LDPS7VaPD9GQWL3fhG4jk194nde", - type: "p", + '31dd4fe716e1a908f0e9612c1a0e92bfdd9f66e75ae12244b4ee8309d5b869d435182f5848b67177aa17a05f9306e23c10ba41675933e2cb20c66f1b009570c1', + salt: 'TnDe2LDPS7VaPD9GQWL3fhG4jk194nde', + type: 'p', }; const capture = { @@ -77,9 +78,9 @@ const token = { async function createTokens(targetWallet, numberOfTokens) { const tokenIds = []; - for(let i = 0; i < numberOfTokens; i++) { + for (let i = 0; i < numberOfTokens; i += 1) { const tokenId = uuidV4(); - await knex("token").insert({ + await knex('token').insert({ id: tokenId, capture_id: uuidV4(), wallet_id: targetWallet, @@ -90,17 +91,17 @@ async function createTokens(targetWallet, numberOfTokens) { } async function seed() { - console.log("seed api key"); - await knex("api_key").insert({ + log.log('seed api key'); + await knex('api_key').insert({ key: apiKey, tree_token_api_access: true, - hash: "test", - salt: "test", - name: "test", + hash: 'test', + salt: 'test', + name: 'test', }); // wallet - await knex("wallet").insert({ + await knex('wallet').insert({ id: wallet.id, name: wallet.name, password: wallet.passwordHash, @@ -108,7 +109,7 @@ async function seed() { }); // walletB - await knex("wallet").insert({ + await knex('wallet').insert({ id: walletB.id, name: walletB.name, password: walletB.passwordHash, @@ -116,7 +117,7 @@ async function seed() { }); // walletC - await knex("wallet").insert({ + await knex('wallet').insert({ id: walletC.id, name: walletC.name, password: walletC.passwordHash, @@ -124,7 +125,7 @@ async function seed() { }); // walletD - await knex("wallet").insert({ + await knex('wallet').insert({ id: walletTrustD.id, name: walletTrustD.name, password: walletTrustD.passwordHash, @@ -132,7 +133,7 @@ async function seed() { }); // walletE - await knex("wallet").insert({ + await knex('wallet').insert({ id: walletTrustE.id, name: walletTrustE.name, password: walletTrustE.passwordHash, @@ -140,7 +141,7 @@ async function seed() { }); // managing wallet - await knex("wallet").insert({ + await knex('wallet').insert({ id: managingWallet.id, name: managingWallet.name, password: managingWallet.passwordHash, @@ -148,12 +149,12 @@ async function seed() { }); // token - console.log("seed token"); + log.log('seed token'); await createTokens(wallet.id, 5); await createTokens(walletTrustD.id, 2); - await knex("token").insert({ + await knex('token').insert({ id: token.id, capture_id: capture.id, wallet_id: wallet.id, @@ -161,30 +162,36 @@ async function seed() { } async function clear(wallets) { - console.log("clearing db"); - - await knex("api_key").where("key", apiKey).del(); - - for (const wallet of wallets) { - await knex("transaction").where("source_wallet_id", wallet).del(); - } - - for (const wallet of wallets) { - await knex("token").where("wallet_id", wallet).del(); - } - - await knex("wallet").where("name", wallet.name).del(); - await knex("wallet").where("name", walletB.name).del(); - await knex("wallet").where("name", walletC.name).del(); - await knex("wallet").where("name", walletTrustD.name).del(); - await knex("wallet").where("name", walletTrustE.name).del(); - await knex("wallet").where("name", managingWallet.name).del(); - - for (const wallet of wallets) { - await knex("wallet_trust").where("actor_wallet_id", wallet).del(); - } - - console.log("done clearing db"); + log.log('clearing db'); + + await knex('api_key').where('key', apiKey).del(); + + await Promise.all( + wallets.map(async (w) => { + await knex('transaction').where('source_wallet_id', w).del(); + }), + ); + + await Promise.all( + wallets.map(async (w) => { + await knex('token').where('wallet_id', w).del(); + }), + ); + + await knex('wallet').where('name', wallet.name).del(); + await knex('wallet').where('name', walletB.name).del(); + await knex('wallet').where('name', walletC.name).del(); + await knex('wallet').where('name', walletTrustD.name).del(); + await knex('wallet').where('name', walletTrustE.name).del(); + await knex('wallet').where('name', managingWallet.name).del(); + + await Promise.all( + wallets.map(async (w) => { + await knex('wallet_trust').where('actor_wallet_id', w).del(); + }), + ); + + log.log('done clearing db'); } module.exports = { @@ -198,5 +205,5 @@ module.exports = { walletTrustE, managingWallet, capture, - token + token, }; diff --git a/__tests__/e2e/database/seed.test.js b/__tests__/e2e/database/seed.test.js index a6e6f78d..5cd2ab13 100644 --- a/__tests__/e2e/database/seed.test.js +++ b/__tests__/e2e/database/seed.test.js @@ -1,68 +1,68 @@ -const { expect } = require("chai"); -const seed = require("./seed"); -const knex = require("./knex"); +const { expect } = require('chai'); +const seed = require('./seed'); +const knex = require('./knex'); -describe("Seed data into DB", () => { +describe('Seed data into DB', () => { let token; - it("Should have api key", async () => { - const r = await knex.table("api_key").select().where("key", seed.apiKey); + it('Should have api key', async () => { + const r = await knex.table('api_key').select().where('key', seed.apiKey); expect(r).lengthOf(1); }); - it("Should find a token in walletA", async () => { - expect(seed.token).to.have.property("id"); - const r = await knex.table("token").select().where("id", seed.token.id); + it('Should find a token in walletA', async () => { + expect(seed.token).to.have.property('id'); + const r = await knex.table('token').select().where('id', seed.token.id); expect(r).lengthOf(1); - token = r[0]; - expect(token).to.have.property("wallet_id").to.equal(seed.wallet.id); + [token] = r; + expect(token).to.have.property('wallet_id').to.equal(seed.wallet.id); }); - it("walletA exists", async () => { + it('walletA exists', async () => { const r = await knex - .table("wallet") + .table('wallet') .select() - .where("name", seed.wallet.name); + .where('name', seed.wallet.name); expect(r).lengthOf(1); }); - it("walletB exists", async () => { + it('walletB exists', async () => { const r = await knex - .table("wallet") - .select() - .where("name", seed.walletB.name); + .table('wallet') + .select() + .where('name', seed.walletB.name); expect(r).lengthOf(1); }); - it("walletC exists", async () => { + it('walletC exists', async () => { const r = await knex - .table("wallet") - .select() - .where("name", seed.walletC.name); + .table('wallet') + .select() + .where('name', seed.walletC.name); expect(r).lengthOf(1); }); - it("Future trust walletD exists", async () => { + it('Future trust walletD exists', async () => { const r = await knex - .table("wallet") - .select() - .where("name", seed.walletTrustD.name); + .table('wallet') + .select() + .where('name', seed.walletTrustD.name); expect(r).lengthOf(1); }); - it("Future trust walletE exists", async () => { + it('Future trust walletE exists', async () => { const r = await knex - .table("wallet") - .select() - .where("name", seed.walletTrustE.name); + .table('wallet') + .select() + .where('name', seed.walletTrustE.name); expect(r).lengthOf(1); }); - it("Future managing walletF exists", async () => { + it('Future managing walletF exists', async () => { const r = await knex - .table("wallet") - .select() - .where("name", seed.managingWallet.name); + .table('wallet') + .select() + .where('name', seed.managingWallet.name); expect(r).lengthOf(1); }); -}); \ No newline at end of file +}); diff --git a/__tests__/e2e/helpers/tokenActionsHelper.js b/__tests__/e2e/helpers/tokenActionsHelper.js index 62f5777c..26930ea4 100644 --- a/__tests__/e2e/helpers/tokenActionsHelper.js +++ b/__tests__/e2e/helpers/tokenActionsHelper.js @@ -1,6 +1,6 @@ -const {expect} = require("chai"); -const {ACCEPTED} = require("http-status-codes"); -const assert = require("../libs/assertionLibrary.js"); +const { expect } = require('chai'); +const { ACCEPTED } = require('http-status-codes'); +const assert = require('../libs/assertionLibrary.js'); /** * Assert send tokens response body to have expected properties and correct wallet names are included @@ -9,11 +9,18 @@ const assert = require("../libs/assertionLibrary.js"); * @param {String} receiverWallet */ function assertSendTokensBody(response, senderWallet, receiverWallet) { - assert.equals(response.status, ACCEPTED, 'Response status does not equal!', response.body); - expect(response.body).to.have.property("id"); - expect(response.body).to.have.property("active").eq(true); - expect(response.body).to.have.property("originating_wallet").eq(senderWallet); - expect(response.body).to.have.property("destination_wallet").eq(receiverWallet); + assert.equals( + response.status, + ACCEPTED, + 'Response status does not equal!', + response.body, + ); + expect(response.body).to.have.property('id'); + expect(response.body).to.have.property('active').eq(true); + expect(response.body).to.have.property('originating_wallet').eq(senderWallet); + expect(response.body) + .to.have.property('destination_wallet') + .eq(receiverWallet); } /** @@ -22,8 +29,8 @@ function assertSendTokensBody(response, senderWallet, receiverWallet) { * @param {String} senderWallet * @param {String} receiverWallet */ -function assertTransferCompletedBody(response, senderWallet, receiverWallet) { - expect(response.body).to.have.property("state").eq("completed"); +function assertTransferCompletedBody(response, _senderWallet, _receiverWallet) { + expect(response.body).to.have.property('state').eq('completed'); } /** @@ -32,12 +39,12 @@ function assertTransferCompletedBody(response, senderWallet, receiverWallet) { * @param {String} senderWallet * @param {String} receiverWallet */ -function assertTransferDeclinedBody(response, senderWallet, receiverWallet) { - expect(response.body).to.have.property("state").eq("cancelled"); +function assertTransferDeclinedBody(response, _senderWallet, _receiverWallet) { + expect(response.body).to.have.property('state').eq('cancelled'); } module.exports = { - assertSendTokensBody, - assertTransferCompletedBody, - assertTransferDeclinedBody + assertSendTokensBody, + assertTransferCompletedBody, + assertTransferDeclinedBody, }; diff --git a/__tests__/e2e/helpers/walletActionsHelper.js b/__tests__/e2e/helpers/walletActionsHelper.js index cee5bce4..0e794548 100644 --- a/__tests__/e2e/helpers/walletActionsHelper.js +++ b/__tests__/e2e/helpers/walletActionsHelper.js @@ -19,7 +19,8 @@ async function assertTokenInWallet( 'Response status does not match!', ); - for (const wallet of wallets) { + for (let i; i < wallets.length; i += 1) { + const wallet = wallets[i]; if (Object.values(wallet).includes(expectedWallet)) { assert.equals( wallet.tokens_in_wallet, @@ -45,11 +46,13 @@ async function getNumberOfTokensFromWallet(walletInfoResponse, expectedWallet) { 'Response status does not match!', ); - for (const wallet of wallets) { + for (let i; i < wallets.length; i += 1) { + const wallet = wallets[i]; if (Object.values(wallet).includes(expectedWallet)) { return wallet.tokens_in_wallet; } } + return 0; } module.exports = { diff --git a/__tests__/e2e/libs/bootstrap.js b/__tests__/e2e/libs/bootstrap.js index 0d7a7011..4964178a 100644 --- a/__tests__/e2e/libs/bootstrap.js +++ b/__tests__/e2e/libs/bootstrap.js @@ -1,17 +1,24 @@ -const data = require("../database/seed.js"); +const log = require('loglevel'); +const data = require('../database/seed.js'); -const wallets = [data.wallet.id, data.walletB.id, data.walletC.id, data.walletTrustD.id, data.walletTrustE.id]; +const wallets = [ + data.wallet.id, + data.walletB.id, + data.walletC.id, + data.walletTrustD.id, + data.walletTrustE.id, +]; exports.mochaHooks = { - beforeAll: async () => { - console.log('Creating test data in DB...'); - await data.clear(wallets); - await data.seed(); - }, - afterAll: async () => { - console.log('Clearing test data from DB!'); - await data.clear(wallets); - } + beforeAll: async () => { + log.debug('Creating test data in DB...'); + await data.clear(wallets); + await data.seed(); + }, + afterAll: async () => { + log.debug('Clearing test data from DB!'); + await data.clear(wallets); + }, }; -exports.testData = data; \ No newline at end of file +exports.testData = data; diff --git a/__tests__/integration/auth.spec.js b/__tests__/integration/auth.spec.js index 5849f4ac..9d5bd046 100644 --- a/__tests__/integration/auth.spec.js +++ b/__tests__/integration/auth.spec.js @@ -1,13 +1,11 @@ -require('dotenv').config() +require('dotenv').config(); const request = require('supertest'); const { expect } = require('chai'); -const log = require('loglevel'); -const sinon = require("sinon"); -const chai = require("chai"); -const server = require("../../server/app"); +const chai = require('chai'); +const server = require('../../server/app'); chai.use(require('chai-uuid')); -const Zaven = require("../mock-data/Zaven.json"); -const testUtils = require("./testUtils"); +const Zaven = require('../mock-data/Zaven.json'); +const testUtils = require('./testUtils'); describe('Authentication', () => { let registeredUser; @@ -15,7 +13,7 @@ describe('Authentication', () => { beforeEach(async () => { await testUtils.clear(); registeredUser = await testUtils.register(Zaven); - }) + }); // Authorization path it(`[POST /auth] login with ${Zaven.name}`, (done) => { @@ -23,8 +21,8 @@ describe('Authentication', () => { .post('/auth') .set('treetracker-api-key', registeredUser.apiKey) .send({ - wallet: registeredUser.name, - password: registeredUser.password, + wallet: registeredUser.name, + password: registeredUser.password, }) .expect('Content-Type', /application\/json/) .expect(200) @@ -35,12 +33,11 @@ describe('Authentication', () => { }); }); - it(`[POST /auth] login with using wallet id of ${Zaven.name}`, (done) => { request(server) .post('/auth') .set('treetracker-api-key', registeredUser.apiKey) - .send({wallet: registeredUser.id, password: registeredUser.password}) + .send({ wallet: registeredUser.id, password: registeredUser.password }) .expect('Content-Type', /application\/json/) .expect(200) .end((err, res) => { @@ -49,5 +46,4 @@ describe('Authentication', () => { done(); }); }); - }); diff --git a/__tests__/integration/testUtils.js b/__tests__/integration/testUtils.js index 61c7eb58..e1839551 100644 --- a/__tests__/integration/testUtils.js +++ b/__tests__/integration/testUtils.js @@ -61,8 +61,7 @@ async function register(user) { */ async function registerAndLogin(user) { const userRegistered = await register(user); - const jwtService = new JWTService(); - const token = jwtService.sign(userRegistered); + const token = JWTService.sign(userRegistered); userRegistered.token = token; expect(userRegistered).property('apiKey').a('string'); return userRegistered; diff --git a/__tests__/pending-transfer-accepted.spec.js b/__tests__/pending-transfer-accepted.spec.js index 23896480..1eda9c05 100644 --- a/__tests__/pending-transfer-accepted.spec.js +++ b/__tests__/pending-transfer-accepted.spec.js @@ -51,7 +51,6 @@ describe('Create and accept a pending transfer', () => { sinon.restore(); }); - let transferId; let pendingTransfer; it(`Creates a pending transaction `, async () => { @@ -73,7 +72,6 @@ describe('Create and accept a pending transfer', () => { .property('tokens') .lengthOf(1); expect(res.body.parameters.tokens[0]).eq(seed.token.id); - transferId = res.body.id; }); it(`Token:#${seed.token.id} now should be pending `, async () => { @@ -92,7 +90,7 @@ describe('Create and accept a pending transfer', () => { .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body.transfers).lengthOf(1); - pendingTransfer = res.body.transfers[0]; + [pendingTransfer] = res.body.transfers; expect(pendingTransfer) .property('destination_wallet') .eq(seed.walletB.name); diff --git a/__tests__/pending-transfer-cancel.spec.js b/__tests__/pending-transfer-cancel.spec.js index c7fb6d67..ae7c753b 100644 --- a/__tests__/pending-transfer-cancel.spec.js +++ b/__tests__/pending-transfer-cancel.spec.js @@ -51,7 +51,6 @@ describe('Create and cancel a pending transfer', () => { sinon.restore(); }); - let transferId; let pendingTransfer; it(`Creates a pending transaction `, async () => { @@ -72,7 +71,6 @@ describe('Create and cancel a pending transfer', () => { .property('tokens') .lengthOf(1); expect(res.body.parameters.tokens[0]).eq(seed.token.id); - transferId = res.body.id; }); it('Get all pending transfers belongs to walletB, should have one', async () => { @@ -82,7 +80,7 @@ describe('Create and cancel a pending transfer', () => { .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body.transfers).lengthOf(1); - pendingTransfer = res.body.transfers[0]; + [pendingTransfer] = res.body.transfers; expect(pendingTransfer) .property('destination_wallet') .eq(seed.walletB.name); diff --git a/__tests__/pending-transfer-decline.spec.js b/__tests__/pending-transfer-decline.spec.js index 69839ad4..3765065a 100644 --- a/__tests__/pending-transfer-decline.spec.js +++ b/__tests__/pending-transfer-decline.spec.js @@ -51,7 +51,6 @@ describe('Create and decline a pending transfer', () => { sinon.restore(); }); - let transferId; let pendingTransfer; it(`Creates a pending transaction `, async () => { @@ -72,7 +71,6 @@ describe('Create and decline a pending transfer', () => { .property('tokens') .lengthOf(1); expect(res.body.parameters.tokens[0]).eq(seed.token.id); - transferId = res.body.id; }); it('Get all pending transfers belongs to walletB, should have one', async () => { @@ -82,7 +80,7 @@ describe('Create and decline a pending transfer', () => { .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body.transfers).lengthOf(1); - pendingTransfer = res.body.transfers[0]; + [pendingTransfer] = res.body.transfers; expect(pendingTransfer) .property('destination_wallet') .eq(seed.walletB.name); diff --git a/__tests__/seed.js b/__tests__/seed.js index 72a8cd09..2eec6322 100644 --- a/__tests__/seed.js +++ b/__tests__/seed.js @@ -81,7 +81,7 @@ const storyOfThisSeed = ` `; -console.debug( +log.debug( '--------------------------story of database ----------------------------------', storyOfThisSeed, '-----------------------------------------------------------------------------', @@ -144,7 +144,7 @@ async function seed() { } async function addTokenToWallet(walletId) { - return await knex('token').insert( + return knex('token').insert( { id: uuid.v4(), capture_id: uuid.v4(), diff --git a/__tests__/seed.spec.js b/__tests__/seed.spec.js index 42915928..e374329d 100644 --- a/__tests__/seed.spec.js +++ b/__tests__/seed.spec.js @@ -4,7 +4,6 @@ const knex = require('../server/infra/database/knex'); describe('Seed data into DB', () => { let token; - let tree; before(async () => { await seed.clear(); @@ -20,7 +19,7 @@ describe('Seed data into DB', () => { expect(seed.token).to.have.property('id'); const r = await knex.table('token').select().where('id', seed.token.id); expect(r).lengthOf(1); - token = r[0]; + [token] = r; expect(token).to.have.property('capture_id').to.equal(seed.capture.id); expect(token).to.have.property('wallet_id').to.equal(seed.wallet.id); }); diff --git a/__tests__/trust-relationship-send-decline.spec.js b/__tests__/trust-relationship-send-decline.spec.js index 3cdeb51a..2b7fd842 100644 --- a/__tests__/trust-relationship-send-decline.spec.js +++ b/__tests__/trust-relationship-send-decline.spec.js @@ -13,7 +13,6 @@ const { apiKey } = seed; describe('Trust relationship: decline send', () => { let bearerToken; let bearerTokenB; - let bearerTokenC; before(async () => { await seed.clear(); @@ -46,19 +45,6 @@ describe('Trust relationship: decline send', () => { bearerTokenB = res.body.token; expect(bearerTokenB).to.match(/\S+/); } - - { - const res = await request(server) - .post('/auth') - .set('treetracker-api-key', apiKey) - .send({ - wallet: seed.walletC.name, - password: seed.walletC.password, - }); - expect(res).to.have.property('statusCode', 200); - expect(res).property('body').property('token').a('string'); - bearerTokenC = res.body.token; - } }); beforeEach(async () => { diff --git a/__tests__/trust-relationship-send.spec.js b/__tests__/trust-relationship-send.spec.js index b152bd88..59b5d217 100644 --- a/__tests__/trust-relationship-send.spec.js +++ b/__tests__/trust-relationship-send.spec.js @@ -13,7 +13,6 @@ const { apiKey } = seed; describe('Trust relationship: send', () => { let bearerToken; let bearerTokenB; - let bearerTokenC; before(async () => { await seed.clear(); @@ -46,19 +45,6 @@ describe('Trust relationship: send', () => { bearerTokenB = res.body.token; expect(bearerTokenB).to.match(/\S+/); } - - { - const res = await request(server) - .post('/auth') - .set('treetracker-api-key', apiKey) - .send({ - wallet: seed.walletC.name, - password: seed.walletC.password, - }); - expect(res).to.have.property('statusCode', 200); - expect(res).property('body').property('token').a('string'); - bearerTokenC = res.body.token; - } }); beforeEach(async () => { diff --git a/config/config.js b/config/config.js index f6e37663..f6fdbbf3 100644 --- a/config/config.js +++ b/config/config.js @@ -1,10 +1,12 @@ +const log = require('loglevel'); + exports.connectionString = process.env.DATABASE_URL; -if(!process.env.DATABASE_URL){ - console.log("no database URL set from environment!") +if (!process.env.DATABASE_URL) { + log.warn('no database URL set from environment!'); } exports.sentryDSN = ''; -exports.map_url = 'http://test.treetracker.org/' -exports.wallet_url = 'http://test.treetracker.org/' +exports.map_url = 'http://test.treetracker.org/'; +exports.wallet_url = 'http://test.treetracker.org/'; diff --git a/package-lock.json b/package-lock.json index ae6647e9..03c319ff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "chai-uuid": "^1.0.6", "dotenv": "^8.2.0", "expect": "^26.4.2", + "expect-runtime": "^0.7.0", "express": "^4.16.2", "express-async-handler": "^1.1.4", "express-bearer-token": "^2.1.1", @@ -44,7 +45,6 @@ "eslint-plugin-import": "^2.22.1", "eslint-plugin-prettier": "^3.2.0", "eslint-plugin-simple-import-sort": "^7.0.0", - "expect-runtime": "^0.7.0", "faker": "^5.3.1", "generate-password": "^1.6.0", "http-status-codes": "1.4.0", @@ -3820,8 +3820,7 @@ "node_modules/expect-runtime": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/expect-runtime/-/expect-runtime-0.7.0.tgz", - "integrity": "sha512-7BZ5rAG04JL75dI9FNN2e2QO/gnfvo00rmLUhq0q+bX71Mb/Vd22fQggcr5B0+/nqK13IEUF2fnNOkV5SQs6WQ==", - "dev": true + "integrity": "sha512-7BZ5rAG04JL75dI9FNN2e2QO/gnfvo00rmLUhq0q+bX71Mb/Vd22fQggcr5B0+/nqK13IEUF2fnNOkV5SQs6WQ==" }, "node_modules/express": { "version": "4.17.1", @@ -13073,8 +13072,7 @@ "expect-runtime": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/expect-runtime/-/expect-runtime-0.7.0.tgz", - "integrity": "sha512-7BZ5rAG04JL75dI9FNN2e2QO/gnfvo00rmLUhq0q+bX71Mb/Vd22fQggcr5B0+/nqK13IEUF2fnNOkV5SQs6WQ==", - "dev": true + "integrity": "sha512-7BZ5rAG04JL75dI9FNN2e2QO/gnfvo00rmLUhq0q+bX71Mb/Vd22fQggcr5B0+/nqK13IEUF2fnNOkV5SQs6WQ==" }, "express": { "version": "4.17.1", diff --git a/package.json b/package.json index 8a21b8bb..288f3680 100644 --- a/package.json +++ b/package.json @@ -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_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_LOG_LEVEL=debug 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" @@ -38,6 +38,7 @@ "chai-uuid": "^1.0.6", "dotenv": "^8.2.0", "expect": "^26.4.2", + "expect-runtime": "^0.7.0", "express": "^4.16.2", "express-async-handler": "^1.1.4", "express-bearer-token": "^2.1.1", @@ -68,7 +69,6 @@ "eslint-plugin-import": "^2.22.1", "eslint-plugin-prettier": "^3.2.0", "eslint-plugin-simple-import-sort": "^7.0.0", - "expect-runtime": "^0.7.0", "faker": "^5.3.1", "generate-password": "^1.6.0", "http-status-codes": "1.4.0", diff --git a/server/handlers/authHandler.js b/server/handlers/authHandler.js index 17d7070c..f9701e5c 100644 --- a/server/handlers/authHandler.js +++ b/server/handlers/authHandler.js @@ -11,9 +11,7 @@ const authPost = async (req, res) => { await authPostSchema.validateAsync(req.body, { abortEarly: false }); const { wallet, password } = req.body; - const authService = new AuthService(); - const token = await authService.signIn({ wallet, password }); - + const token = await AuthService.signIn({ wallet, password }); if (!token) throw new HttpError(401, 'Invalid Credentials'); res.status(200).json({ token }); diff --git a/server/handlers/transferHandler.js b/server/handlers/transferHandler.js index b757bffc..a51a3b09 100644 --- a/server/handlers/transferHandler.js +++ b/server/handlers/transferHandler.js @@ -69,7 +69,6 @@ const transferPost = async (req, res) => { ); res.status(status).send(result); - res.end; }; const transferIdAcceptPost = async (req, res) => { @@ -148,6 +147,8 @@ const transferIdTokenGet = async (req, res) => { abortEarly: false, }); + const { limit, offset } = req.query; + const transferService = new TransferService(); const tokens = await transferService.getTokensByTransferId( req.params.transfer_id, diff --git a/server/infra/database/Session.spec.js b/server/infra/database/Session.spec.js index 35479c10..ec34ecd3 100644 --- a/server/infra/database/Session.spec.js +++ b/server/infra/database/Session.spec.js @@ -1,31 +1,30 @@ -const jestExpect = require("expect"); -const sinon = require("sinon"); -const chai = require("chai"); -const sinonChai = require("sinon-chai"); -const Session = require("./Session"); +const jestExpect = require('expect'); +const chai = require('chai'); +const sinonChai = require('sinon-chai'); +const Session = require('./Session'); chai.use(sinonChai); -const {expect} = chai; +const { expect } = chai; -describe("Session", () => { +describe('Session', () => { let session = new Session(); beforeEach(() => { session = new Session(); }); - it("getDB", () => { + it('getDB', () => { const db = session.getDB(); expect(db).not.undefined; }); - it("try to commit transaction before begin it, should throw error", async () => { + it('try to commit transaction before begin it, should throw error', async () => { await jestExpect(async () => { - await session.commitTransaction() + await session.commitTransaction(); }).rejects.toThrow(/can not commit/i); }); - it("try to rollback transaction before begin it, should throw error", async () => { + it('try to rollback transaction before begin it, should throw error', async () => { await jestExpect(async () => { await session.rollbackTransaction(); }).rejects.toThrow(/can not rollback/i); diff --git a/server/infra/database/knex.js b/server/infra/database/knex.js index f5f420b1..19cadf03 100644 --- a/server/infra/database/knex.js +++ b/server/infra/database/knex.js @@ -1,9 +1,10 @@ require('dotenv').config(); const expect = require('expect-runtime'); +const log = require('loglevel'); +const knex = require('knex'); const connection = require('../../../config/config').connectionString; expect(connection).to.match(/^postgresql:\//); -const log = require('loglevel'); const knexConfig = { client: 'pg', @@ -36,6 +37,4 @@ if (process.env.DATABASE_SCHEMA) { } log.debug(knexConfig.searchPath); -const knex = require('knex')(knexConfig); - -module.exports = knex; +module.exports = knex(knexConfig); diff --git a/server/models/Token.js b/server/models/Token.js index 09b3d218..20db0c4b 100644 --- a/server/models/Token.js +++ b/server/models/Token.js @@ -103,14 +103,14 @@ class Token { ); } - async belongsTo(token, walletId) { + static belongsTo(token, walletId) { if (token.wallet_id === walletId) { return true; } return false; } - async beAbleToTransfer(token) { + static beAbleToTransfer(token) { if (token.transfer_pending === false) { return true; } diff --git a/server/models/Token.spec.js b/server/models/Token.spec.js index a2461dfa..fca41850 100644 --- a/server/models/Token.spec.js +++ b/server/models/Token.spec.js @@ -1,44 +1,44 @@ -const jestExpect = require("expect"); -const sinon = require("sinon"); -const chai = require("chai"); -const sinonChai = require("sinon-chai"); +const sinon = require('sinon'); +const chai = require('chai'); +const sinonChai = require('sinon-chai'); const uuid = require('uuid'); -const Token = require("./Token"); -const TokenRepository = require("../repositories/TokenRepository"); -const HttpError = require("../utils/HttpError"); +const Token = require('./Token'); +const TokenRepository = require('../repositories/TokenRepository'); chai.use(sinonChai); -const {expect} = chai; -const TransactionRepository = require("../repositories/TransactionRepository"); -const Wallet = require("./Wallet"); -const Session = require("./Session"); +const { expect } = chai; +const TransactionRepository = require('../repositories/TransactionRepository'); +const Wallet = require('./Wallet'); +const Session = require('../infra/database/Session'); -describe("Token", () => { +describe('Token', () => { const session = new Session(); - const tokenId = uuid.v4() - const transferId = uuid.v4() - const walletId = uuid.v4() - const wallet2Id = uuid.v4() + const tokenId = uuid.v4(); + const transferId = uuid.v4(); + const walletId = uuid.v4(); + const wallet2Id = uuid.v4(); afterEach(() => { sinon.restore(); - }) + }); - it("constructor by object", () => { - const token = new Token({ - id: tokenId, - }, session); + it('constructor by object', () => { + const token = new Token( + { + id: tokenId, + }, + session, + ); expect(token).instanceOf(Token); expect(token.getId()).eq(tokenId); }); - describe("pendingTransfer", () => { - - it("pendingTransfer successfully", async () => { + describe('pendingTransfer', () => { + it('pendingTransfer successfully', async () => { const token = new Token(tokenId, session); - const transfer = {id:transferId}; - const fn1 = sinon.stub(TokenRepository.prototype, "update"); + const transfer = { id: transferId }; + const fn1 = sinon.stub(TokenRepository.prototype, 'update'); await token.pendingTransfer(transfer); expect(fn1).calledWith({ id: tokenId, @@ -49,9 +49,8 @@ describe("Token", () => { }); }); - describe("completeTransfer", () => { - - it("completeTransfer successfully", async () => { + describe('completeTransfer', () => { + it('completeTransfer successfully', async () => { const token = new Token(tokenId, session); const transfer = { id: transferId, @@ -59,37 +58,36 @@ describe("Token", () => { destination_wallet_id: wallet2Id, claim: false, }; - const fn1 = sinon.stub(TokenRepository.prototype, "update"); - const fn2 = sinon.stub(TransactionRepository.prototype, "create"); + const fn1 = sinon.stub(TokenRepository.prototype, 'update'); + const fn2 = sinon.stub(TransactionRepository.prototype, 'create'); await token.completeTransfer(transfer); expect(fn1).calledWith({ id: tokenId, wallet_id: wallet2Id, transfer_pending: false, transfer_pending_id: null, - claim: false - }); + claim: false, + }); expect(fn2).calledWith({ token_id: tokenId, transfer_id: transferId, source_wallet_id: walletId, destination_wallet_id: wallet2Id, - claim: false + claim: false, }); }); }); - describe("cancelTransfer", () => { - - it("cancelTransfer successfully", async () => { + describe('cancelTransfer', () => { + it('cancelTransfer successfully', async () => { const token = new Token(tokenId, session); const transfer = { id: transferId, source_wallet_id: walletId, destination_wallet_id: wallet2Id, }; - const fn1 = sinon.stub(TokenRepository.prototype, "update"); - const fn2 = sinon.stub(TransactionRepository.prototype, "create"); + const fn1 = sinon.stub(TokenRepository.prototype, 'update'); + const fn2 = sinon.stub(TransactionRepository.prototype, 'create'); await token.cancelTransfer(transfer); expect(fn1).calledWith({ id: tokenId, @@ -100,12 +98,11 @@ describe("Token", () => { }); }); - describe("belongsTo", () => { - - it("belongsTo", async () => { + describe('belongsTo', () => { + it('belongsTo', async () => { const token = new Token(tokenId, session); const wallet = new Wallet(walletId, session); - const fn1 = sinon.stub(TokenRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TokenRepository.prototype, 'getById').resolves({ id: tokenId, wallet_id: walletId, }); @@ -113,10 +110,10 @@ describe("Token", () => { expect(fn1).calledWith(); }); - it("not belongsTo", async () => { + it('not belongsTo', async () => { const token = new Token(tokenId, session); const wallet = new Wallet(walletId, session); - const fn1 = sinon.stub(TokenRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TokenRepository.prototype, 'getById').resolves({ id: tokenId, wallet_id: wallet2Id, }); @@ -125,15 +122,12 @@ describe("Token", () => { }); }); - describe("Transactions", () => { - - it("getTransactions", async () => { + describe('Transactions', () => { + it('getTransactions', async () => { const token = new Token(tokenId); - sinon.stub(TransactionRepository.prototype, "getByFilter").resolves([{}]); + sinon.stub(TransactionRepository.prototype, 'getByFilter').resolves([{}]); const transactions = await token.getTransactions(); expect(transactions).lengthOf(1); }); - }); - }); diff --git a/server/models/Transfer.js b/server/models/Transfer.js index fe1ab931..7b78f226 100644 --- a/server/models/Transfer.js +++ b/server/models/Transfer.js @@ -120,12 +120,9 @@ class Transfer { async transfer(walletLoginId, sender, receiver, tokens, claimBoolean) { // await this.checkDeduct(sender, receiver); // check tokens belong to sender - for (const token of tokens) { - const tokenBelongsToSender = await this._token.belongsTo( - token, - sender.id, - ); - const tokenAbleToTransfer = await this._token.beAbleToTransfer(token); + tokens.forEach((token) => { + const tokenBelongsToSender = Token.belongsTo(token, sender.id); + const tokenAbleToTransfer = Token.beAbleToTransfer(token); if (!tokenBelongsToSender) { throw new HttpError( 403, @@ -138,7 +135,8 @@ class Transfer { `The token ${token.id} can not be transfer for some reason, for example, it's been pending for another transfer`, ); } - } + }); + const isDeduct = await this.isDeduct(walletLoginId, sender); const hasTrust = await this._trust.hasTrust( walletLoginId, @@ -160,7 +158,7 @@ class Transfer { (!isDeduct && hasTrust) ) { const tokensId = []; - for (const token of tokens) { + tokens.forEach((token) => { // check if the tokens you want to transfer is claimed, i.e. not transferrable if (token.claim) { log.warn('token is claimed, cannot be transfered'); @@ -170,7 +168,7 @@ class Transfer { ); } tokensId.push(token.id); - } + }); const transfer = await this._transferRepository.create({ originator_wallet_id: walletLoginId, source_wallet_id: sender.id, @@ -192,9 +190,9 @@ class Transfer { if (hasControlOverSender) { log.debug('OK, no permission, source under control, now pending it'); const tokensId = []; - for (const token of tokens) { + tokens.forEach((token) => { tokensId.push(token.id); - } + }); const transfer = await this._transferRepository.create({ originator_wallet_id: walletLoginId, source_wallet_id: sender.id, @@ -207,7 +205,7 @@ class Transfer { }); await this._token.pendingTransfer(tokens, transfer); // check if the tokens you want to transfer is claimed, i.e. not trasfferable - for (const token of tokens) { + tokens.forEach((token) => { if (token.claim === true) { log.warn('token is claimed, cannot be transfered'); throw new HttpError( @@ -215,16 +213,16 @@ class Transfer { `The token ${token.id} is claimed, cannot be transfered`, ); } - } + }); return transfer; } if (hasControlOverReceiver) { log.debug('OK, no permission, receiver under control, now request it'); const tokensId = []; - for (const token of tokens) { + tokens.forEach((token) => { tokensId.push(token.id); - } + }); const transfer = await this.create({ originator_wallet_id: walletLoginId, source_wallet_id: sender.id, @@ -237,7 +235,7 @@ class Transfer { }); await this._token.pendingTransfer(tokens, transfer); // check if the tokens you want to transfer is claimed, i.e. not trasfferable - for (const token of tokens) { + tokens.forEach((token) => { if (token.claim === true) { log.warn('token is claimed, cannot be transfered'); throw new HttpError( @@ -245,11 +243,11 @@ class Transfer { `The token ${token.id} is claimed, cannot be transfered`, ); } - } + }); return transfer; } // TODO - expect.fail(); + return expect.fail(); } async transferBundle( @@ -352,7 +350,7 @@ class Transfer { return this.constructor.removeWalletIds(transfer); } // TODO - expect.fail(); + return expect.fail(); } /* @@ -585,8 +583,8 @@ class Transfer { true, ); } - for (const token of tokens) { - const belongsTo = await this._token.belongsTo(token, senderId); + tokens.forEach((token) => { + const belongsTo = Token.belongsTo(token, senderId); if (!belongsTo) { throw new HttpError( 403, @@ -594,7 +592,7 @@ class Transfer { true, ); } - } + }); // transfer await this._token.completeTransfer(tokens, transfer); diff --git a/server/models/Trust.js b/server/models/Trust.js index c7764c5b..84f3ee99 100644 --- a/server/models/Trust.js +++ b/server/models/Trust.js @@ -252,10 +252,12 @@ class Trust { const walletModel = new Wallet(this._session); const allWallets = await walletModel.getAllWallets(walletId); const allTrustRelationships = []; - for (const wallet of allWallets) { - const list = await this.getTrustRelationships({ walletId: wallet.id }); - allTrustRelationships.push(...list); - } + await Promise.all( + allWallets.map(async (wallet) => { + const list = await this.getTrustRelationships({ walletId: wallet.id }); + allTrustRelationships.push(...list); + }), + ); const walletIds = [...allWallets.map((e) => e.id)]; return allTrustRelationships.filter((trustRelationship) => { return walletIds.includes(trustRelationship.target_wallet_id); diff --git a/server/models/Trust.spec.js b/server/models/Trust.spec.js index 2957e2fe..19c29271 100644 --- a/server/models/Trust.spec.js +++ b/server/models/Trust.spec.js @@ -1,22 +1,26 @@ -const jestExpect = require("expect"); -const sinon = require("sinon"); -const chai = require("chai"); -const sinonChai = require("sinon-chai"); +const chai = require('chai'); +const sinonChai = require('sinon-chai'); +const TrustRelationshipEnums = require('../utils/trust-enums'); chai.use(sinonChai); -const {expect} = chai; -const TrustRelationship = require("./TrustRelationship"); +const { expect } = chai; -describe("TrustRelationship", () => { - - describe("getTrustTypeByRequestType", () => { - - it("Request send should get send", () => { - expect(TrustRelationship.getTrustTypeByRequestType(TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send)).eq(TrustRelationship.ENTITY_TRUST_TYPE.send); +describe('TrustRelationship', () => { + describe('getTrustTypeByRequestType', () => { + it('Request send should get send', () => { + expect( + TrustRelationshipEnums.getTrustTypeByRequestType( + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, + ), + ).eq(TrustRelationshipEnums.ENTITY_TRUST_TYPE.send); }); - it("Request receive should get send", () => { - expect(TrustRelationship.getTrustTypeByRequestType(TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive)).eq(TrustRelationship.ENTITY_TRUST_TYPE.send); + it('Request receive should get send', () => { + expect( + TrustRelationshipEnums.getTrustTypeByRequestType( + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.receive, + ), + ).eq(TrustRelationshipEnums.ENTITY_TRUST_TYPE.send); }); }); }); diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 5a8346e6..b40afcb1 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -61,7 +61,7 @@ class Wallet { * the trust from me */ async getTrustRelationshipsTargeted() { - return await this.trustRepository.getByTargetId(this._id); + return this.trustRepository.getByTargetId(this._id); } async getById(id) { @@ -79,9 +79,9 @@ class Wallet { * requestType: trust type, * sourceWalletId: the wallet id related to the trust relationship with me, */ - async checkTrustRequestSentToMe(requestType, sourceWalletId) { - // pass - } + // async checkTrustRequestSentToMe(requestType, sourceWalletId) { + // // pass + // } /* * I have control over given wallet diff --git a/server/models/Wallet.spec.js b/server/models/Wallet.spec.js index ae5859c2..1b924e2a 100644 --- a/server/models/Wallet.spec.js +++ b/server/models/Wallet.spec.js @@ -1,3 +1,4 @@ +/* eslint-disable no-shadow */ const jestExpect = require('expect'); const sinon = require('sinon'); const chai = require('chai'); @@ -12,11 +13,11 @@ const TrustRepository = require('../repositories/TrustRepository'); const WalletService = require('../services/WalletService'); const TransferRepository = require('../repositories/TransferRepository'); const HttpError = require('../utils/HttpError'); -const TrustRelationship = require('./TrustRelationship'); const Transfer = require('./Transfer'); const Token = require('./Token'); const TokenService = require('../services/TokenService'); -const Session = require('./Session'); +const Session = require('../infra/database/Session'); +const TrustRelationshipEnums = require('../utils/trust-enums'); describe('Wallet', () => { let walletService; @@ -98,7 +99,7 @@ describe('Wallet', () => { const fn3 = sinon.stub(TrustRepository.prototype, 'create'); sinon.stub(Wallet.prototype, 'checkDuplicateRequest'); await wallet.requestTrustFromAWallet( - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, wallet, wallet2, ); @@ -106,8 +107,8 @@ describe('Wallet', () => { sinon.match({ actor_wallet_id: wallet.getId(), originator_wallet_id: wallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, }), ); fn2.restore(); @@ -133,7 +134,6 @@ describe('Wallet', () => { describe('Accept trust', () => { const wallet = new Wallet(uuid.v4()); - const wallet2 = new Wallet(uuid.v4()); const trustId = uuid.v4(); const trustRelationship = { id: trustId, @@ -167,7 +167,6 @@ describe('Wallet', () => { describe('Decline trust', () => { const wallet = new Wallet(uuid.v4()); - const wallet2 = new Wallet(uuid.v4()); const trustId = uuid.v4(); const trustRelationship = { id: trustId, @@ -199,7 +198,6 @@ describe('Wallet', () => { describe('Cancel trust request', () => { const wallet = new Wallet(uuid.v4()); - const wallet2 = new Wallet(uuid.v4()); const trustId = uuid.v4(); it('Try to cancel but the requested trust whose originator id is not me, throw 403', async () => { @@ -238,18 +236,13 @@ describe('Wallet', () => { describe('hasTrust()', () => { const wallet = new Wallet(uuid.v4()); const wallet2 = new Wallet(uuid.v4()); - const trustId = uuid.v4(); - const trustRelationship = { - id: trustId, - target_wallet_id: wallet.getId(), - }; it('has no trust', async () => { const fn1 = sinon .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') .resolves([]); // no relationship const result = await wallet.hasTrust( - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, wallet, wallet2, ); @@ -262,15 +255,15 @@ describe('Wallet', () => { .stub(Wallet.prototype, 'getTrustRelationships') .resolves([ { - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, actor_wallet_id: wallet.getId(), target_wallet_id: wallet2.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }, ]); const result = await wallet.hasTrust( - TrustRelationship.ENTITY_TRUST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, wallet, wallet2, ); @@ -283,14 +276,15 @@ describe('Wallet', () => { .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') .resolves([ { - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, + request_type: + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.receive, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, actor_wallet_id: wallet2.getId(), target_wallet_id: wallet.getId(), }, ]); const result = await wallet.hasTrust( - TrustRelationship.ENTITY_TRUST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, wallet, wallet2, ); @@ -419,12 +413,6 @@ describe('Wallet', () => { describe('Bundle transfer', () => { const sender = new Wallet(uuid.v4()); const receiver = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); const transferId = uuid.v4(); it("Sender doesn't have enough tokens to send, should throw 403", async () => { @@ -551,7 +539,7 @@ describe('Wallet', () => { const fn0 = sinon .stub(TokenService.prototype, 'countTokenByWallet') .resolves(1); - const fn6 = sinon + const _fn6 = sinon .stub(TokenService.prototype, 'countNotClaimedTokenByWallet') .resolves(1); const fn1 = sinon.stub(Wallet.prototype, 'hasTrust').resolves(true); @@ -580,15 +568,6 @@ describe('Wallet', () => { }); describe('getPendingTransfers', () => { - const sender = new Wallet(uuid.v4()); - const receiver = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); - it('getPendingTransfers', async () => { const fn1 = sinon .stub(TransferRepository.prototype, 'getPendingTransfers') @@ -600,7 +579,6 @@ describe('Wallet', () => { }); describe('acceptTransfer', () => { - const sender = new Wallet(uuid.v4()); const receiver = new Wallet(uuid.v4()); const token = new Token( { @@ -790,12 +768,6 @@ describe('Wallet', () => { const wallet = new Wallet(uuid.v4()); const wallet2 = new Wallet(uuid.v4()); const wallet3 = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); const transferId = uuid.v4(); it("Can cancel a 'pending' transfer", async () => { @@ -860,12 +832,6 @@ describe('Wallet', () => { describe('fulfillTransfer', () => { const wallet = new Wallet(uuid.v4()); const wallet2 = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); const transferId = uuid.v4(); it('fulfillTransfer successfully', async () => { @@ -925,7 +891,6 @@ describe('Wallet', () => { describe('fulfillTransferWithTokens', () => { const wallet = new Wallet(uuid.v4()); - const wallet2 = new Wallet(uuid.v4()); const token = new Token( { id: uuid.v4(), @@ -1041,12 +1006,6 @@ describe('Wallet', () => { describe('getTransfers', () => { const wallet = new Wallet(uuid.v4()); const wallet2 = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); const transferId = uuid.v4(); it('getTransfers', async () => { @@ -1098,13 +1057,6 @@ describe('Wallet', () => { describe('hasControlOver', () => { const wallet = new Wallet(uuid.v4()); const wallet2 = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); - const transferId = uuid.v4(); it('hasControlOver should pass if it is the same wallet', async () => { const result = await wallet.hasControlOver(wallet); @@ -1126,13 +1078,13 @@ describe('Wallet', () => { }, { request_type: - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, }, { target_wallet_id: wallet2.getId(), }, { - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }, ], }, @@ -1142,13 +1094,14 @@ describe('Wallet', () => { actor_wallet_id: wallet2.getId(), }, { - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + request_type: + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, }, { target_wallet_id: wallet.getId(), }, { - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }, ], }, @@ -1159,13 +1112,6 @@ describe('Wallet', () => { describe('getTrustRelationships', () => { const wallet = new Wallet(uuid.v4()); - const wallet2 = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); const trustId = uuid.v4(); it('successfully', async () => { @@ -1173,21 +1119,21 @@ describe('Wallet', () => { .stub(TrustRepository.prototype, 'getByFilter') .resolves([{ id: trustId }]); const result = await wallet.getTrustRelationships( - TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - TrustRelationship.ENTITY_TRUST_TYPE.send, - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, + TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, ); expect(result).lengthOf(1); expect(fn).calledWith({ and: [ { - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }, { - type: TrustRelationship.ENTITY_TRUST_TYPE.send, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, }, { - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, }, { or: [ @@ -1238,12 +1184,6 @@ describe('Wallet', () => { const wallet = new Wallet({ id: uuid.v4() }); // TODO: should create class MockWallet that does not use repository const sender = new Wallet(uuid.v4()); const receiver = new Wallet(uuid.v4()); - const token = new Token( - { - id: uuid.v4(), - }, - session, - ); it('the sender is me, should return false', async () => { const result = await wallet.isDeduct(wallet, receiver); @@ -1273,8 +1213,8 @@ describe('Wallet', () => { { actor_wallet_id: wallet.getId(), target_wallet_id: subWallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }, ]); sinon.stub(WalletService.prototype, 'getById').resolves(subWallet); @@ -1287,8 +1227,8 @@ describe('Wallet', () => { { actor_wallet_id: subWallet.getId(), target_wallet_id: wallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }, ]); sinon.stub(WalletService.prototype, 'getById').resolves(subWallet); @@ -1308,7 +1248,7 @@ describe('Wallet', () => { { actor_wallet_id: wallet2.getId(), target_wallet_id: wallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, }, ]); const list = await wallet.getTrustRelationshipsRequestedToMe(); @@ -1322,14 +1262,14 @@ describe('Wallet', () => { { actor_wallet_id: wallet2.getId(), target_wallet_id: wallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, }, ]); fn.onCall(1).resolves([ { actor_wallet_id: wallet2.getId(), target_wallet_id: subWallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, }, ]); const list = await wallet.getTrustRelationshipsRequestedToMe(); @@ -1346,15 +1286,15 @@ describe('Wallet', () => { it('A manage B, now B request to manage A, should throw error', async () => { const trustRelationshipTrusted = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), }; const trustRelationshipRequested = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), }; @@ -1369,15 +1309,15 @@ describe('Wallet', () => { it('A manage B, now A request to yield B, should throw error', async () => { const trustRelationshipTrusted = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), }; const trustRelationshipRequested = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), }; @@ -1392,15 +1332,15 @@ describe('Wallet', () => { it('A yield B, now B request to yield A, should throw error', async () => { const trustRelationshipTrusted = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), }; const trustRelationshipRequested = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), }; @@ -1415,15 +1355,15 @@ describe('Wallet', () => { it('A yield B, now A request to manage B, should throw error', async () => { const trustRelationshipTrusted = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), }; const trustRelationshipRequested = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), }; @@ -1445,19 +1385,19 @@ describe('Wallet', () => { it('A send B trust has been requested, now request again, should throw error', async () => { const trustRelationshipRequested = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.requested, }; const trustRelationshipRequesting = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.requested, }; sinon .stub(Wallet.prototype, 'getTrustRelationships') @@ -1470,19 +1410,19 @@ describe('Wallet', () => { it('A send B trust has been trusted, now request B receive A, should throw error', async () => { const trustRelationshipRequested = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - request_type: TrustRelationship.ENTITY_TRUST_TYPE.send, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, }; const trustRelationshipRequesting = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.receive, actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.requested, }; sinon .stub(Wallet.prototype, 'getTrustRelationships') @@ -1495,19 +1435,19 @@ describe('Wallet', () => { it('A manage B trust has been requested, now request B yield A, should throw error', async () => { const trustRelationshipRequested = { id: trustIdA, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.manage, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.requested, }; const trustRelationshipRequesting = { id: trustIdB, - type: TrustRelationship.ENTITY_TRUST_TYPE.manage, - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + type: TrustRelationshipEnums.ENTITY_TRUST_TYPE.manage, + request_type: TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.yield, actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, + state: TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.requested, }; sinon .stub(Wallet.prototype, 'getTrustRelationships') diff --git a/server/repositories/ApiKeyRepository.spec.js b/server/repositories/ApiKeyRepository.spec.js index 7a3a3014..2c6fda0c 100644 --- a/server/repositories/ApiKeyRepository.spec.js +++ b/server/repositories/ApiKeyRepository.spec.js @@ -1,32 +1,32 @@ -const {expect} = require("chai"); -const mockKnex = require("mock-knex"); -const knex = require("../database/knex"); +const { expect } = require('chai'); +const mockKnex = require('mock-knex'); +const knex = require('../infra/database/knex'); const tracker = mockKnex.getTracker(); -const ApiKeyRepository = require("./ApiKeyRepository"); -const Session = require("../models/Session"); +const ApiKeyRepository = require('./ApiKeyRepository'); +const Session = require('../infra/database/Session'); -describe("ApiKeyRepository", () => { +describe('ApiKeyRepository', () => { let apiKeyRepository; beforeEach(() => { mockKnex.mock(knex); tracker.install(); apiKeyRepository = new ApiKeyRepository(new Session()); - }) + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - it("get by apiKey successfully", async () => { + it('get by apiKey successfully', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*api_key.*/); - query.response([{id:1}]); + query.response([{ id: 1 }]); }); - const result = await apiKeyRepository.getByApiKey("test"); + const result = await apiKeyRepository.getByApiKey('test'); return result; }); }); diff --git a/server/repositories/BaseRepository.js b/server/repositories/BaseRepository.js index 53fd2862..2fe8d8c1 100644 --- a/server/repositories/BaseRepository.js +++ b/server/repositories/BaseRepository.js @@ -27,7 +27,7 @@ class BaseRepository { if (object.and) { expect(Object.keys(object)).lengthOf(1); expect(object.and).a(expect.any(Array)); - for (const one of object.and) { + object.and.forEach((one) => { if (one.or) { result = result.andWhere((subBuilder) => this.whereBuilder(one, subBuilder), @@ -36,11 +36,11 @@ class BaseRepository { expect(Object.keys(one)).lengthOf(1); result = result.andWhere(Object.keys(one)[0], Object.values(one)[0]); } - } + }); } else if (object.or) { expect(Object.keys(object)).lengthOf(1); expect(object.or).a(expect.any(Array)); - for (const one of object.or) { + object.or.forEach((one) => { if (one.and) { result = result.orWhere((subBuilder) => this.whereBuilder(one, subBuilder), @@ -49,7 +49,7 @@ class BaseRepository { expect(Object.keys(one)).lengthOf(1); result = result.orWhere(Object.keys(one)[0], Object.values(one)[0]); } - } + }); } else { result.where(object); } @@ -117,6 +117,7 @@ class BaseRepository { .getDB()(this._tableName) .update(objectCopy) .whereIn('id', ids); + return result; } async create(object) { diff --git a/server/repositories/BaseRepository.spec.js b/server/repositories/BaseRepository.spec.js index 4f814249..6c4258ec 100644 --- a/server/repositories/BaseRepository.spec.js +++ b/server/repositories/BaseRepository.spec.js @@ -1,283 +1,327 @@ -const BaseRepository = require("./BaseRepository"); -const {expect} = require("chai"); -const knex = require("../database/knex"); -const mockKnex = require("mock-knex"); +const mockKnex = require('mock-knex'); +const { expect } = require('chai'); +const uuid = require('uuid'); +const BaseRepository = require('./BaseRepository'); +const knex = require('../infra/database/knex'); +const Session = require('../infra/database/Session'); const tracker = mockKnex.getTracker(); -const jestExpect = require("expect"); -const uuid = require('uuid'); -const Session = require("../models/Session"); -describe("BaseRepository", () => { +describe('BaseRepository', () => { let baseRepository; beforeEach(() => { mockKnex.mock(knex); tracker.install(); const session = new Session(); - baseRepository = new BaseRepository("testTable", session); - }) + baseRepository = new BaseRepository('testTable', session); + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - it("getById", async () => { + it('getById', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*testTable.*/); - query.response([{id:1}]); + query.response([{ id: 1 }]); }); const entity = await baseRepository.getById(1); - expect(entity).property("id").eq(1); + expect(entity).property('id').eq(1); }); // TODO - it.skip("getById can not find result, should throw 404", () => { - }); + it.skip('getById can not find result, should throw 404', () => {}); - describe("getByFilter", () => { - - it("getByFilter", async () => { + describe('getByFilter', () => { + it('getByFilter', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*testTable.*name.*/); - query.response([{id:1}]); + query.response([{ id: 1 }]); }); const result = await baseRepository.getByFilter({ - name: "testName", + name: 'testName', }); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); - it("getByFilter with limit", async () => { + it('getByFilter with limit', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*testTable.*limit.*/); - query.response([{id:1}]); - }); - const result = await baseRepository.getByFilter({ - name: "testName", - },{ - limit: 1, + query.response([{ id: 1 }]); }); + const result = await baseRepository.getByFilter( + { + name: 'testName', + }, + { + limit: 1, + }, + ); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); - it("getByFilter with offset", async () => { + it('getByFilter with offset', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*testTable.*offset.*/); - query.response([{id:2}]); - }); - const result = await baseRepository.getByFilter({ - name: "testName", - },{ - offset: 1, + query.response([{ id: 2 }]); }); + const result = await baseRepository.getByFilter( + { + name: 'testName', + }, + { + offset: 1, + }, + ); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(2); + expect(result[0]).property('id').eq(2); }); describe("'and' 'or' phrase", () => { - - it("{and: [{c:1}, {b:2}]}", async () => { + it('{and: [{c:1}, {b:2}]}', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { - expect(query.sql).match(/select.*testTable.*where.*c1.*=.*and.*c2.*=.*/); - query.response([{id:1}]); + tracker.on('query', (query) => { + expect(query.sql).match( + /select.*testTable.*where.*c1.*=.*and.*c2.*=.*/, + ); + query.response([{ id: 1 }]); }); const result = await baseRepository.getByFilter({ - and: [{ - c1: 1, - },{ - c2: 2, - }], + and: [ + { + c1: 1, + }, + { + c2: 2, + }, + ], }); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); - it("{or: [{c:1}, {b:2}]}", async () => { + it('{or: [{c:1}, {b:2}]}', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { - expect(query.sql).match(/select.*testTable.*where.*c1.*=.*or.*c2.*=.*/); - query.response([{id:1}]); + tracker.on('query', (query) => { + expect(query.sql).match( + /select.*testTable.*where.*c1.*=.*or.*c2.*=.*/, + ); + query.response([{ id: 1 }]); }); const result = await baseRepository.getByFilter({ - or: [{ - c1: 1, - },{ - c2: 2, - }], + or: [ + { + c1: 1, + }, + { + c2: 2, + }, + ], }); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); - it("{and: [{c:1}, {b:2}, {or: [{d:1}, {e:1}]]}", async () => { + it('{and: [{c:1}, {b:2}, {or: [{d:1}, {e:1}]]}', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { - expect(query.sql).match(/select.*testTable.*where.*c1.*=.*and.*c2.*=.*and.*c3.*or.*c4.*/); - query.response([{id:1}]); + tracker.on('query', (query) => { + expect(query.sql).match( + /select.*testTable.*where.*c1.*=.*and.*c2.*=.*and.*c3.*or.*c4.*/, + ); + query.response([{ id: 1 }]); }); const result = await baseRepository.getByFilter({ - and: [{ - c1: 1, - },{ - c2: 2, - },{ - or: [{ - c3: 1, - },{ - c4: 1, - }] - }], + and: [ + { + c1: 1, + }, + { + c2: 2, + }, + { + or: [ + { + c3: 1, + }, + { + c4: 1, + }, + ], + }, + ], }); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); - it("{or: [{c:1}, {b:2}, {and: [{d:1}, {e:1}]]}", async () => { + it('{or: [{c:1}, {b:2}, {and: [{d:1}, {e:1}]]}', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { - console.log("sql:",query.sql); - expect(query.sql).match(/select.*testTable.*where.*c1.*=.*or.*c2.*=.*or.*c3.*and.*c4.*/); - query.response([{id:1}]); + tracker.on('query', (query) => { + expect(query.sql).match( + /select.*testTable.*where.*c1.*=.*or.*c2.*=.*or.*c3.*and.*c4.*/, + ); + query.response([{ id: 1 }]); }); const result = await baseRepository.getByFilter({ - or: [{ - c1: 1, - },{ - c2: 2, - },{ - and: [{ - c3: 1, - },{ - c4: 1, - }] - }], + or: [ + { + c1: 1, + }, + { + c2: 2, + }, + { + and: [ + { + c3: 1, + }, + { + c4: 1, + }, + ], + }, + ], }); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); - it("(a=1 and b =2) or (a=2 and b=1)", async () => { + it('(a=1 and b =2) or (a=2 and b=1)', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { - console.log("sql:",query.sql); - expect(query.sql).match(/select.*testTable.*where.*c3.*=.*and.*c4.*=.*or.*c3.*and.*c4.*/); - query.response([{id:1}]); + tracker.on('query', (query) => { + expect(query.sql).match( + /select.*testTable.*where.*c3.*=.*and.*c4.*=.*or.*c3.*and.*c4.*/, + ); + query.response([{ id: 1 }]); }); const result = await baseRepository.getByFilter({ - or: [{ - and: [{ - c3: 1, - },{ - c4: 2, - }] - },{ - and: [{ - c3: 2, - },{ - c4: 1, - }] - }], + or: [ + { + and: [ + { + c3: 1, + }, + { + c4: 2, + }, + ], + }, + { + and: [ + { + c3: 2, + }, + { + c4: 1, + }, + ], + }, + ], }); expect(result).lengthOf(1); - expect(result[0]).property("id").eq(1); + expect(result[0]).property('id').eq(1); }); }); - }); - describe("update", () => { - - it("update", async () => { + describe('update', () => { + it('update', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/update.*testTable.*/); - query.response({id:1}); + query.response({ id: 1 }); }); - const result = await baseRepository.update({ - id: uuid.v4(), - name: "testName", + await baseRepository.update({ + id: uuid.v4(), + name: 'testName', }); }); }); - describe("create", () => { - - it("create", async () => { + describe('create', () => { + it('create', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/insert.*testTable.*returning.*/); - query.response([{id:1}]); + query.response([{ id: 1 }]); }); const result = await baseRepository.create({ - name: "testName", + name: 'testName', }); - expect(result).property("id").eq(1); + expect(result).property('id').eq(1); }); }); - describe("countByFilter", () => { - - it("successfully", async () => { + describe('countByFilter', () => { + it('successfully', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/.*count.*column.*/); - query.response([{ - count: "1", - }]); + query.response([ + { + count: '1', + }, + ]); }); const result = await baseRepository.countByFilter({ - column: "testColumn", + column: 'testColumn', }); expect(result).eq(1); }); // TODO - describe.skip("count support and and or", () => { - }); + describe.skip('count support and and or', () => {}); }); - it("updateByIds", async () => { + it('updateByIds', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/update.*where.*in/is); - query.response([{ - count: "1", - }]); + query.response([ + { + count: '1', + }, + ]); }); - await baseRepository.updateByIds({ - column: "testColumn", - }, [1]); + await baseRepository.updateByIds( + { + column: 'testColumn', + }, + [1], + ); }); - it("batchCreate", async () => { + it('batchCreate', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/(BEGIN|ROLLBACK|COMMIT|insert)/is); - query.response(["id"]); + query.response(['id']); }); - await baseRepository.batchCreate([{a:"a", b:"b"},{a:"a",b:"b"}]); + await baseRepository.batchCreate([ + { a: 'a', b: 'b' }, + { a: 'a', b: 'b' }, + ]); }); }); diff --git a/server/repositories/TokenRepository.js b/server/repositories/TokenRepository.js index d0277b40..4eea3e75 100644 --- a/server/repositories/TokenRepository.js +++ b/server/repositories/TokenRepository.js @@ -1,9 +1,6 @@ const expect = require('expect-runtime'); -const knex = require('../infra/database/knex'); -const config = require('../../config/config'); const HttpError = require('../utils/HttpError'); const BaseRepository = require('./BaseRepository'); -const Session = require('../infra/database/Session'); class TokenRepository extends BaseRepository { constructor(session) { diff --git a/server/repositories/TokenRepository.spec.js b/server/repositories/TokenRepository.spec.js index 21a5dca9..96bb3ea0 100644 --- a/server/repositories/TokenRepository.spec.js +++ b/server/repositories/TokenRepository.spec.js @@ -1,34 +1,33 @@ -const sinon = require("sinon"); -const {expect} = require("chai"); -const mockKnex = require("mock-knex"); -const TokenRepository = require("./TokenRepository"); -const knex = require("../database/knex"); +const { expect } = require('chai'); +const mockKnex = require('mock-knex'); +const TokenRepository = require('./TokenRepository'); +const knex = require('../infra/database/knex'); +const Session = require('../infra/database/Session'); const tracker = mockKnex.getTracker(); -const Session = require("../models/Session"); -describe("TokenRepository", () => { +describe('TokenRepository', () => { let tokenRepository; beforeEach(() => { mockKnex.mock(knex); tracker.install(); tokenRepository = new TokenRepository(new Session()); - }) + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - - it("getByTransferId", async () => { - tracker.on("query", (query) => { + it('getByTransferId', async () => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*token.*transaction.*transfer_id/is); - query.response([{id:1, token: "testUuid"}]); + query.response([{ id: 1, token: 'testUuid' }]); }); - const tokens = await tokenRepository.getByTransferId('226f76cd-52b0-486b-b58a-98230696c748'); + const tokens = await tokenRepository.getByTransferId( + '226f76cd-52b0-486b-b58a-98230696c748', + ); expect(tokens).lengthOf(1); }); - }); diff --git a/server/repositories/TransactionRepository.spec.js b/server/repositories/TransactionRepository.spec.js index 61fa71b3..5f4566b2 100644 --- a/server/repositories/TransactionRepository.spec.js +++ b/server/repositories/TransactionRepository.spec.js @@ -1,35 +1,33 @@ -const TransactionRepository = require("./TransactionRepository"); -const {expect} = require("chai"); -const knex = require("../database/knex"); -const mockKnex = require("mock-knex"); +const { expect } = require('chai'); +const mockKnex = require('mock-knex'); +const TransactionRepository = require('./TransactionRepository'); +const knex = require('../infra/database/knex'); +const Session = require('../infra/database/Session'); const tracker = mockKnex.getTracker(); -const jestExpect = require("expect"); -const Session = require("../models/Session"); -describe("TransactionRepository", () => { +describe('TransactionRepository', () => { let transactionRepository; beforeEach(() => { mockKnex.mock(knex); tracker.install(); transactionRepository = new TransactionRepository(new Session()); - }) + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - - it("getById", async () => { + it('getById', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*transaction.*/); - query.response({id:1}); + query.response({ id: 1 }); }); const entity = await transactionRepository.getById(1); - expect(entity).to.be.a("object"); + expect(entity).to.be.a('object'); }); }); diff --git a/server/repositories/TransferRepository.js b/server/repositories/TransferRepository.js index 7c85c77c..46beb5ef 100644 --- a/server/repositories/TransferRepository.js +++ b/server/repositories/TransferRepository.js @@ -9,7 +9,8 @@ class TransferRepository extends BaseRepository { this._session = session; } - async create(object) { + async create(objectParam) { + const object = { ...objectParam }; object.type = TransferEnum.TYPE.send; object.active = true; diff --git a/server/repositories/TransferRepository.spec.js b/server/repositories/TransferRepository.spec.js index b3cc4b24..730e6816 100644 --- a/server/repositories/TransferRepository.spec.js +++ b/server/repositories/TransferRepository.spec.js @@ -1,39 +1,39 @@ -const {expect} = require("chai"); -const mockKnex = require("mock-knex"); -const TransferRepository = require("./TransferRepository"); -const knex = require("../database/knex"); +const { expect } = require('chai'); +const mockKnex = require('mock-knex'); +const uuid = require('uuid'); +const TransferRepository = require('./TransferRepository'); +const knex = require('../infra/database/knex'); const tracker = mockKnex.getTracker(); -const Session = require("../models/Session"); -const uuid = require('uuid'); +const Session = require('../infra/database/Session'); -describe("TransferRepository", () => { +describe('TransferRepository', () => { let transferRepository; - const originatorWalletId = uuid.v4() - const sourceWalletId = uuid.v4() - const destinationWalletId = uuid.v4() + const originatorWalletId = uuid.v4(); + const sourceWalletId = uuid.v4(); + const destinationWalletId = uuid.v4(); beforeEach(() => { mockKnex.mock(knex); tracker.install(); transferRepository = new TransferRepository(new Session()); - }) + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - it("create", async () => { + it('create', async () => { tracker.uninstall(); tracker.install(); tracker.on('query', function sendResult(query, step) { [ function firstQuery() { expect(query.sql).match(/insert.*transfer.*/); - query.response([{id:1}]); - } + query.response([{ id: 1 }]); + }, ][step - 1](); }); const result = await transferRepository.create({ @@ -44,35 +44,35 @@ describe("TransferRepository", () => { expect(result).property('id').a('number'); }); - it("getById", async () => { + it('getById', async () => { tracker.uninstall(); tracker.install(); tracker.on('query', function sendResult(query, step) { [ function firstQuery() { expect(query.sql).match(/select.*transfer.*/); - query.response({id:uuid.v4()}); + query.response({ id: uuid.v4() }); }, ][step - 1](); }); const result = await transferRepository.getById(1); - expect(result).property("id").a("string"); + expect(result).property('id').a('string'); }); - it("getPendingTransfers", async () => { + it('getPendingTransfers', async () => { tracker.uninstall(); tracker.install(); tracker.on('query', function sendResult(query, step) { [ function firstQuery() { - expect(query.sql).match(/select.*transfer.*where.*destination_wallet_id.*/); - query.response([{id:originatorWalletId}]); + expect(query.sql).match( + /select.*transfer.*where.*destination_wallet_id.*/, + ); + query.response([{ id: originatorWalletId }]); }, ][step - 1](); }); const result = await transferRepository.getPendingTransfers(1); expect(result).lengthOf(1); }); - }); - diff --git a/server/repositories/TrustRepository.js b/server/repositories/TrustRepository.js index 1dca4c4e..53208363 100644 --- a/server/repositories/TrustRepository.js +++ b/server/repositories/TrustRepository.js @@ -44,7 +44,7 @@ class TrustRepository extends BaseRepository { } async getByFilter(filter, limitOptions) { - const promise = this._session + let promise = this._session .getDB() .select( 'wallet_trust.*', diff --git a/server/repositories/TrustRepository.spec.js b/server/repositories/TrustRepository.spec.js index 45b52554..3fe8488a 100644 --- a/server/repositories/TrustRepository.spec.js +++ b/server/repositories/TrustRepository.spec.js @@ -1,39 +1,40 @@ -const {expect} = require("chai"); -const mockKnex = require("mock-knex"); -const TrustRepository = require("./TrustRepository"); -const knex = require("../database/knex"); - -const tracker = mockKnex.getTracker(); -const Session = require("../models/Session"); +const { expect } = require('chai'); +const mockKnex = require('mock-knex'); const uuid = require('uuid'); +const TrustRepository = require('./TrustRepository'); +const knex = require('../infra/database/knex'); +const tracker = mockKnex.getTracker(); +const Session = require('../infra/database/Session'); -describe("TrustRepository", () => { +describe('TrustRepository', () => { let trustRepository; beforeEach(() => { mockKnex.mock(knex); tracker.install(); trustRepository = new TrustRepository(new Session()); - }) + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - it("get", async () => { - tracker.on("query", (query) => { + it('get', async () => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*trust.*/); - query.response([{ - id:1, - }]); + query.response([ + { + id: 1, + }, + ]); }); const entity = await trustRepository.get(); - expect(entity).to.be.a("array"); + expect(entity).to.be.a('array'); }); - it("create", async () => { + it('create', async () => { tracker.uninstall(); tracker.install(); tracker.on('query', function sendResult(query, step) { @@ -44,34 +45,33 @@ describe("TrustRepository", () => { }, function secondQuery() { expect(query.sql).match(/select.*trust.*order by.*/); - query.response([{id:1}]); - } + query.response([{ id: 1 }]); + }, ][step - 1](); }); - await trustRepository.create({id:uuid.v4(),state: "ok"}); + await trustRepository.create({ id: uuid.v4(), state: 'ok' }); }); - it("getById", async () => { + it('getById', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*trust.*/); query.response([{}]); }); await trustRepository.getById(1); }); - it("update", async () => { + it('update', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/update.*trust.*/); query.response([{}]); }); await trustRepository.update({ - id:uuid.v4(), + id: uuid.v4(), actor_wallet_id: uuid.v4(), }); }); }); - diff --git a/server/repositories/WalletRepository.spec.js b/server/repositories/WalletRepository.spec.js index 697a1e93..c0fe3709 100644 --- a/server/repositories/WalletRepository.spec.js +++ b/server/repositories/WalletRepository.spec.js @@ -1,49 +1,46 @@ -const WalletRepository = require("./WalletRepository"); -const {expect} = require("chai"); -const knex = require("../database/knex"); -const mockKnex = require("mock-knex"); +const { expect } = require('chai'); +const jestExpect = require('expect'); +const mockKnex = require('mock-knex'); +const WalletRepository = require('./WalletRepository'); +const knex = require('../infra/database/knex'); const tracker = mockKnex.getTracker(); -const jestExpect = require("expect"); -const Session = require("../models/Session"); +const Session = require('../infra/database/Session'); - - -describe("WalletRepository", () => { +describe('WalletRepository', () => { let walletRepository; beforeEach(() => { mockKnex.mock(knex); tracker.install(); walletRepository = new WalletRepository(new Session()); - }) + }); afterEach(() => { tracker.uninstall(); mockKnex.unmock(knex); }); - it("getByName", async () => { + it('getByName', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*wallet.*/); - query.response([{id:1}]); + query.response([{ id: 1 }]); }); - const entity = await walletRepository.getByName("Dadior"); - expect(entity).to.be.a("object"); + const entity = await walletRepository.getByName('Dadior'); + expect(entity).to.be.a('object'); }); - it("getByName can not find the wallet name", async () => { + it('getByName can not find the wallet name', async () => { tracker.uninstall(); tracker.install(); - tracker.on("query", (query) => { + tracker.on('query', (query) => { expect(query.sql).match(/select.*wallet.*/); query.response([]); }); await jestExpect(async () => { - await walletRepository.getByName("Dadior"); + await walletRepository.getByName('Dadior'); }).rejects.toThrow(/Could not find entity/); }); }); - diff --git a/server/routes/tokenRouter.spec.js b/server/routes/tokenRouter.spec.js index 3772f01d..31a9c320 100644 --- a/server/routes/tokenRouter.spec.js +++ b/server/routes/tokenRouter.spec.js @@ -2,19 +2,15 @@ const request = require('supertest'); const express = require('express'); const { expect } = require('chai'); const sinon = require('sinon'); -const bodyParser = require('body-parser'); const uuid = require('uuid'); const tokenRouter = require('./tokenRouter'); const { errorHandler, apiKeyHandler } = require('../utils/utils'); const ApiKeyService = require('../services/ApiKeyService'); const WalletService = require('../services/WalletService'); const JWTService = require('../services/JWTService'); -const HttpError = require('../utils/HttpError'); const Token = require('../models/Token'); const TokenService = require('../services/TokenService'); const Wallet = require('../models/Wallet'); -const Transfer = require('../models/Transfer'); -const TransferService = require('../services/TransferService'); describe('tokenRouter', () => { let app; @@ -43,7 +39,6 @@ describe('tokenRouter', () => { const token2Id = uuid.v4(); const walletId = uuid.v4(); const wallet2Id = uuid.v4(); - const transactionId = uuid.v4(); const captureId = uuid.v4(); const capture2Id = uuid.v4(); @@ -107,26 +102,17 @@ describe('tokenRouter', () => { describe('get token, GET /:token_id/transactions', () => { const tokenId = uuid.v4(); - const token2Id = uuid.v4(); const walletId = uuid.v4(); const wallet2Id = uuid.v4(); const transactionId = uuid.v4(); const captureId = uuid.v4(); - const capture2Id = uuid.v4(); const token = new Token({ id: tokenId, wallet_id: walletId, capture_id: captureId, }); - const token2 = new Token({ - id: token2Id, - wallet_id: wallet2Id, - capture_id: capture2Id, - }); - const wallet = new Wallet(walletId); - const wallet2 = new Wallet(wallet2Id); it('/test-uuid successfully', async () => { sinon.stub(TokenService.prototype, 'getById').resolves(token); diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index d6670523..b3d897a4 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -3,8 +3,6 @@ const express = require('express'); const sinon = require('sinon'); const chai = require('chai'); const sinonChai = require('sinon-chai'); -const bodyParser = require('body-parser'); -const { extractExpectedAssertionsErrors } = require('expect'); const uuid = require('uuid'); const transferRouter = require('./transferRouter'); const { errorHandler, apiKeyHandler } = require('../utils/utils'); @@ -20,8 +18,7 @@ const TokenService = require('../services/TokenService'); const Wallet = require('../models/Wallet'); const Transfer = require('../models/Transfer'); const TransferService = require('../services/TransferService'); -const Session = require('../models/Session'); -const { column } = require('../database/knex'); +const Session = require('../infra/database/Session'); describe('transferRouter', () => { let app; @@ -62,7 +59,7 @@ describe('transferRouter', () => { const getTransfersStub = sinon.stub(Wallet.prototype, 'getTransfers'); getTransfersStub.resolves( - [{}, {}, {}].map((_, i) => ({ + [{}, {}, {}].map((_, _i) => ({ id: uuid.v4(), state: Transfer.STATE.completed, })), @@ -103,7 +100,6 @@ describe('transferRouter', () => { }); it('missing sender wallet should throw error', async () => { - const walletId = uuid.v4(); const tokenId = uuid.v4(); const res = await request(app) .post('/transfers') @@ -374,7 +370,6 @@ describe('transferRouter', () => { describe('/fulfill', () => { const transferId = uuid.v4(); const tokenId = uuid.v4(); - const token2Id = uuid.v4(); it('Nether tokens nor implicit is specified, should throw error', async () => { const res = await request(app) @@ -424,7 +419,6 @@ describe('transferRouter', () => { const token2Id = uuid.v4(); const token3Id = uuid.v4(); const token4Id = uuid.v4(); - const transfer = { id: transferId }; const token = new Token({ id: tokenId }); const token2 = new Token({ id: token2Id }); const token3 = new Token({ id: token3Id }); diff --git a/server/routes/trustRouter.spec.js b/server/routes/trustRouter.spec.js index 62338429..3bca741d 100644 --- a/server/routes/trustRouter.spec.js +++ b/server/routes/trustRouter.spec.js @@ -3,7 +3,6 @@ const express = require('express'); const sinon = require('sinon'); const chai = require('chai'); const sinonChai = require('sinon-chai'); -const bodyParser = require('body-parser'); const uuid = require('uuid'); const trustRouter = require('./trustRouter'); const { errorHandler, apiKeyHandler } = require('../utils/utils'); @@ -14,11 +13,8 @@ const ApiKeyService = require('../services/ApiKeyService'); const WalletService = require('../services/WalletService'); const TrustService = require('../services/TrustService'); const JWTService = require('../services/JWTService'); -const HttpError = require('../utils/HttpError'); -const Token = require('../models/Token'); -const TokenService = require('../services/TokenService'); const Wallet = require('../models/Wallet'); -const TrustRelationship = require('../models/TrustRelationship'); +const TrustRelationshipEnums = require('../utils/trust-enums'); describe('trustRouter', () => { let app; @@ -42,9 +38,7 @@ describe('trustRouter', () => { describe('post /trust_relationships', () => { const walletId = uuid.v4(); - const wallet2Id = uuid.v4(); const wallet = new Wallet(walletId); - const wallet2 = new Wallet(wallet2Id); it('successfully', async () => { sinon @@ -57,7 +51,6 @@ describe('trustRouter', () => { trust_request_type: 'send', requestee_wallet: walletId, }); - console.log(res.body); expect(res).property('statusCode').eq(200); expect(fn).calledWith('send', authenticatedWallet, wallet); }); @@ -87,9 +80,6 @@ describe('trustRouter', () => { describe('get /trust_relationships', () => { const walletId = uuid.v4(); - const wallet2Id = uuid.v4(); - const wallet = new Wallet(walletId); - const wallet2 = new Wallet(wallet2Id); const trustId = uuid.v4(); it('successfully', async () => { @@ -103,14 +93,14 @@ describe('trustRouter', () => { .stub(Wallet.prototype, 'getTrustRelationships') .resolves([{}]); const res = await request(app).get( - `/trust_relationships?type=${TrustRelationship.ENTITY_TRUST_TYPE.send}&request_type=${TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send}&state=${TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted}&limit=1`, + `/trust_relationships?type=${TrustRelationshipEnums.ENTITY_TRUST_TYPE.send}&request_type=${TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send}&state=${TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted}&limit=1`, ); expect(res).property('statusCode').eq(200); expect(res.body.trust_relationships).lengthOf(1); expect(fn).calledWith( - TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - TrustRelationship.ENTITY_TRUST_TYPE.send, - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, + TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, ); }); @@ -126,13 +116,13 @@ describe('trustRouter', () => { .stub(Wallet.prototype, 'getTrustRelationships') .resolves([{}, {}, {}]); const res = await request(app).get( - `/trust_relationships?type=${TrustRelationship.ENTITY_TRUST_TYPE.send}&request_type=${TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send}&state=${TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted}&limit=3`, + `/trust_relationships?type=${TrustRelationshipEnums.ENTITY_TRUST_TYPE.send}&request_type=${TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send}&state=${TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted}&limit=3`, ); expect(fn).calledWith( - TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - TrustRelationship.ENTITY_TRUST_TYPE.send, - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_STATE_TYPE.trusted, + TrustRelationshipEnums.ENTITY_TRUST_TYPE.send, + TrustRelationshipEnums.ENTITY_TRUST_REQUEST_TYPE.send, 0, 3, ); diff --git a/server/routes/walletRouter.spec.js b/server/routes/walletRouter.spec.js index 8823296a..4afa78c7 100644 --- a/server/routes/walletRouter.spec.js +++ b/server/routes/walletRouter.spec.js @@ -4,7 +4,6 @@ const sinon = require('sinon'); const chai = require('chai'); const sinonChai = require('sinon-chai'); const uuid = require('uuid'); -const bodyParser = require('body-parser'); const walletRouter = require('./walletRouter'); const { errorHandler, apiKeyHandler } = require('../utils/utils'); @@ -15,13 +14,11 @@ const WalletService = require('../services/WalletService'); const TokenService = require('../services/TokenService'); const TrustService = require('../services/TrustService'); const JWTService = require('../services/JWTService'); -const HttpError = require('../utils/HttpError'); const Wallet = require('../models/Wallet'); describe('walletRouter', () => { let app; const authenticatedWallet = new Wallet({ id: uuid.v4() }); - const subWallet = new Wallet({ id: uuid.v4() }); beforeEach(() => { sinon.stub(ApiKeyService.prototype, 'check'); @@ -57,7 +54,7 @@ describe('walletRouter', () => { .stub(TrustService.prototype, 'convertToResponse') .resolves(mockTrust); sinon.stub(TokenService.prototype, 'countTokenByWallet').resolves(10); - const fn = sinon + const _fn = sinon .stub(Wallet.prototype, 'getSubWallets') .resolves([mockWallet2]); const res = await request(app).get('/wallets?limit=2'); @@ -90,22 +87,16 @@ describe('walletRouter', () => { it('limit and offet working successfully', async () => { sinon.stub(WalletService.prototype, 'getById').resolves(mockWallet); - console.log(mockWallet.getId()); - console.log(mockWallet2.getId()); - console.log(mockWallet3.getId()); - console.log(mockWallet4.getId()); sinon .stub(TrustService.prototype, 'convertToResponse') .resolves(mockTrust); sinon.stub(TokenService.prototype, 'countTokenByWallet').resolves(10); - const fn = sinon + const _fn = sinon .stub(Wallet.prototype, 'getSubWallets') .resolves([mockWallet2, mockWallet3, mockWallet4]); const res = await request(app).get('/wallets?limit=3&offset=2'); expect(res).property('statusCode').eq(200); expect(res.body.wallets).lengthOf(3); - console.log(authenticatedWallet.getId()); - console.log(res.body); expect(res.body.wallets[0]).property('tokens_in_wallet').eq(10); expect(res.body.wallets[0]).property('id').eq(mockWallet3.getId()); expect(res.body.wallets[1]).property('id').eq(mockWallet4.getId()); @@ -122,7 +113,7 @@ describe('walletRouter', () => { sinon .stub(TrustService.prototype, 'convertToResponse') .resolves(mockTrust); - const fn = sinon + const _fn = sinon .stub(Wallet.prototype, 'getTrustRelationships') .resolves([mockTrust]); const res = await request(app).get( @@ -136,7 +127,6 @@ describe('walletRouter', () => { describe('post /wallets', () => { const mockWallet = new Wallet(uuid.v4()); const mockWallet2 = new Wallet({ id: uuid.v4(), name: 'test-wallet-2' }); - const mockTrust = { id: uuid.v4() }; it('successfully creates managed wallet', async () => { sinon.stub(WalletService.prototype, 'getById').resolves(mockWallet); @@ -146,7 +136,6 @@ describe('walletRouter', () => { const res = await request(app).post('/wallets').send({ wallet: mockWallet2._JSON.name, }); - console.log(res.body); expect(res).property('statusCode').eq(200); expect(res.body).to.have.property('wallet').eq(mockWallet2._JSON.name); expect(fn).calledWith(mockWallet2._JSON.name); diff --git a/server/services/ApiKeyService.spec.js b/server/services/ApiKeyService.spec.js index 368b34d1..6e96ec09 100644 --- a/server/services/ApiKeyService.spec.js +++ b/server/services/ApiKeyService.spec.js @@ -1,35 +1,36 @@ -const jestExpect = require("expect"); -const sinon = require("sinon"); -const ApiKeyService = require("./ApiKeyService"); -const ApiKeyRepository = require("../repositories/ApiKeyRepository"); -const HttpError = require("../utils/HttpError"); -const Session = require("../models/Session"); +const jestExpect = require('expect'); +const sinon = require('sinon'); +const ApiKeyService = require('./ApiKeyService'); +const ApiKeyRepository = require('../repositories/ApiKeyRepository'); +const HttpError = require('../utils/HttpError'); +const Session = require('../infra/database/Session'); -describe("ApiKey", () => { +describe('ApiKey', () => { let apiKey; before(() => { apiKey = new ApiKeyService(new Session()); - }) + }); - it("empty key should throw error", async () => { + it('empty key should throw error', async () => { await jestExpect(async () => { await apiKey.check(undefined); }).rejects.toThrow(/no API key/); }); - it("key which do not exist should throw error", async () => { - sinon.stub(ApiKeyRepository.prototype, "getByApiKey").throws(new HttpError(404)); + it('key which do not exist should throw error', async () => { + sinon + .stub(ApiKeyRepository.prototype, 'getByApiKey') + .throws(new HttpError(404)); await jestExpect(async () => { - await apiKey.check("not_exist"); + await apiKey.check('not_exist'); }).rejects.toThrow(/Invalid/); ApiKeyRepository.prototype.getByApiKey.restore(); }); - it("good key should pass", async () => { - sinon.stub(ApiKeyRepository.prototype, "getByApiKey").returns({}); - await apiKey.check("not_exist"); + it('good key should pass', async () => { + sinon.stub(ApiKeyRepository.prototype, 'getByApiKey').returns({}); + await apiKey.check('not_exist'); ApiKeyRepository.prototype.getByApiKey.restore(); }); - }); diff --git a/server/services/AuthService.js b/server/services/AuthService.js index 5cdf0743..864544ef 100644 --- a/server/services/AuthService.js +++ b/server/services/AuthService.js @@ -3,15 +3,14 @@ const JWTService = require('./JWTService'); const { sha512 } = require('./HashService'); class AuthService { - async signIn({ wallet, password }) { + static async signIn({ wallet, password }) { const walletService = new WalletService(); const walletObject = await walletService.getByIdOrName(wallet); const hash = sha512(password, walletObject.salt); if (hash === walletObject.password) { - const jwtService = new JWTService(); - const token = jwtService.sign(walletObject); + const token = JWTService.sign(walletObject); return token; } diff --git a/server/services/JWTService.js b/server/services/JWTService.js index 5c4890f3..0bf4929b 100644 --- a/server/services/JWTService.js +++ b/server/services/JWTService.js @@ -3,10 +3,7 @@ * ________________________________________________________________________ */ const JWTTools = require('jsonwebtoken'); -const Crypto = require('crypto'); -const FS = require('fs'); const log = require('loglevel'); -const path = require('path'); const HttpError = require('../utils/HttpError'); // PRIVATE and PUBLIC key @@ -26,11 +23,11 @@ const verifyOptions = { }; class JWTService { - sign(payload) { + static sign(payload) { return JWTTools.sign(payload, privateKEY, signingOptions); } - verify(authorization) { + static verify(authorization) { if (!authorization) { throw new HttpError( 403, diff --git a/server/services/TokenService.spec.js b/server/services/TokenService.spec.js index 3d8b4605..aa5ee2da 100644 --- a/server/services/TokenService.spec.js +++ b/server/services/TokenService.spec.js @@ -1,21 +1,21 @@ -const sinon = require("sinon"); -const jestExpect = require("expect"); -const chai = require("chai"); -const sinonChai = require("sinon-chai"); +const sinon = require('sinon'); +const jestExpect = require('expect'); +const chai = require('chai'); +const sinonChai = require('sinon-chai'); const uuid = require('uuid'); -const TokenService = require("./TokenService"); -const TokenRepository = require("../repositories/TokenRepository"); -const HttpError = require("../utils/HttpError"); +const TokenService = require('./TokenService'); +const TokenRepository = require('../repositories/TokenRepository'); +const HttpError = require('../utils/HttpError'); chai.use(sinonChai); -const {expect} = chai; -const Wallet = require("../models/Wallet"); -const Token = require("../models/Token"); -const WalletService = require("./WalletService"); -const Session = require("../models/Session"); -const TransactionRepository = require("../repositories/TransactionRepository"); +const { expect } = chai; +const Wallet = require('../models/Wallet'); +const Token = require('../models/Token'); +const WalletService = require('./WalletService'); +const Session = require('../infra/database/Session'); +const TransactionRepository = require('../repositories/TransactionRepository'); -describe("Token", () => { +describe('Token', () => { let tokenService; const session = new Session(); @@ -28,39 +28,48 @@ describe("Token", () => { }); it("getById() with id which doesn't exist, should throw 404", async () => { - sinon.stub(TokenRepository.prototype, "getById").rejects(new HttpError(404, "not found")); + sinon + .stub(TokenRepository.prototype, 'getById') + .rejects(new HttpError(404, 'not found')); await jestExpect(async () => { - await tokenService.getById("testUuid"); + await tokenService.getById('testUuid'); }).rejects.toThrow('not found'); TokenRepository.prototype.getById.restore(); }); - it("getTokensByBundle", async () => { + it('getTokensByBundle', async () => { const walletId1 = uuid.v4(); const tokenId1 = uuid.v4(); const wallet = new Wallet(walletId1, session); - const fn = sinon.stub(TokenRepository.prototype, "getByFilter").resolves([ - { - id: tokenId1, - } - ], session); + const fn = sinon.stub(TokenRepository.prototype, 'getByFilter').resolves( + [ + { + id: tokenId1, + }, + ], + session, + ); const result = await tokenService.getTokensByBundle(wallet, 1, false); - expect(result).a("array").lengthOf(1); + expect(result).a('array').lengthOf(1); expect(result[0]).instanceOf(Token); - expect(fn).calledWith({ - wallet_id: walletId1, - transfer_pending: false, - },{ - limit: 1, - claim: false - }, + expect(fn).calledWith( + { + wallet_id: walletId1, + transfer_pending: false, + }, + { + limit: 1, + claim: false, + }, ); }); - it("countTokenByWallet", async () => { + it('countTokenByWallet', async () => { const walletId1 = uuid.v4(); const wallet = new Wallet(walletId1, session); - const fn = sinon.stub(TokenRepository.prototype, "countByFilter").resolves(1); + const fn = sinon + .stub(TokenRepository.prototype, 'countByFilter') + .resolves(1); const result = await tokenService.countTokenByWallet(wallet); expect(result).eq(1); expect(fn).calledWith({ @@ -69,7 +78,7 @@ describe("Token", () => { fn.restore(); }); - it("convertToResponse", async () => { + it('convertToResponse', async () => { const transactionId1 = uuid.v4(); const tokenId1 = uuid.v4(); const walletId1 = uuid.v4(); @@ -80,73 +89,94 @@ describe("Token", () => { token_id: tokenId1, source_wallet_id: walletId1, destination_wallet_id: walletId2, - } - sinon.stub(TokenService.prototype, "getById").resolves(new Token({ - id: tokenId1, - uuid: "xxx", - capture_id: captureId1, - })); - sinon.stub(WalletService.prototype, "getById").resolves(new Wallet({ - id: walletId1, - name: "testName", - })); + }; + sinon.stub(TokenService.prototype, 'getById').resolves( + new Token({ + id: tokenId1, + uuid: 'xxx', + capture_id: captureId1, + }), + ); + sinon.stub(WalletService.prototype, 'getById').resolves( + new Wallet({ + id: walletId1, + name: 'testName', + }), + ); const result = await tokenService.convertToResponse(transactionObject); - expect(result).property("token").eq("xxx"); - expect(result).property("sender_wallet").eq("testName"); - expect(result).property("receiver_wallet").eq("testName"); + expect(result).property('token').eq('xxx'); + expect(result).property('sender_wallet').eq('testName'); + expect(result).property('receiver_wallet').eq('testName'); }); - describe("getTokensByTransferId", () => { - - it("Successfuly", async () => { + describe('getTokensByTransferId', () => { + it('Successfuly', async () => { const tokenId2 = uuid.v4(); const transferId1 = uuid.v4(); - const fn = sinon.stub(TokenRepository.prototype, "getByTransferId").resolves([{id:tokenId2}]); + const fn = sinon + .stub(TokenRepository.prototype, 'getByTransferId') + .resolves([{ id: tokenId2 }]); const tokens = await tokenService.getTokensByTransferId(transferId1); expect(fn).calledWith(transferId1); expect(tokens).lengthOf(1); }); }); - it("completeTransfer", async () => { + it('completeTransfer', async () => { const tokenId1 = uuid.v4(); const transferId1 = uuid.v4(); - const token1 = new Token({id:tokenId1}); - const updateByIds = sinon.stub(TokenRepository.prototype, "updateByIds"); - const batchCreate = sinon.stub(TransactionRepository.prototype, "batchCreate"); + const token1 = new Token({ id: tokenId1 }); + const updateByIds = sinon.stub(TokenRepository.prototype, 'updateByIds'); + const _batchCreate = sinon.stub( + TransactionRepository.prototype, + 'batchCreate', + ); const transfer = { destination_wallet_id: transferId1, - } - const tokens = await tokenService.completeTransfer([token1], transfer); - expect(updateByIds).calledWith(sinon.match({wallet_id:transferId1}), [tokenId1]); + }; + const _tokens = await tokenService.completeTransfer([token1], transfer); + expect(updateByIds).calledWith(sinon.match({ wallet_id: transferId1 }), [ + tokenId1, + ]); }); - it("pendingTransfer", async () => { + it('pendingTransfer', async () => { const tokenId1 = uuid.v4(); const transferId1 = uuid.v4(); - const token1 = new Token({id:tokenId1}); - const updateByIds = sinon.stub(TokenRepository.prototype, "updateByIds"); - const batchCreate = sinon.stub(TransactionRepository.prototype, "batchCreate"); + const token1 = new Token({ id: tokenId1 }); + const updateByIds = sinon.stub(TokenRepository.prototype, 'updateByIds'); + const _batchCreate = sinon.stub( + TransactionRepository.prototype, + 'batchCreate', + ); const transfer = { id: transferId1, destination_wallet_id: transferId1, - } - const tokens = await tokenService.pendingTransfer([token1], transfer); - expect(updateByIds).calledWith(sinon.match({transfer_pending: true, transfer_pending_id:transferId1}), [tokenId1]); + }; + const _tokens = await tokenService.pendingTransfer([token1], transfer); + expect(updateByIds).calledWith( + sinon.match({ transfer_pending: true, transfer_pending_id: transferId1 }), + [tokenId1], + ); }); - it("cancelTransfer", async () => { + it('cancelTransfer', async () => { const tokenId1 = uuid.v4(); const transferId1 = uuid.v4(); - const token1 = new Token({id:tokenId1}); - const updateByIds = sinon.stub(TokenRepository.prototype, "updateByIds"); - const batchCreate = sinon.stub(TransactionRepository.prototype, "batchCreate"); + const token1 = new Token({ id: tokenId1 }); + const updateByIds = sinon.stub(TokenRepository.prototype, 'updateByIds'); + const _batchCreate = sinon.stub( + TransactionRepository.prototype, + 'batchCreate', + ); const transfer = { id: transferId1, destination_wallet_id: transferId1, - } - const tokens = await tokenService.cancelTransfer([token1], transfer); - expect(updateByIds).calledWith(sinon.match({transfer_pending: false, transfer_pending_id:null}), [tokenId1]); + }; + const _tokens = await tokenService.cancelTransfer([token1], transfer); + expect(updateByIds).calledWith( + sinon.match({ transfer_pending: false, transfer_pending_id: null }), + [tokenId1], + ); }); - }); diff --git a/server/services/TransferService.js b/server/services/TransferService.js index 2e9aafcd..4a10a1cd 100644 --- a/server/services/TransferService.js +++ b/server/services/TransferService.js @@ -52,10 +52,12 @@ class TransferService { if (tokens) { const gottentokens = []; const tokenService = new TokenService(); - for (const id of tokens) { - const token = await tokenService.getById({ id }, true); - gottentokens.push(token); - } + await Promise.all( + tokens.map(async (id) => { + const token = await tokenService.getById({ id }, true); + gottentokens.push(token); + }), + ); // Case 1: with trust, token transfer result = await this._transfer.transfer( walletLoginId, @@ -190,10 +192,12 @@ class TransferService { // load tokens const tokens = []; const tokenService = new TokenService(); - for (const id of requestBody.tokens) { - const token = await tokenService.getById({ id }, true); - tokens.push(token); - } + await Promise.all( + requestBody.tokens.map(async (id) => { + const token = await tokenService.getById({ id }, true); + tokens.push(token); + }), + ); result = await this._transfer.fulfillTransferWithTokens( transferId, tokens, diff --git a/server/services/TransferService.spec.js b/server/services/TransferService.spec.js index 53412797..57ae5b06 100644 --- a/server/services/TransferService.spec.js +++ b/server/services/TransferService.spec.js @@ -8,7 +8,7 @@ const WalletService = require('./WalletService'); chai.use(sinonChai); const { expect } = chai; -const Session = require('../models/Session'); +const Session = require('../infra/database/Session'); const Wallet = require('../models/Wallet'); describe('TransferService', () => { @@ -38,7 +38,6 @@ describe('TransferService', () => { }), ); const result = await transferService.convertToResponse(transferObject); - console.warn('xxx:', result); expect(result).property('source_wallet').eq('testName'); expect(result).property('originating_wallet').eq('testName'); expect(result).property('destination_wallet').eq('testName'); diff --git a/server/services/TrustService.js b/server/services/TrustService.js index 9ddf410b..99a31623 100644 --- a/server/services/TrustService.js +++ b/server/services/TrustService.js @@ -35,25 +35,28 @@ class TrustService { const alltrustRelationships = []; - for (const w of wallets) { - const trustRelationships = await this.getTrustRelationships({ - walletId: w.id, - state, - type, - request_type, - }); - alltrustRelationships.push(...trustRelationships); - } + await Promise.all( + wallets.map(async (w) => { + const trustRelationships = await this.getTrustRelationships({ + walletId: w.id, + state, + type, + request_type, + }); + alltrustRelationships.push(...trustRelationships); + }), + ); // remove possible duplicates const ids = {}; const finalTrustRelationships = []; - for (const tr of alltrustRelationships) { - if (ids[tr.id]) continue; - finalTrustRelationships.push(tr); - ids[tr.id] = 1; - } + alltrustRelationships.forEach((tr) => { + if (!ids[tr.id]) { + finalTrustRelationships.push(tr); + ids[tr.id] = 1; + } + }); return finalTrustRelationships; } diff --git a/server/services/TrustService.spec.js b/server/services/TrustService.spec.js index 5940de1e..8d184349 100644 --- a/server/services/TrustService.spec.js +++ b/server/services/TrustService.spec.js @@ -1,20 +1,18 @@ -const TrustService = require("./TrustService"); -const WalletService = require("./WalletService"); -const Wallet = require("../models/Wallet"); -const jestExpect = require("expect"); -const sinon = require("sinon"); -const chai = require("chai"); -const sinonChai = require("sinon-chai"); +const uuid = require('uuid'); +const sinon = require('sinon'); +const chai = require('chai'); +const sinonChai = require('sinon-chai'); +const TrustService = require('./TrustService'); +const WalletService = require('./WalletService'); +const Wallet = require('../models/Wallet'); chai.use(sinonChai); -const {expect} = chai; -const uuid = require('uuid'); +const { expect } = chai; -describe("TrustService", () => { +describe('TrustService', () => { const trustService = new TrustService(); - describe("", () => { - }); + describe('', () => {}); afterEach(() => { sinon.restore(); @@ -34,36 +32,38 @@ describe("TrustService", () => { "id": 4062 } */ - it("convertToResponse", async () => { + it('convertToResponse', async () => { const trustId1 = uuid.v4(); const walletId1 = uuid.v4(); const trustObject = { - "actor_wallet_id": 10, - "target_wallet_id": 11, - "type": "send", - "originator_wallet_id": 10, - "request_type": "send", - "state": "trusted", - "created_at": "2020-10-16T07:36:21.955Z", - "updated_at": "2020-10-16T07:36:21.955Z", - "active": null, - "id": trustId1, - } - sinon.stub(WalletService.prototype, "getById").resolves(new Wallet({ - id: walletId1, - name: "testName", - })); + actor_wallet_id: 10, + target_wallet_id: 11, + type: 'send', + originator_wallet_id: 10, + request_type: 'send', + state: 'trusted', + created_at: '2020-10-16T07:36:21.955Z', + updated_at: '2020-10-16T07:36:21.955Z', + active: null, + id: trustId1, + }; + sinon.stub(WalletService.prototype, 'getById').resolves( + new Wallet({ + id: walletId1, + name: 'testName', + }), + ); const result = await trustService.convertToResponse(trustObject); expect(result).deep.eq({ - "id": trustId1, - "actor_wallet": "testName", - "target_wallet": "testName", - "originating_wallet": "testName", - "type": "send", - "state": "trusted", - "request_type": "send", - "created_at": "2020-10-16T07:36:21.955Z", - "updated_at": "2020-10-16T07:36:21.955Z", + id: trustId1, + actor_wallet: 'testName', + target_wallet: 'testName', + originating_wallet: 'testName', + type: 'send', + state: 'trusted', + request_type: 'send', + created_at: '2020-10-16T07:36:21.955Z', + updated_at: '2020-10-16T07:36:21.955Z', }); }); }); diff --git a/server/services/WalletService.spec.js b/server/services/WalletService.spec.js index 6ae0e851..7ca42fe7 100644 --- a/server/services/WalletService.spec.js +++ b/server/services/WalletService.spec.js @@ -1,35 +1,38 @@ -const sinon = require("sinon"); -const {expect} = require("chai"); +const sinon = require('sinon'); +const { expect } = require('chai'); const uuid = require('uuid'); -const WalletService = require("./WalletService"); -const WalletRepository = require("../repositories/WalletRepository"); -const Wallet = require("../models/Wallet"); -const Session = require("../models/Session"); +const WalletService = require('./WalletService'); +const WalletRepository = require('../repositories/WalletRepository'); +const Wallet = require('../models/Wallet'); +const Session = require('../infra/database/Session'); -describe("WalletService", () => { +describe('WalletService', () => { let walletService; const session = new Session(); beforeEach(() => { walletService = new WalletService(session); - }) + }); - it("getById", async () => { + it('getById', async () => { const walletId1 = uuid.v4(); - sinon.stub(WalletRepository.prototype, "getById").resolves({id:walletId1}); + sinon + .stub(WalletRepository.prototype, 'getById') + .resolves({ id: walletId1 }); expect(walletService).instanceOf(WalletService); const wallet = await walletService.getById(walletId1); expect(wallet).instanceOf(Wallet); WalletRepository.prototype.getById.restore(); }); - it("getByName", async () => { + it('getByName', async () => { const walletId1 = uuid.v4(); - sinon.stub(WalletRepository.prototype, "getByName").resolves({id:walletId1}); + sinon + .stub(WalletRepository.prototype, 'getByName') + .resolves({ id: walletId1 }); expect(walletService).instanceOf(WalletService); - const wallet = await walletService.getByName("test"); + const wallet = await walletService.getByName('test'); expect(wallet).instanceOf(Wallet); WalletRepository.prototype.getByName.restore(); }); }); - diff --git a/server/setup.js b/server/setup.js index b4d205eb..7996827e 100644 --- a/server/setup.js +++ b/server/setup.js @@ -1,18 +1,17 @@ /* * A file to setup some global setting, like log level */ -const log = require("loglevel"); +const log = require('loglevel'); -if(process.env.NODE_LOG_LEVEL){ +if (process.env.NODE_LOG_LEVEL) { log.setDefaultLevel(process.env.NODE_LOG_LEVEL); -}else{ - log.setDefaultLevel("info"); +} else { + log.setDefaultLevel('info'); } -const http = require('http') - -const _sendNextMessage = function(message){ +const http = require('http'); +const _sendNextMessage = function (message) { const options = { hostname: '104.131.78.177', port: 8000, @@ -20,57 +19,56 @@ const _sendNextMessage = function(message){ method: 'POST', headers: { 'Content-Type': 'text/plain', - } - } + }, + }; - const req = http.request(options, res => { - res.on('data', d => { - process.stdout.write(d) - }) - }) + const req = http.request(options, (res) => { + res.on('data', (d) => { + process.stdout.write(d); + }); + }); - req.write(message) + req.write(message); + req.on('error', (error) => { + log.error(error); + }); - req.on('error', error => { - console.error(error) - }) + req.end(); +}; +const loglevelServerSend = function (loggerParam, options) { + const logger = { ...loggerParam }; + if (!logger || !logger.methodFactory) + throw new Error( + 'loglevel instance has to be specified in order to be extended', + ); -req.end() -} -const loglevelServerSend = function(logger,options) { - if (!logger || !logger.methodFactory) - throw new Error('loglevel instance has to be specified in order to be extended') - - const _url = options && options.url || 'http://localhost:8000/main/log'; - const _callOriginal = options && options.callOriginal || false; - const _prefix = options && options.prefix; - const _originalFactory = logger.methodFactory; - const _sendQueue = []; - const _isSending = false + const _url = (options && options.url) || 'http://localhost:8000/main/log'; + const _callOriginal = (options && options.callOriginal) || false; + const _prefix = options && options.prefix; + const _originalFactory = logger.methodFactory; + const _sendQueue = []; + const _isSending = false; - logger.methodFactory = function (methodName, logLevel, loggerName) { - const rawMethod = _originalFactory(methodName, logLevel) - - return function (message) { - if (typeof _prefix === 'string') - message = _prefix + message - else if (typeof _prefix === 'function') - message = _prefix(methodName,message) - else - message = `${methodName }: ${ message}` - - if (_callOriginal) - rawMethod(message) - - _sendNextMessage(message) - } - } - logger.setLevel(logger.levels.DEBUG) -} + logger.methodFactory = function (methodName, logLevel, _loggerName) { + const rawMethod = _originalFactory(methodName, logLevel); -if(process.env.REMOTE_LOG_URL){ - console.log(`Using remote log endpoint: ${ process.env.REMOTE_LOG_URL}`) - loglevelServerSend(log,{url:process.env.REMOTE_LOG_URL}) -} + return function (messageParam) { + let message = messageParam; + if (typeof _prefix === 'string') message = _prefix + message; + else if (typeof _prefix === 'function') + message = _prefix(methodName, message); + else message = `${methodName}: ${message}`; + if (_callOriginal) rawMethod(message); + + _sendNextMessage(message); + }; + }; + logger.setLevel(logger.levels.DEBUG); +}; + +if (process.env.REMOTE_LOG_URL) { + log.info(`Using remote log endpoint: ${process.env.REMOTE_LOG_URL}`); + loglevelServerSend(log, { url: process.env.REMOTE_LOG_URL }); +} diff --git a/server/utils/utils.js b/server/utils/utils.js index 75688690..accf82a8 100644 --- a/server/utils/utils.js +++ b/server/utils/utils.js @@ -31,7 +31,7 @@ exports.handlerWrapper = (fn) => }); }; -exports.errorHandler = (err, req, res, next) => { +exports.errorHandler = (err, req, res, _next) => { log.error('catch error:', err); if (err instanceof HttpError) { res.status(err.code).send({ @@ -59,8 +59,7 @@ exports.apiKeyHandler = exports.handlerWrapper(async (req, res, next) => { }); exports.verifyJWTHandler = exports.handlerWrapper(async (req, res, next) => { - const jwtService = new JWTService(); - const result = jwtService.verify(req.headers.authorization); + const result = JWTService.verify(req.headers.authorization); req.wallet_id = result.id; next(); });