From a4d12719ce08508a273d8f4f0a20184ea4383beb Mon Sep 17 00:00:00 2001 From: zo-chu Date: Thu, 18 Mar 2021 22:45:29 +0000 Subject: [PATCH 01/42] add limit to token api --- server/routes/tokenRouter.js | 12 +++++++----- server/services/TokenService.js | 7 +++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index 676b1378..69f3137a 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -42,7 +42,7 @@ tokenRouter.get('/', Joi.assert( req.query, Joi.object({ - limit: Joi.number().required(), + limit: Joi.number().min(1).max(1000).required(), start: Joi.number().min(1).max(10000).integer(), wallet: Joi.string(), }) @@ -53,19 +53,21 @@ tokenRouter.get('/', const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); let tokens = []; + if(wallet){ const walletInstance = await walletService.getByName(wallet); const isSub = await walletLogin.hasControlOver(walletInstance); if(!isSub){ - throw new HttpError(403, "Wallet do not belongs to wallet logged in"); + throw new HttpError(403, "Wallet does not belong to wallet logged in"); } - tokens = await tokenService.getByOwner(walletInstance); + tokens = await tokenService.getByOwner(walletInstance, limit); }else{ - tokens = await tokenService.getByOwner(walletLogin); + tokens = await tokenService.getByOwner(walletLogin, limit); } //filter tokens by query, TODO optimization required - tokens = tokens.slice(start? start-1:0, limit); + tokens = tokens.slice(start? start-1:0, limit); // TODO remove + const tokensJson = []; for(const token of tokens){ const json = await token.toJSON(); diff --git a/server/services/TokenService.js b/server/services/TokenService.js index 235a256b..b2379426 100644 --- a/server/services/TokenService.js +++ b/server/services/TokenService.js @@ -20,12 +20,11 @@ class TokenService{ return token; } - async getByOwner(wallet){ + async getByOwner(wallet, limit){ const tokensObject = await this.tokenRepository.getByFilter({ wallet_id: wallet.getId(), - }); - const tokens = tokensObject.map(object => new Token(object, this._session)); - return tokens; + }, limit); + return tokensObject.map(object => new Token(object, this._session)); } async getTokensByPendingTransferId(transferId){ From 6e3014065e56ef5d8cc1dca4b3a468fd74775dbe Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 21 Mar 2021 21:07:48 +0000 Subject: [PATCH 02/42] add offset to tokens api --- server/repositories/BaseRepository.js | 3 ++- server/repositories/BaseRepository.spec.js | 18 +++++++++++++++++- server/routes/tokenRouter.js | 12 ++++++------ server/routes/tokenRouter.spec.js | 4 ++-- server/services/TokenService.js | 4 ++-- 5 files changed, 29 insertions(+), 12 deletions(-) diff --git a/server/repositories/BaseRepository.js b/server/repositories/BaseRepository.js index 074682d2..52a195e2 100644 --- a/server/repositories/BaseRepository.js +++ b/server/repositories/BaseRepository.js @@ -26,6 +26,7 @@ class BaseRepository{ * limit: number */ async getByFilter(filter, options){ + const offset = options && options.offset ? options.offset : 0 const whereBuilder = function(object, builder){ let result = builder; if(object['and']){ @@ -55,7 +56,7 @@ class BaseRepository{ } return result; } - let promise = this._session.getDB().select().table(this._tableName).where(builder => whereBuilder(filter, builder)); + let promise = this._session.getDB().select().table(this._tableName).offset(offset).where(builder => whereBuilder(filter, builder)); if(options && options.limit){ promise = promise.limit(options && options.limit); } diff --git a/server/repositories/BaseRepository.spec.js b/server/repositories/BaseRepository.spec.js index 713a53fe..10ba4821 100644 --- a/server/repositories/BaseRepository.spec.js +++ b/server/repositories/BaseRepository.spec.js @@ -36,7 +36,7 @@ describe("BaseRepository", () => { it.skip("getById can not find result, should throw 404", () => { }); - describe.only("getByFilter", () => { + describe("getByFilter", () => { it("getByFilter", async () => { tracker.uninstall(); @@ -68,6 +68,22 @@ describe("BaseRepository", () => { expect(result[0]).property("id").eq(1); }); + it("getByFilter with offset", async () => { + tracker.uninstall(); + tracker.install(); + tracker.on("query", (query) => { + expect(query.sql).match(/select.*testTable.*offset.*/); + query.response([{id:2}]); + }); + const result = await baseRepository.getByFilter({ + name: "testName", + },{ + offset: 1, + }); + expect(result).lengthOf(1); + expect(result[0]).property("id").eq(2); + }); + describe("'and' 'or' phrase", () => { it("{and: [{c:1}, {b:2}]}", async () => { diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index 69f3137a..a289e0db 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -42,8 +42,8 @@ tokenRouter.get('/', Joi.assert( req.query, Joi.object({ - limit: Joi.number().min(1).max(1000).required(), - start: Joi.number().min(1).max(10000).integer(), + limit: Joi.number().min(1).max(1000).required().default(1000), + start: Joi.number().min(0).max(1000).integer().default(0), wallet: Joi.string(), }) ); @@ -60,13 +60,13 @@ tokenRouter.get('/', if(!isSub){ throw new HttpError(403, "Wallet does not belong to wallet logged in"); } - tokens = await tokenService.getByOwner(walletInstance, limit); + tokens = await tokenService.getByOwner(walletInstance, limit, start); }else{ - tokens = await tokenService.getByOwner(walletLogin, limit); + tokens = await tokenService.getByOwner(walletLogin, limit, start); } - + console.log(tokens) //filter tokens by query, TODO optimization required - tokens = tokens.slice(start? start-1:0, limit); // TODO remove + // tokens = tokens.slice(start? start-1:0, limit); // TODO remove const tokensJson = []; for(const token of tokens){ diff --git a/server/routes/tokenRouter.spec.js b/server/routes/tokenRouter.spec.js index 19138f37..bc2698b0 100644 --- a/server/routes/tokenRouter.spec.js +++ b/server/routes/tokenRouter.spec.js @@ -69,10 +69,10 @@ describe("tokenRouter", () => { }); it("successfully, default wallet", async () => { - sinon.stub(TokenService.prototype, "getByOwner").resolves([token, token2]); + sinon.stub(TokenService.prototype, "getByOwner").resolves([token2]); sinon.stub(WalletService.prototype, "getById").resolves(wallet); const res = await request(app) - .get("/?limit=10&start=2"); + .get("/?limit=10&start=1"); expect(res).property("statusCode").eq(200); expect(res.body.tokens).lengthOf(1); expect(res.body.tokens[0]).property("id").eq(token2Id); diff --git a/server/services/TokenService.js b/server/services/TokenService.js index b2379426..70da884f 100644 --- a/server/services/TokenService.js +++ b/server/services/TokenService.js @@ -20,10 +20,10 @@ class TokenService{ return token; } - async getByOwner(wallet, limit){ + async getByOwner(wallet, limit, offset){ const tokensObject = await this.tokenRepository.getByFilter({ wallet_id: wallet.getId(), - }, limit); + }, {limit, offset}); return tokensObject.map(object => new Token(object, this._session)); } From fd87341edb8811d0e068ac28f0cee63402e2011a Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 21 Mar 2021 21:43:35 +0000 Subject: [PATCH 03/42] add integration tests --- __tests__/get-tokens.spec.js | 52 +++++++++++++++++++++++------------- __tests__/seed.js | 10 +++++++ 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/__tests__/get-tokens.spec.js b/__tests__/get-tokens.spec.js index f2d1bd2e..375b5f86 100644 --- a/__tests__/get-tokens.spec.js +++ b/__tests__/get-tokens.spec.js @@ -1,26 +1,23 @@ /* * The integration test to test the whole business, with DB */ -require('dotenv').config() +require('dotenv').config(); const request = require('supertest'); -const server = require("../server/app"); +const server = require('../server/app'); const { expect } = require('chai'); const seed = require('./seed'); -const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); -const sinon = require("sinon"); -const chai = require("chai"); +const sinon = require('sinon'); +const chai = require('chai'); chai.use(require('chai-uuid')); describe('GET tokens', () => { let bearerToken; let bearerTokenB; - before( async () => { - + beforeEach(async () => { await seed.clear(); await seed.seed(); + sinon.restore(); { // Authorizes before each of the follow tests @@ -51,14 +48,10 @@ describe('GET tokens', () => { } }); - beforeEach(async () => { - sinon.restore(); - }) - it(`walletA, GET /tokens/${seed.token.id} Should be able to get a token `, async () => { const res = await request(server) .get(`/tokens/${seed.token.id}`) - .set('treetracker-api-key',seed.apiKey) + .set('treetracker-api-key', seed.apiKey) .set('Authorization', `Bearer ${bearerToken}`); expect(res).to.have.property('statusCode', 200); expect(res.body).to.have.property('id').eq(seed.token.id); @@ -67,7 +60,7 @@ describe('GET tokens', () => { it(`walletA, GET /tokens/${seed.tokenB.id} Should be forbidden`, async () => { const res = await request(server) .get(`/tokens/${seed.tokenB.id}`) - .set('treetracker-api-key',seed.apiKey) + .set('treetracker-api-key', seed.apiKey) .set('Authorization', `Bearer ${bearerToken}`); expect(res).to.have.property('statusCode', 401); }); @@ -75,7 +68,7 @@ describe('GET tokens', () => { it(`walletA, GET /tokens Should be able to get a token `, async () => { const res = await request(server) .get(`/tokens?limit=10`) - .set('treetracker-api-key',seed.apiKey) + .set('treetracker-api-key', seed.apiKey) .set('Authorization', `Bearer ${bearerToken}`); expect(res).to.have.property('statusCode', 200); expect(res.body.tokens[0]).to.have.property('id').eq(seed.token.id); @@ -84,7 +77,7 @@ describe('GET tokens', () => { it(`walletB, GET /tokens Should be able to get a token, which actually belongs to walletC`, async () => { const res = await request(server) .get(`/tokens?limit=10&wallet=walletC`) - .set('treetracker-api-key',seed.apiKey) + .set('treetracker-api-key', seed.apiKey) .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body.tokens[0]).to.have.property('id').eq(seed.tokenB.id); @@ -93,9 +86,32 @@ describe('GET tokens', () => { it(`walletB, GET /tokens/${seed.tokenB.id} Should be able to get a token `, async () => { const res = await request(server) .get(`/tokens/${seed.tokenB.id}`) - .set('treetracker-api-key',seed.apiKey) + .set('treetracker-api-key', seed.apiKey) .set('Authorization', `Bearer ${bearerTokenB}`); expect(res).to.have.property('statusCode', 200); expect(res.body).to.have.property('id').eq(seed.tokenB.id); }); + it(`GET /tokens/ should return correct limit`, async () => { + await seed.addTokenToWallet(seed.wallet.id); + const res = await request(server) + .get(`/tokens?limit=1`) + .set('treetracker-api-key', seed.apiKey) + .set('Authorization', `Bearer ${bearerToken}`); + + expect(res).to.have.property('statusCode', 200); + expect(res.body.tokens.length).to.eq(1); + expect(res.body.tokens[0].id).eq(seed.token.id); + }); + + it(`GET /tokens/ should return correct offset`, async () => { + const insertedId = (await seed.addTokenToWallet(seed.wallet.id))[0].id; + const res = await request(server) + .get(`/tokens?start=1&limit=10`) + .set('treetracker-api-key', seed.apiKey) + .set('Authorization', `Bearer ${bearerToken}`); + + expect(res).to.have.property('statusCode', 200); + expect(res.body.tokens.length).to.eq(1); + expect(res.body.tokens[0].id).eq(insertedId); + }); }); diff --git a/__tests__/seed.js b/__tests__/seed.js index 29e04971..fc02823f 100644 --- a/__tests__/seed.js +++ b/__tests__/seed.js @@ -147,6 +147,15 @@ async function seed() { .insert(tokenB); } +async function addTokenToWallet(walletId){ + return await knex('token') + .insert({ + id: uuid.v4(), + capture_id: uuid.v4(), + wallet_id: walletId, + }, ['id']); +} + async function clear() { log.debug('clear tables'); await knex('api_key').del(); @@ -168,4 +177,5 @@ module.exports = { token, tokenB, captureB, + addTokenToWallet }; From 37ab1fc9aeb4e1dbee403cbc51f7cd93e2c4706a Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 21 Mar 2021 22:05:14 +0000 Subject: [PATCH 04/42] fix offset and limit for transactions --- server/models/Token.js | 4 ++-- server/routes/tokenRouter.js | 16 ++++------------ server/routes/tokenRouter.spec.js | 19 +++++++++++-------- 3 files changed, 17 insertions(+), 22 deletions(-) diff --git a/server/models/Token.js b/server/models/Token.js index dc4b868b..3cdd5cb2 100644 --- a/server/models/Token.js +++ b/server/models/Token.js @@ -114,10 +114,10 @@ class Token{ } } - async getTransactions(){ + async getTransactions(limit, offset = 0){ const transactions = await this.transactionRepository.getByFilter({ token_id: this._id, - }); + }, {limit, offset}); return transactions; } diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index a289e0db..6933f93c 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -87,8 +87,8 @@ tokenRouter.get('/:id/transactions', Joi.assert( req.query, Joi.object({ - limit: Joi.number().required(), - start: Joi.number().min(1).max(10000).integer(), + limit: Joi.number().min(1).max(1000).integer().default(1000).required(), + start: Joi.number().min(0).max(1000).integer(), id: Joi.string().guid(), transactions: Joi.string(), }) @@ -111,22 +111,14 @@ tokenRouter.get('/:id/transactions', }else{ throw new HttpError(401, "Have no permission to visit this token"); } - const transactions = await token.getTransactions(); + const transactions = await token.getTransactions(limit, start); + let response = []; for(const t of transactions){ const transaction = await tokenService.convertToResponse(t); response.push(transaction); } - //filter transaction json by query - let numStart = parseInt(start); - let numLimit = parseInt(limit); - let numBegin = numStart?numStart-1:0; - let numEnd=numBegin+numLimit; - response = response.slice(numBegin, numEnd); - // console.log(numBegin); - // console.log(numEnd); - // console.log(response); res.status(200).json({ history: response, }); diff --git a/server/routes/tokenRouter.spec.js b/server/routes/tokenRouter.spec.js index bc2698b0..962e6600 100644 --- a/server/routes/tokenRouter.spec.js +++ b/server/routes/tokenRouter.spec.js @@ -179,31 +179,36 @@ describe("tokenRouter", () => { sinon.stub(token, "toJSON").resolves({ wallet_id: walletId, }); - sinon.stub(token, "getTransactions").resolves([ - {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()} + const getTransactionsStub = sinon.stub(token, "getTransactions") + getTransactionsStub.resolves([ + {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()} ]); sinon.stub(WalletService.prototype, "getById").resolves(wallet); sinon.stub(TokenService.prototype, "convertToResponse").resolves({ token: tokenId, sender_wallet: authenticatedWallet, receiver_wallet: wallet2Id, - }).onCall(4).resolves({ + }).onCall(0).resolves({ token: tokenId, sender_wallet: "number5", receiver_wallet: "number5", - }).onCall(5).resolves({ + }).onCall(1).resolves({ token: tokenId, sender_wallet: "number6", receiver_wallet: "number6", - }).onCall(6).resolves({ + }).onCall(2).resolves({ token: tokenId, sender_wallet: "number7", receiver_wallet: "number7", }); sinon.stub(Wallet.prototype, "getSubWallets").resolves([]); + + const limit = "3" + const offset = "5" const res = await request(app) - .get(`/${tokenId}/transactions?limit=3&start=5`); + .get(`/${tokenId}/transactions?limit=${limit}&start=${offset}`); expect(res).property("statusCode").eq(200); + expect(getTransactionsStub.getCall(0).args).deep.to.equal([limit, offset]) expect(res.body.history).lengthOf(3); expect(res.body.history[0]).property("sender_wallet").eq("number5"); expect(res.body.history[0]).property("receiver_wallet").eq("number5"); @@ -213,8 +218,6 @@ describe("tokenRouter", () => { expect(res.body.history[2]).property("sender_wallet").eq("number7"); expect(res.body.history[2]).property("receiver_wallet").eq("number7"); - - }); }); From 56bceb660a9628a9f947c6a30c636732a015fa3c Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 21 Mar 2021 22:06:52 +0000 Subject: [PATCH 05/42] remove comment --- server/routes/tokenRouter.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index 6933f93c..63310170 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -64,9 +64,6 @@ tokenRouter.get('/', }else{ tokens = await tokenService.getByOwner(walletLogin, limit, start); } - console.log(tokens) - //filter tokens by query, TODO optimization required - // tokens = tokens.slice(start? start-1:0, limit); // TODO remove const tokensJson = []; for(const token of tokens){ From 3399cc9a5573a3a80c34aed73cfee1592062b4a6 Mon Sep 17 00:00:00 2001 From: deanchen Date: Mon, 22 Mar 2021 11:28:51 +0800 Subject: [PATCH 06/42] fix: broken test --- server/repositories/BaseRepository.js | 3 --- server/repositories/BaseRepository.spec.js | 4 ++-- server/repositories/TokenRepository.spec.js | 8 -------- server/repositories/TransferRepository.js | 2 +- server/repositories/TransferRepository.spec.js | 4 ++-- server/repositories/TrustRepository.spec.js | 9 ++++++--- 6 files changed, 11 insertions(+), 19 deletions(-) diff --git a/server/repositories/BaseRepository.js b/server/repositories/BaseRepository.js index 52a195e2..d0a5b0c5 100644 --- a/server/repositories/BaseRepository.js +++ b/server/repositories/BaseRepository.js @@ -94,9 +94,6 @@ class BaseRepository{ async create(object){ const result = await this._session.getDB()(this._tableName).insert(object).returning("*"); - expect(result).match([{ - id: expect.anything(), - }]); return result[0]; } diff --git a/server/repositories/BaseRepository.spec.js b/server/repositories/BaseRepository.spec.js index 10ba4821..0311317d 100644 --- a/server/repositories/BaseRepository.spec.js +++ b/server/repositories/BaseRepository.spec.js @@ -5,6 +5,7 @@ const mockKnex = require("mock-knex"); const tracker = mockKnex.getTracker(); const jestExpect = require("expect"); const Session = require("../models/Session"); +const uuid = require('uuid'); describe("BaseRepository", () => { let baseRepository; @@ -211,10 +212,9 @@ describe("BaseRepository", () => { query.response({id:1}); }); const result = await baseRepository.update({ - id: 1, + id: uuid.v4(), name: "testName", }); - expect(result).property("id").eq(1); }); }); diff --git a/server/repositories/TokenRepository.spec.js b/server/repositories/TokenRepository.spec.js index 8c65fb16..686d6417 100644 --- a/server/repositories/TokenRepository.spec.js +++ b/server/repositories/TokenRepository.spec.js @@ -20,14 +20,6 @@ describe("TokenRepository", () => { mockKnex.unmock(knex); }); - it("get by uuid successfully", async () => { - tracker.on("query", (query) => { - expect(query.sql).match(/select.*uuid.*/); - query.response({id:1, token: "testUuid"}); - }); - const token = await tokenRepository.getByUUID("testUuid"); - expect(token).property("token").eq("testUuid"); - }); it("getByTransferId", async () => { tracker.on("query", (query) => { diff --git a/server/repositories/TransferRepository.js b/server/repositories/TransferRepository.js index e2c91dcf..03801b48 100644 --- a/server/repositories/TransferRepository.js +++ b/server/repositories/TransferRepository.js @@ -17,7 +17,7 @@ class TransferRepository extends BaseRepository{ object.active = true; const result = await super.create(object); expect(result).match({ - id: expect.any(String), + id: expect.anything(), }); return result; } diff --git a/server/repositories/TransferRepository.spec.js b/server/repositories/TransferRepository.spec.js index 176f5fb6..7debd965 100644 --- a/server/repositories/TransferRepository.spec.js +++ b/server/repositories/TransferRepository.spec.js @@ -50,12 +50,12 @@ describe("TransferRepository", () => { [ function firstQuery() { expect(query.sql).match(/select.*transfer.*/); - query.response({id:1}); + query.response({id:uuid.v4()}); }, ][step - 1](); }); const result = await transferRepository.getById(1); - expect(result).property("id").eq(1); + expect(result).property("id").a("string"); }); it("getPendingTransfers", async () => { diff --git a/server/repositories/TrustRepository.spec.js b/server/repositories/TrustRepository.spec.js index bbba919e..08048e8b 100644 --- a/server/repositories/TrustRepository.spec.js +++ b/server/repositories/TrustRepository.spec.js @@ -4,6 +4,7 @@ const knex = require("../database/knex"); const mockKnex = require("mock-knex"); const tracker = mockKnex.getTracker(); const Session = require("../models/Session"); +const uuid = require('uuid'); describe("TrustRepository", () => { @@ -46,8 +47,7 @@ describe("TrustRepository", () => { } ][step - 1](); }); - const result = await trustRepository.create({}); - expect(result).property('id').a('number'); + await trustRepository.create({id:uuid.v4(),state: "ok"}); }); it("getById", async () => { @@ -67,7 +67,10 @@ describe("TrustRepository", () => { expect(query.sql).match(/update.*trust.*/); query.response([{}]); }); - await trustRepository.update({id:1}); + await trustRepository.update({ + id:uuid.v4(), + actor_wallet_id: uuid.v4(), + }); }); }); From b97e54c2f70964d2612cebf8a68fab855d902004 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Mon, 22 Mar 2021 21:43:50 +0000 Subject: [PATCH 07/42] add offsets and limit to transfers --- server/models/Wallet.js | 5 ++--- server/routes/transferRouter.js | 13 +++---------- server/routes/transferRouter.spec.js | 26 ++++++-------------------- 3 files changed, 11 insertions(+), 33 deletions(-) diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 336ed7be..1e616e0a 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -844,7 +844,7 @@ class Wallet{ /* * Get all transfers belongs to me */ - async getTransfers(state, wallet){ + async getTransfers(state, wallet, offset = 0, limit){ const filter = { and: [], } @@ -871,8 +871,7 @@ class Wallet{ }] }); } - const result = await this.transferRepository.getByFilter(filter); - return result; + return await this.transferRepository.getByFilter(filter, {offset, limit} ); } async getTransferById(id){ diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 315890a3..ddf461c4 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -271,8 +271,8 @@ transferRouter.get("/", Joi.string(), Joi.number().min(4).max(32) ), - limit: Joi.number().required(), - start: Joi.number().min(1).max(10000).integer() + limit: Joi.number().min(1).max(1000).required(), + start: Joi.number().min(0).max(1000).integer().default(0) }) ); const {state, wallet, limit, start} = req.query; @@ -283,8 +283,7 @@ transferRouter.get("/", if(wallet){ walletTransfer = await walletService.getByIdOrName(wallet); } - - const result = await walletTransfer.getTransfers(state); + const result = await walletTransfer.getTransfers(state, start, limit); const transferService = new TransferService(session); let json = []; for(let t of result){ @@ -292,12 +291,6 @@ transferRouter.get("/", json.push(j); } - //filter tokensJson by query - let numStart = parseInt(start); - let numLimit = parseInt(limit); - let numBegin = numStart?numStart-1:0; - let numEnd=numBegin+numLimit; - json = json.slice(numBegin, numEnd); res.status(200).json({transfers: json}); }) ); diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index 4e6f38c7..10bdabb3 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -59,39 +59,25 @@ describe("transferRouter", () => { .stub(WalletService.prototype, 'getByIdOrName') .resolves(new Wallet(uuid.v4())); - sinon.stub(Wallet.prototype, 'getTransfers').resolves( - [{},{},{},{},{},{},{},{},{},{}].map((_,i) => ({id:uuid.v4(), state:Transfer.STATE.completed}) + const getTransfersStub = sinon.stub(Wallet.prototype, 'getTransfers') + getTransfersStub.resolves( + [{},{},{}].map((_,i) => ({id:uuid.v4(), state:Transfer.STATE.completed}) )); const token0Id = uuid.v4(); const token1Id = uuid.v4(); const token2Id = uuid.v4(); - const token3Id = uuid.v4(); - const token4Id = uuid.v4(); - const token5Id = uuid.v4(); - const token6Id = uuid.v4(); - const token7Id = uuid.v4(); - const token8Id = uuid.v4(); - const token9Id = uuid.v4(); sinon.stub(TransferService.prototype, "convertToResponse") .onCall(0).resolves({id:token0Id, state:Transfer.STATE.completed}) .onCall(1).resolves({id:token1Id, state:Transfer.STATE.completed}) - .onCall(2).resolves({id:token2Id, state:Transfer.STATE.completed}) - .onCall(3).resolves({id:token3Id, state:Transfer.STATE.completed}) - .onCall(4).resolves({id:token4Id, state:Transfer.STATE.completed}) - .onCall(5).resolves({id:token5Id, state:Transfer.STATE.completed}) - .onCall(6).resolves({id:token6Id, state:Transfer.STATE.completed}) - .onCall(7).resolves({id:token7Id, state:Transfer.STATE.completed}) - .onCall(8).resolves({id:token8Id, state:Transfer.STATE.completed}) - .onCall(9).resolves({id:token9Id, state:Transfer.STATE.completed}); + .onCall(2).resolves({id:token2Id, state:Transfer.STATE.completed}); const res = await request(app) .get("/?limit=3&wallet=testWallet&start=5"); expect(res.body.transfers).lengthOf(3); - // console.log("HERE2"); - // console.log(res.body.transfers); - expect(res.body.transfers.map(t=>(t.id))).to.deep.equal([token4Id, token5Id, token6Id]); + expect(getTransfersStub.getCall(0).args[0]).to.deep.equal(undefined, 5, 3) + expect(res.body.transfers.map(t=>(t.id))).to.deep.equal([token0Id, token1Id, token2Id]); }); it("missing tokens should throw error", async () => { From 7c716d8173356140f1348d9f4305c83f4a249841 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Fri, 26 Mar 2021 19:23:56 +0000 Subject: [PATCH 08/42] fix transfer tokens to have offset and limit --- server/models/Wallet.js | 6 +++--- server/repositories/TokenRepository.js | 12 +++++------- server/routes/transferRouter.js | 12 +++--------- server/routes/transferRouter.spec.js | 7 ++++--- server/services/TokenService.js | 8 ++++---- 5 files changed, 19 insertions(+), 26 deletions(-) diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 1e616e0a..4270797e 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -889,13 +889,13 @@ class Wallet{ return transfer; } - async getTokensByTransferId(id){ + async getTokensByTransferId(id, limit, offset){ const transfer = await this.getTransferById(id); let tokens; if(transfer.state === Transfer.STATE.completed){ - tokens = await this.tokenService.getTokensByTransferId(transfer.id); + tokens = await this.tokenService.getTokensByTransferId(transfer.id, limit, offset); }else{ - tokens = await this.tokenService.getTokensByPendingTransferId(transfer.id); + tokens = await this.tokenService.getTokensByPendingTransferId(transfer.id, limit, offset); } return tokens; } diff --git a/server/repositories/TokenRepository.js b/server/repositories/TokenRepository.js index 569fe5a9..156d050f 100644 --- a/server/repositories/TokenRepository.js +++ b/server/repositories/TokenRepository.js @@ -24,16 +24,14 @@ class TokenRepository extends BaseRepository{ /* * select transaction table by transfer id, return matched tokens */ - async getByTransferId(transferId){ - const result = await this._session.getDB().raw(` + async getByTransferId(transferId, limit, offset = 0){ + return await this._session.getDB().raw(` SELECT "token".* FROM "token" JOIN "transaction" - ON "token".id = "transaction".token_id - WHERE "transaction".transfer_id = '226f76cd-52b0-486b-b58a-98230696c748' - `); - return result; + ON "token".id = "transaction".token_id`) + .where("transaction.transfer_id", transferId) // used to be '226f76cd-52b0-486b-b58a-98230696c748' + .limit(limit).offset(offset) } - } module.exports = TokenRepository; diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index ddf461c4..70e857e2 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -329,26 +329,20 @@ transferRouter.get('/:transfer_id/tokens', Joi.assert( req.query, Joi.object({ - limit: Joi.number().required(), - start: Joi.number().min(1).max(10000).integer(), + limit: Joi.number().min(1).max(1000).required(), + start: Joi.number().min(0).max(10000).integer().default(0), }) ); const {limit, start} = req.query; const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id); + const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start)); let tokensJson = []; for(const token of tokens){ const json = await token.toJSON(); tokensJson.push(json); } - //filter tokensJson by query - let numStart = parseInt(start); - let numLimit = parseInt(limit); - let numBegin = numStart?numStart-1:0; - let numEnd=numBegin+numLimit; - tokensJson = tokensJson.slice(numBegin, numEnd); res.status(200).json({ tokens: tokensJson, }); diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index 10bdabb3..3a473e8f 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -374,13 +374,14 @@ describe("transferRouter", () => { it("limit and start working successfully", async () => { const fn = sinon.stub(WalletService.prototype, "getById").resolves(authenticatedWallet); - const fn2 = sinon.stub(Wallet.prototype, "getTokensByTransferId").resolves([token, token2, token3, token4]); + const fn2 = sinon.stub(Wallet.prototype, "getTokensByTransferId").resolves([token2, token3, token4]); const res = await request(app) .get(`/${transferId}/tokens?limit=3&start=2`); expect(fn).calledWith(authenticatedWallet.getId()); - expect(fn2).calledWith(transferId); + + expect(fn2).calledWith(transferId, 3, 2); expect(res).property("statusCode").eq(200); - console.log(res.body); + expect(res.body).property("tokens").lengthOf(3); expect(res.body.tokens.map(t=>(t.id))).to.deep.equal([token2.getId(), token3.getId(), token4.getId()]); }); diff --git a/server/services/TokenService.js b/server/services/TokenService.js index 70da884f..87951c7a 100644 --- a/server/services/TokenService.js +++ b/server/services/TokenService.js @@ -27,10 +27,10 @@ class TokenService{ return tokensObject.map(object => new Token(object, this._session)); } - async getTokensByPendingTransferId(transferId){ + async getTokensByPendingTransferId(transferId, limit, offset = 0){ const result = await this.tokenRepository.getByFilter({ transfer_pending_id: transferId, - }); + }, {limit, offset}); return result.map(object => { return new Token(object, this._session); }); @@ -87,8 +87,8 @@ class TokenService{ return result; } - async getTokensByTransferId(transferId){ - const result = await this.tokenRepository.getByTransferId(transferId); + async getTokensByTransferId(transferId, limit, offset = 0){ + const result = await this.tokenRepository.getByTransferId(transferId, limit, offset); const tokens = []; for(const r of result){ const token = new Token(r); From 02127f7829806a936d63376cc5474ef807a49928 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Fri, 26 Mar 2021 19:45:02 +0000 Subject: [PATCH 09/42] update trust api to have limit and offset in db --- server/models/Wallet.js | 4 ++-- server/repositories/BaseRepository.js | 2 +- server/routes/trustRouter.js | 23 ++++++++--------------- server/routes/trustRouter.spec.js | 14 +++++++------- 4 files changed, 18 insertions(+), 25 deletions(-) diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 4270797e..d213df0e 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -101,7 +101,7 @@ class Wallet{ /* * Get trust relationships by filters, setting filter to undefined to allow all data */ - async getTrustRelationships(state, type, request_type){ + async getTrustRelationships(state, type, request_type, offset, limit){ const filter = { and: [], } @@ -123,7 +123,7 @@ class Wallet{ originator_wallet_id: this._id, }] }); - return await this.trustRepository.getByFilter(filter); + return await this.trustRepository.getByFilter(filter, {offset, limit}); } /* diff --git a/server/repositories/BaseRepository.js b/server/repositories/BaseRepository.js index 52a195e2..fef502dc 100644 --- a/server/repositories/BaseRepository.js +++ b/server/repositories/BaseRepository.js @@ -58,7 +58,7 @@ class BaseRepository{ } let promise = this._session.getDB().select().table(this._tableName).offset(offset).where(builder => whereBuilder(filter, builder)); if(options && options.limit){ - promise = promise.limit(options && options.limit); + promise = promise.limit(options.limit); } const result = await promise; expect(result).a(expect.any(Array)); diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index eddc8c44..de26294a 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -20,8 +20,8 @@ trustRouter.get('/', state: Joi.string(), type: Joi.string(), request_type: Joi.string(), - start: Joi.number(), - limit: Joi.number().min(1).max(10000).integer(), + start: Joi.number().min(0).default(0).integer(), + limit: Joi.number().min(1).max(10000).integer().default(1000), }) ) Joi.assert( @@ -36,9 +36,11 @@ trustRouter.get('/', const trustService = new TrustService(session); const wallet = await walletService.getById(res.locals.wallet_id); const trust_relationships = await wallet.getTrustRelationships( - req.query.state, - req.query.type, - req.query.request_type, + state, + type, + request_type, + Number(start || 0), + Number(limit || 0) ); const subWallets = await wallet.getSubWallets(); for(const sw of subWallets){ @@ -59,16 +61,7 @@ trustRouter.get('/', const j = await trustService.convertToResponse(t); trust_relationships_json.push(j); } - - //filter trust_relationships json by query - let numStart = parseInt(start); - let numLimit = parseInt(limit) ? parseInt(limit) : 0; //TODO: fix this correctly by using db - let numBegin = numStart?numStart-1:0; - let numEnd = numBegin + ((numLimit != 0) ? numLimit : 1000); - if(numEnd != 0){ - trust_relationships_json = trust_relationships_json.slice(numBegin, numEnd); - } - + res.status(200).json({ trust_relationships: trust_relationships_json, }); diff --git a/server/routes/trustRouter.spec.js b/server/routes/trustRouter.spec.js index 1d0e6585..4fa95c3a 100644 --- a/server/routes/trustRouter.spec.js +++ b/server/routes/trustRouter.spec.js @@ -123,19 +123,19 @@ describe("trustRouter", () => { // TODO: need to update the test sinon.stub(WalletService.prototype, "getById").resolves(new Wallet(walletId)); sinon.stub(TrustService.prototype, "convertToResponse").resolves({id:trustId}); - const fn = sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{},{},{},{}]); + const fn = sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{},{},{}]); const res = await request(app) .get(`/?type=${TrustRelationship.ENTITY_TRUST_TYPE.send}&request_type=${TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send}&state=${TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted}&limit=3`); - console.log(res.body); - expect(res).property("statusCode").eq(200); - console.log(res.body.trust_relationships); - //get 3 from 4 items - expect(res.body.trust_relationships).lengthOf(3); + expect(fn).calledWith( TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, TrustRelationship.ENTITY_TRUST_TYPE.send, - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send + TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + 0, + 3 ) + expect(res).property("statusCode").eq(200); + expect(res.body.trust_relationships).lengthOf(3); }); //TODO From c959e156f5879deabdb9b5ae546619734f944ba0 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Sun, 28 Mar 2021 06:03:14 +0000 Subject: [PATCH 10/42] chore(release): 1.12.1 [skip ci] --- CHANGELOG.md | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae7476aa..7d2ff785 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [1.12.1](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.0...v1.12.1) (2021-03-28) + + +### Bug Fixes + +* broken test ([3399cc9](https://github.com/Greenstand/treetracker-wallet-api/commit/3399cc9a5573a3a80c34aed73cfee1592062b4a6)) + # [1.12.0](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.11.2...v1.12.0) (2021-03-26) diff --git a/package.json b/package.json index f5c15e13..72a02ba6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.12.0", + "version": "1.12.1", "description": "https://documenter.getpostman.com/view/10112806/SWTD8H5x?version=latest", "private": true, "main": "server/server.js", From df6092cfd00aa38586d92fe07469d503155765f3 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Mon, 22 Mar 2021 21:43:50 +0000 Subject: [PATCH 11/42] add offsets and limit to transfers --- server/models/Wallet.js | 5 ++--- server/routes/transferRouter.js | 13 +++---------- server/routes/transferRouter.spec.js | 26 ++++++-------------------- 3 files changed, 11 insertions(+), 33 deletions(-) diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 336ed7be..1e616e0a 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -844,7 +844,7 @@ class Wallet{ /* * Get all transfers belongs to me */ - async getTransfers(state, wallet){ + async getTransfers(state, wallet, offset = 0, limit){ const filter = { and: [], } @@ -871,8 +871,7 @@ class Wallet{ }] }); } - const result = await this.transferRepository.getByFilter(filter); - return result; + return await this.transferRepository.getByFilter(filter, {offset, limit} ); } async getTransferById(id){ diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 315890a3..ddf461c4 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -271,8 +271,8 @@ transferRouter.get("/", Joi.string(), Joi.number().min(4).max(32) ), - limit: Joi.number().required(), - start: Joi.number().min(1).max(10000).integer() + limit: Joi.number().min(1).max(1000).required(), + start: Joi.number().min(0).max(1000).integer().default(0) }) ); const {state, wallet, limit, start} = req.query; @@ -283,8 +283,7 @@ transferRouter.get("/", if(wallet){ walletTransfer = await walletService.getByIdOrName(wallet); } - - const result = await walletTransfer.getTransfers(state); + const result = await walletTransfer.getTransfers(state, start, limit); const transferService = new TransferService(session); let json = []; for(let t of result){ @@ -292,12 +291,6 @@ transferRouter.get("/", json.push(j); } - //filter tokensJson by query - let numStart = parseInt(start); - let numLimit = parseInt(limit); - let numBegin = numStart?numStart-1:0; - let numEnd=numBegin+numLimit; - json = json.slice(numBegin, numEnd); res.status(200).json({transfers: json}); }) ); diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index 4e6f38c7..10bdabb3 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -59,39 +59,25 @@ describe("transferRouter", () => { .stub(WalletService.prototype, 'getByIdOrName') .resolves(new Wallet(uuid.v4())); - sinon.stub(Wallet.prototype, 'getTransfers').resolves( - [{},{},{},{},{},{},{},{},{},{}].map((_,i) => ({id:uuid.v4(), state:Transfer.STATE.completed}) + const getTransfersStub = sinon.stub(Wallet.prototype, 'getTransfers') + getTransfersStub.resolves( + [{},{},{}].map((_,i) => ({id:uuid.v4(), state:Transfer.STATE.completed}) )); const token0Id = uuid.v4(); const token1Id = uuid.v4(); const token2Id = uuid.v4(); - const token3Id = uuid.v4(); - const token4Id = uuid.v4(); - const token5Id = uuid.v4(); - const token6Id = uuid.v4(); - const token7Id = uuid.v4(); - const token8Id = uuid.v4(); - const token9Id = uuid.v4(); sinon.stub(TransferService.prototype, "convertToResponse") .onCall(0).resolves({id:token0Id, state:Transfer.STATE.completed}) .onCall(1).resolves({id:token1Id, state:Transfer.STATE.completed}) - .onCall(2).resolves({id:token2Id, state:Transfer.STATE.completed}) - .onCall(3).resolves({id:token3Id, state:Transfer.STATE.completed}) - .onCall(4).resolves({id:token4Id, state:Transfer.STATE.completed}) - .onCall(5).resolves({id:token5Id, state:Transfer.STATE.completed}) - .onCall(6).resolves({id:token6Id, state:Transfer.STATE.completed}) - .onCall(7).resolves({id:token7Id, state:Transfer.STATE.completed}) - .onCall(8).resolves({id:token8Id, state:Transfer.STATE.completed}) - .onCall(9).resolves({id:token9Id, state:Transfer.STATE.completed}); + .onCall(2).resolves({id:token2Id, state:Transfer.STATE.completed}); const res = await request(app) .get("/?limit=3&wallet=testWallet&start=5"); expect(res.body.transfers).lengthOf(3); - // console.log("HERE2"); - // console.log(res.body.transfers); - expect(res.body.transfers.map(t=>(t.id))).to.deep.equal([token4Id, token5Id, token6Id]); + expect(getTransfersStub.getCall(0).args[0]).to.deep.equal(undefined, 5, 3) + expect(res.body.transfers.map(t=>(t.id))).to.deep.equal([token0Id, token1Id, token2Id]); }); it("missing tokens should throw error", async () => { From 29998e859186619bfb4746a5c45bde57a46c7847 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Fri, 26 Mar 2021 19:23:56 +0000 Subject: [PATCH 12/42] fix transfer tokens to have offset and limit --- server/models/Wallet.js | 6 +++--- server/repositories/TokenRepository.js | 12 +++++------- server/routes/transferRouter.js | 12 +++--------- server/routes/transferRouter.spec.js | 7 ++++--- server/services/TokenService.js | 8 ++++---- 5 files changed, 19 insertions(+), 26 deletions(-) diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 1e616e0a..4270797e 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -889,13 +889,13 @@ class Wallet{ return transfer; } - async getTokensByTransferId(id){ + async getTokensByTransferId(id, limit, offset){ const transfer = await this.getTransferById(id); let tokens; if(transfer.state === Transfer.STATE.completed){ - tokens = await this.tokenService.getTokensByTransferId(transfer.id); + tokens = await this.tokenService.getTokensByTransferId(transfer.id, limit, offset); }else{ - tokens = await this.tokenService.getTokensByPendingTransferId(transfer.id); + tokens = await this.tokenService.getTokensByPendingTransferId(transfer.id, limit, offset); } return tokens; } diff --git a/server/repositories/TokenRepository.js b/server/repositories/TokenRepository.js index 569fe5a9..156d050f 100644 --- a/server/repositories/TokenRepository.js +++ b/server/repositories/TokenRepository.js @@ -24,16 +24,14 @@ class TokenRepository extends BaseRepository{ /* * select transaction table by transfer id, return matched tokens */ - async getByTransferId(transferId){ - const result = await this._session.getDB().raw(` + async getByTransferId(transferId, limit, offset = 0){ + return await this._session.getDB().raw(` SELECT "token".* FROM "token" JOIN "transaction" - ON "token".id = "transaction".token_id - WHERE "transaction".transfer_id = '226f76cd-52b0-486b-b58a-98230696c748' - `); - return result; + ON "token".id = "transaction".token_id`) + .where("transaction.transfer_id", transferId) // used to be '226f76cd-52b0-486b-b58a-98230696c748' + .limit(limit).offset(offset) } - } module.exports = TokenRepository; diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index ddf461c4..70e857e2 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -329,26 +329,20 @@ transferRouter.get('/:transfer_id/tokens', Joi.assert( req.query, Joi.object({ - limit: Joi.number().required(), - start: Joi.number().min(1).max(10000).integer(), + limit: Joi.number().min(1).max(1000).required(), + start: Joi.number().min(0).max(10000).integer().default(0), }) ); const {limit, start} = req.query; const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id); + const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start)); let tokensJson = []; for(const token of tokens){ const json = await token.toJSON(); tokensJson.push(json); } - //filter tokensJson by query - let numStart = parseInt(start); - let numLimit = parseInt(limit); - let numBegin = numStart?numStart-1:0; - let numEnd=numBegin+numLimit; - tokensJson = tokensJson.slice(numBegin, numEnd); res.status(200).json({ tokens: tokensJson, }); diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index 10bdabb3..3a473e8f 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -374,13 +374,14 @@ describe("transferRouter", () => { it("limit and start working successfully", async () => { const fn = sinon.stub(WalletService.prototype, "getById").resolves(authenticatedWallet); - const fn2 = sinon.stub(Wallet.prototype, "getTokensByTransferId").resolves([token, token2, token3, token4]); + const fn2 = sinon.stub(Wallet.prototype, "getTokensByTransferId").resolves([token2, token3, token4]); const res = await request(app) .get(`/${transferId}/tokens?limit=3&start=2`); expect(fn).calledWith(authenticatedWallet.getId()); - expect(fn2).calledWith(transferId); + + expect(fn2).calledWith(transferId, 3, 2); expect(res).property("statusCode").eq(200); - console.log(res.body); + expect(res.body).property("tokens").lengthOf(3); expect(res.body.tokens.map(t=>(t.id))).to.deep.equal([token2.getId(), token3.getId(), token4.getId()]); }); diff --git a/server/services/TokenService.js b/server/services/TokenService.js index 70da884f..87951c7a 100644 --- a/server/services/TokenService.js +++ b/server/services/TokenService.js @@ -27,10 +27,10 @@ class TokenService{ return tokensObject.map(object => new Token(object, this._session)); } - async getTokensByPendingTransferId(transferId){ + async getTokensByPendingTransferId(transferId, limit, offset = 0){ const result = await this.tokenRepository.getByFilter({ transfer_pending_id: transferId, - }); + }, {limit, offset}); return result.map(object => { return new Token(object, this._session); }); @@ -87,8 +87,8 @@ class TokenService{ return result; } - async getTokensByTransferId(transferId){ - const result = await this.tokenRepository.getByTransferId(transferId); + async getTokensByTransferId(transferId, limit, offset = 0){ + const result = await this.tokenRepository.getByTransferId(transferId, limit, offset); const tokens = []; for(const r of result){ const token = new Token(r); From 23c573200d2469af81611e71e9fcb773e00fc751 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Fri, 26 Mar 2021 19:45:02 +0000 Subject: [PATCH 13/42] update trust api to have limit and offset in db --- server/models/Wallet.js | 4 ++-- server/repositories/BaseRepository.js | 2 +- server/routes/trustRouter.js | 23 ++++++++--------------- server/routes/trustRouter.spec.js | 14 +++++++------- 4 files changed, 18 insertions(+), 25 deletions(-) diff --git a/server/models/Wallet.js b/server/models/Wallet.js index 4270797e..d213df0e 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -101,7 +101,7 @@ class Wallet{ /* * Get trust relationships by filters, setting filter to undefined to allow all data */ - async getTrustRelationships(state, type, request_type){ + async getTrustRelationships(state, type, request_type, offset, limit){ const filter = { and: [], } @@ -123,7 +123,7 @@ class Wallet{ originator_wallet_id: this._id, }] }); - return await this.trustRepository.getByFilter(filter); + return await this.trustRepository.getByFilter(filter, {offset, limit}); } /* diff --git a/server/repositories/BaseRepository.js b/server/repositories/BaseRepository.js index d0a5b0c5..a873fa31 100644 --- a/server/repositories/BaseRepository.js +++ b/server/repositories/BaseRepository.js @@ -58,7 +58,7 @@ class BaseRepository{ } let promise = this._session.getDB().select().table(this._tableName).offset(offset).where(builder => whereBuilder(filter, builder)); if(options && options.limit){ - promise = promise.limit(options && options.limit); + promise = promise.limit(options.limit); } const result = await promise; expect(result).a(expect.any(Array)); diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index eddc8c44..de26294a 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -20,8 +20,8 @@ trustRouter.get('/', state: Joi.string(), type: Joi.string(), request_type: Joi.string(), - start: Joi.number(), - limit: Joi.number().min(1).max(10000).integer(), + start: Joi.number().min(0).default(0).integer(), + limit: Joi.number().min(1).max(10000).integer().default(1000), }) ) Joi.assert( @@ -36,9 +36,11 @@ trustRouter.get('/', const trustService = new TrustService(session); const wallet = await walletService.getById(res.locals.wallet_id); const trust_relationships = await wallet.getTrustRelationships( - req.query.state, - req.query.type, - req.query.request_type, + state, + type, + request_type, + Number(start || 0), + Number(limit || 0) ); const subWallets = await wallet.getSubWallets(); for(const sw of subWallets){ @@ -59,16 +61,7 @@ trustRouter.get('/', const j = await trustService.convertToResponse(t); trust_relationships_json.push(j); } - - //filter trust_relationships json by query - let numStart = parseInt(start); - let numLimit = parseInt(limit) ? parseInt(limit) : 0; //TODO: fix this correctly by using db - let numBegin = numStart?numStart-1:0; - let numEnd = numBegin + ((numLimit != 0) ? numLimit : 1000); - if(numEnd != 0){ - trust_relationships_json = trust_relationships_json.slice(numBegin, numEnd); - } - + res.status(200).json({ trust_relationships: trust_relationships_json, }); diff --git a/server/routes/trustRouter.spec.js b/server/routes/trustRouter.spec.js index 1d0e6585..4fa95c3a 100644 --- a/server/routes/trustRouter.spec.js +++ b/server/routes/trustRouter.spec.js @@ -123,19 +123,19 @@ describe("trustRouter", () => { // TODO: need to update the test sinon.stub(WalletService.prototype, "getById").resolves(new Wallet(walletId)); sinon.stub(TrustService.prototype, "convertToResponse").resolves({id:trustId}); - const fn = sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{},{},{},{}]); + const fn = sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{},{},{}]); const res = await request(app) .get(`/?type=${TrustRelationship.ENTITY_TRUST_TYPE.send}&request_type=${TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send}&state=${TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted}&limit=3`); - console.log(res.body); - expect(res).property("statusCode").eq(200); - console.log(res.body.trust_relationships); - //get 3 from 4 items - expect(res.body.trust_relationships).lengthOf(3); + expect(fn).calledWith( TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, TrustRelationship.ENTITY_TRUST_TYPE.send, - TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send + TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + 0, + 3 ) + expect(res).property("statusCode").eq(200); + expect(res.body.trust_relationships).lengthOf(3); }); //TODO From 3ec5b007ab84b4864f012c26533a8c19dad38dac Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 28 Mar 2021 21:11:13 +0100 Subject: [PATCH 14/42] fix lost variable --- server/routes/transferRouter.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 70e857e2..7ed398d1 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -283,7 +283,8 @@ transferRouter.get("/", if(wallet){ walletTransfer = await walletService.getByIdOrName(wallet); } - const result = await walletTransfer.getTransfers(state, start, limit); + + const result = await walletTransfer.getTransfers(state, wallet, start, limit); const transferService = new TransferService(session); let json = []; for(let t of result){ @@ -337,7 +338,8 @@ transferRouter.get('/:transfer_id/tokens', const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start)); + const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start || 0)); + let tokensJson = []; for(const token of tokens){ const json = await token.toJSON(); From 11e940192ae35e43a11765bcde1681e836748657 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 28 Mar 2021 21:26:14 +0100 Subject: [PATCH 15/42] fix broken filter, add todo to fully fix --- server/routes/transferRouter.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 7ed398d1..f3f7f8bd 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -279,12 +279,13 @@ transferRouter.get("/", const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); + let walletTransfer = walletLogin; if(wallet){ walletTransfer = await walletService.getByIdOrName(wallet); } - - const result = await walletTransfer.getTransfers(state, wallet, start, limit); + // todo fix filtering by wallet, instead of undefined should take a wallet object with getId() function + const result = await walletTransfer.getTransfers(state, undefined , start, limit); const transferService = new TransferService(session); let json = []; for(let t of result){ From b6aed568f54339392802a1f98e50ff5354ed30f1 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 28 Mar 2021 21:41:08 +0100 Subject: [PATCH 16/42] fix insert --- server/repositories/TokenRepository.js | 7 ++++--- server/repositories/TokenRepository.spec.js | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/server/repositories/TokenRepository.js b/server/repositories/TokenRepository.js index 156d050f..ee2c51ec 100644 --- a/server/repositories/TokenRepository.js +++ b/server/repositories/TokenRepository.js @@ -28,9 +28,10 @@ class TokenRepository extends BaseRepository{ return await this._session.getDB().raw(` SELECT "token".* FROM "token" JOIN "transaction" - ON "token".id = "transaction".token_id`) - .where("transaction.transfer_id", transferId) // used to be '226f76cd-52b0-486b-b58a-98230696c748' - .limit(limit).offset(offset) + ON "token".id = "transaction".token_id + WHERE "transaction".transfer_id = ${transferId} + LIMIT ${limit} + OFFSET ${offset}`) } } diff --git a/server/repositories/TokenRepository.spec.js b/server/repositories/TokenRepository.spec.js index 686d6417..dbafe7a9 100644 --- a/server/repositories/TokenRepository.spec.js +++ b/server/repositories/TokenRepository.spec.js @@ -26,7 +26,7 @@ describe("TokenRepository", () => { expect(query.sql).match(/select.*token.*transaction.*transfer_id/is); query.response([{id:1, token: "testUuid"}]); }); - const tokens = await tokenRepository.getByTransferId("testUuid"); + const tokens = await tokenRepository.getByTransferId('226f76cd-52b0-486b-b58a-98230696c748'); expect(tokens).lengthOf(1); }); From f2557a174fe1fe521bafc300b6e5b4151d586e36 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Sun, 28 Mar 2021 21:51:37 +0100 Subject: [PATCH 17/42] remove max from offset fixes #191 --- server/routes/tokenRouter.js | 4 ++-- server/routes/transferRouter.js | 4 ++-- server/routes/walletRouter.js | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index 63310170..60777dc4 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -43,7 +43,7 @@ tokenRouter.get('/', req.query, Joi.object({ limit: Joi.number().min(1).max(1000).required().default(1000), - start: Joi.number().min(0).max(1000).integer().default(0), + start: Joi.number().min(0).integer().default(0), wallet: Joi.string(), }) ); @@ -85,7 +85,7 @@ tokenRouter.get('/:id/transactions', req.query, Joi.object({ limit: Joi.number().min(1).max(1000).integer().default(1000).required(), - start: Joi.number().min(0).max(1000).integer(), + start: Joi.number().min(0).integer(), id: Joi.string().guid(), transactions: Joi.string(), }) diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index f3f7f8bd..14bee886 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -272,7 +272,7 @@ transferRouter.get("/", Joi.number().min(4).max(32) ), limit: Joi.number().min(1).max(1000).required(), - start: Joi.number().min(0).max(1000).integer().default(0) + start: Joi.number().min(0).integer().default(0) }) ); const {state, wallet, limit, start} = req.query; @@ -332,7 +332,7 @@ transferRouter.get('/:transfer_id/tokens', req.query, Joi.object({ limit: Joi.number().min(1).max(1000).required(), - start: Joi.number().min(0).max(10000).integer().default(0), + start: Joi.number().min(0).integer().default(0), }) ); const {limit, start} = req.query; diff --git a/server/routes/walletRouter.js b/server/routes/walletRouter.js index adb165e2..3016b0e4 100644 --- a/server/routes/walletRouter.js +++ b/server/routes/walletRouter.js @@ -17,7 +17,7 @@ walletRouter.get('/', req.query, Joi.object({ limit: Joi.number().required(), - start: Joi.number().min(1).max(10000).integer(), + start: Joi.number().min(1).integer(), }) ); const {limit, start} = req.query; From bcc816318534727b9e2232ada4e69fa8fc3ea829 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Wed, 31 Mar 2021 21:43:52 +0100 Subject: [PATCH 18/42] start -> offset --- __tests__/get-tokens.spec.js | 2 +- docs/api/spec/treetracker-token-api.yaml | 24 +++++++++---------- .../treetracker-wallet-api-collection.json | 8 +++---- server/routes/tokenRouter.js | 14 +++++------ server/routes/tokenRouter.spec.js | 4 ++-- server/routes/transferRouter.js | 12 +++++----- server/routes/transferRouter.spec.js | 8 +++---- server/routes/trustRouter.js | 6 ++--- server/routes/walletRouter.js | 6 ++--- server/routes/walletRouter.spec.js | 2 +- 10 files changed, 43 insertions(+), 43 deletions(-) diff --git a/__tests__/get-tokens.spec.js b/__tests__/get-tokens.spec.js index 375b5f86..b3525a02 100644 --- a/__tests__/get-tokens.spec.js +++ b/__tests__/get-tokens.spec.js @@ -106,7 +106,7 @@ describe('GET tokens', () => { it(`GET /tokens/ should return correct offset`, async () => { const insertedId = (await seed.addTokenToWallet(seed.wallet.id))[0].id; const res = await request(server) - .get(`/tokens?start=1&limit=10`) + .get(`/tokens?offset=1&limit=10`) .set('treetracker-api-key', seed.apiKey) .set('Authorization', `Bearer ${bearerToken}`); diff --git a/docs/api/spec/treetracker-token-api.yaml b/docs/api/spec/treetracker-token-api.yaml index 1d5b1038..7c042c32 100644 --- a/docs/api/spec/treetracker-token-api.yaml +++ b/docs/api/spec/treetracker-token-api.yaml @@ -56,9 +56,9 @@ paths: type: integer format: int32 example: 10 - - name: start + - name: offset in: query - description: 'Where does the list start, 1 means start from the beginning of the list' + description: 'Where does the list offset, 0 means start from the beginning of the list' required: false style: form explode: true @@ -135,9 +135,9 @@ paths: type: integer format: int32 example: 10 - - name: start + - name: offset in: query - description: 'Where does the list start, 1 means start from the beginning of the list' + description: 'Where does the list offset, 0 means offset from the beginning of the list' required: false style: form explode: true @@ -254,9 +254,9 @@ paths: type: integer format: int32 example: 10 - - name: start + - name: offset in: query - description: 'Where does the list start, 1 means start from the beginning of the list' + description: 'Where does the list offset, 0 means offset from the beginning of the list' required: false style: form explode: true @@ -295,9 +295,9 @@ paths: type: integer format: int32 example: 10 - - name: start + - name: offset in: query - description: 'Where does the list start, 1 means start from the beginning of the list' + description: 'Where does the list offset, 0 means offset from the beginning of the list' required: false style: form explode: true @@ -451,9 +451,9 @@ paths: type: integer format: int32 example: 10 - - name: start + - name: offset in: query - description: 'Where does the list start, 1 means start from the beginning of the list' + description: 'Where does the list offset, 0 means offset from the beginning of the list' required: false style: form explode: true @@ -530,9 +530,9 @@ paths: type: integer format: int32 example: 10 - - name: start + - name: offset in: query - description: 'Where does the list start, 1 means start from the beginning of the list' + description: 'Where does the list offset, 0 means start from the beginning of the list' required: false style: form explode: true diff --git a/docs/api/treetracker-wallet-api-collection.json b/docs/api/treetracker-wallet-api-collection.json index a1653d53..9793583b 100644 --- a/docs/api/treetracker-wallet-api-collection.json +++ b/docs/api/treetracker-wallet-api-collection.json @@ -191,7 +191,7 @@ } ], "url": { - "raw": "{{BASE_URL}}/tokens/:token_uuid/transactions?limit=&start=", + "raw": "{{BASE_URL}}/tokens/:token_uuid/transactions?limit=&offset=", "host": [ "{{BASE_URL}}" ], @@ -207,7 +207,7 @@ "description": "(Required) " }, { - "key": "start", + "key": "offset", "value": "", "description": "(Required) " } @@ -248,7 +248,7 @@ } ], "url": { - "raw": "{{baseUrl}}/tokens/:token_uuid/transactions?limit=10&start=10", + "raw": "{{baseUrl}}/tokens/:token_uuid/transactions?limit=10&offset=10", "host": [ "{{baseUrl}}" ], @@ -263,7 +263,7 @@ "value": "10" }, { - "key": "start", + "key": "offset", "value": "10" } ], diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index 60777dc4..11f38f80 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -43,11 +43,11 @@ tokenRouter.get('/', req.query, Joi.object({ limit: Joi.number().min(1).max(1000).required().default(1000), - start: Joi.number().min(0).integer().default(0), + offset: Joi.number().min(0).integer().default(0), wallet: Joi.string(), }) ); - const {limit, wallet, start} = req.query; + const {limit, wallet, offset} = req.query; const session = new Session(); const tokenService = new TokenService(session); const walletService = new WalletService(session); @@ -60,9 +60,9 @@ tokenRouter.get('/', if(!isSub){ throw new HttpError(403, "Wallet does not belong to wallet logged in"); } - tokens = await tokenService.getByOwner(walletInstance, limit, start); + tokens = await tokenService.getByOwner(walletInstance, limit, offset); }else{ - tokens = await tokenService.getByOwner(walletLogin, limit, start); + tokens = await tokenService.getByOwner(walletLogin, limit, offset); } const tokensJson = []; @@ -85,12 +85,12 @@ tokenRouter.get('/:id/transactions', req.query, Joi.object({ limit: Joi.number().min(1).max(1000).integer().default(1000).required(), - start: Joi.number().min(0).integer(), + offset: Joi.number().min(0).integer(), id: Joi.string().guid(), transactions: Joi.string(), }) ); - const {limit, start} = req.query; + const {limit, offset} = req.query; const session = new Session(); const {id} = req.params; @@ -108,7 +108,7 @@ tokenRouter.get('/:id/transactions', }else{ throw new HttpError(401, "Have no permission to visit this token"); } - const transactions = await token.getTransactions(limit, start); + const transactions = await token.getTransactions(limit, offset); let response = []; for(const t of transactions){ diff --git a/server/routes/tokenRouter.spec.js b/server/routes/tokenRouter.spec.js index 962e6600..ff2760db 100644 --- a/server/routes/tokenRouter.spec.js +++ b/server/routes/tokenRouter.spec.js @@ -72,7 +72,7 @@ describe("tokenRouter", () => { sinon.stub(TokenService.prototype, "getByOwner").resolves([token2]); sinon.stub(WalletService.prototype, "getById").resolves(wallet); const res = await request(app) - .get("/?limit=10&start=1"); + .get("/?limit=10&offset=1"); expect(res).property("statusCode").eq(200); expect(res.body.tokens).lengthOf(1); expect(res.body.tokens[0]).property("id").eq(token2Id); @@ -206,7 +206,7 @@ describe("tokenRouter", () => { const limit = "3" const offset = "5" const res = await request(app) - .get(`/${tokenId}/transactions?limit=${limit}&start=${offset}`); + .get(`/${tokenId}/transactions?limit=${limit}&offset=${offset}`); expect(res).property("statusCode").eq(200); expect(getTransactionsStub.getCall(0).args).deep.to.equal([limit, offset]) expect(res.body.history).lengthOf(3); diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 14bee886..efb7b41c 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -272,10 +272,10 @@ transferRouter.get("/", Joi.number().min(4).max(32) ), limit: Joi.number().min(1).max(1000).required(), - start: Joi.number().min(0).integer().default(0) + offset: Joi.number().min(0).integer().default(0) }) ); - const {state, wallet, limit, start} = req.query; + const {state, wallet, limit, offset} = req.query; const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); @@ -285,7 +285,7 @@ transferRouter.get("/", walletTransfer = await walletService.getByIdOrName(wallet); } // todo fix filtering by wallet, instead of undefined should take a wallet object with getId() function - const result = await walletTransfer.getTransfers(state, undefined , start, limit); + const result = await walletTransfer.getTransfers(state, undefined , offset, limit); const transferService = new TransferService(session); let json = []; for(let t of result){ @@ -332,14 +332,14 @@ transferRouter.get('/:transfer_id/tokens', req.query, Joi.object({ limit: Joi.number().min(1).max(1000).required(), - start: Joi.number().min(0).integer().default(0), + offset: Joi.number().min(0).integer().default(0), }) ); - const {limit, start} = req.query; + const {limit, offset} = req.query; const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start || 0)); + const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(offset || 0)); let tokensJson = []; for(const token of tokens){ diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index 3a473e8f..f4448c23 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -74,7 +74,7 @@ describe("transferRouter", () => { .onCall(2).resolves({id:token2Id, state:Transfer.STATE.completed}); const res = await request(app) - .get("/?limit=3&wallet=testWallet&start=5"); + .get("/?limit=3&wallet=testWallet&offset=5"); expect(res.body.transfers).lengthOf(3); expect(getTransfersStub.getCall(0).args[0]).to.deep.equal(undefined, 5, 3) expect(res.body.transfers.map(t=>(t.id))).to.deep.equal([token0Id, token1Id, token2Id]); @@ -347,7 +347,7 @@ describe("transferRouter", () => { }); }); - describe("GET /{transfer_id}/tokens start and limit working", () => { + describe("GET /{transfer_id}/tokens offset and limit working", () => { const transferId = uuid.v4(); const tokenId = uuid.v4(); @@ -372,11 +372,11 @@ describe("transferRouter", () => { expect(res.body).property("tokens").lengthOf(1); }); - it("limit and start working successfully", async () => { + it("limit and offset working successfully", async () => { const fn = sinon.stub(WalletService.prototype, "getById").resolves(authenticatedWallet); const fn2 = sinon.stub(Wallet.prototype, "getTokensByTransferId").resolves([token2, token3, token4]); const res = await request(app) - .get(`/${transferId}/tokens?limit=3&start=2`); + .get(`/${transferId}/tokens?limit=3&offset=2`); expect(fn).calledWith(authenticatedWallet.getId()); expect(fn2).calledWith(transferId, 3, 2); diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index de26294a..31c4aa10 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -20,7 +20,7 @@ trustRouter.get('/', state: Joi.string(), type: Joi.string(), request_type: Joi.string(), - start: Joi.number().min(0).default(0).integer(), + offset: Joi.number().min(0).default(0).integer(), limit: Joi.number().min(1).max(10000).integer().default(1000), }) ) @@ -30,7 +30,7 @@ trustRouter.get('/', wallet_id: Joi.string().required() }) ) - const {state, type, request_type, limit, start} = req.query; + const {state, type, request_type, limit, offset} = req.query; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -39,7 +39,7 @@ trustRouter.get('/', state, type, request_type, - Number(start || 0), + Number(offset || 0), Number(limit || 0) ); const subWallets = await wallet.getSubWallets(); diff --git a/server/routes/walletRouter.js b/server/routes/walletRouter.js index 3016b0e4..88cc34d3 100644 --- a/server/routes/walletRouter.js +++ b/server/routes/walletRouter.js @@ -17,10 +17,10 @@ walletRouter.get('/', req.query, Joi.object({ limit: Joi.number().required(), - start: Joi.number().min(1).integer(), + offset: Joi.number().min(1).integer(), }) ); - const {limit, start} = req.query; + const {limit, offset} = req.query; const session = new Session(); const walletService = new WalletService(session); const loggedInWallet = await walletService.getById(res.locals.wallet_id); @@ -37,7 +37,7 @@ walletRouter.get('/', walletsJson.push(json); } - let numStart = parseInt(start); + let numStart = parseInt(offset); let numLimit = parseInt(limit); let numBegin = numStart?numStart-1:0; let numEnd=numBegin+numLimit; diff --git a/server/routes/walletRouter.spec.js b/server/routes/walletRouter.spec.js index 95592f17..7ee55af7 100644 --- a/server/routes/walletRouter.spec.js +++ b/server/routes/walletRouter.spec.js @@ -95,7 +95,7 @@ describe("walletRouter", ()=> { sinon.stub(TokenService.prototype, "countTokenByWallet").resolves(10); const fn = sinon.stub(Wallet.prototype, "getSubWallets").resolves([ mockWallet2, mockWallet3, mockWallet4]); const res = await request(app) - .get('/?limit=3&start=2'); + .get('/?limit=3&offset=2'); expect(res).property("statusCode").eq(200); expect(res.body.wallets).lengthOf(3); console.log(authenticatedWallet.getId()); From 8793c732eabca832ced6af7d98a6b0ef884295dc Mon Sep 17 00:00:00 2001 From: Zaven Arra Date: Fri, 2 Apr 2021 14:17:44 -0700 Subject: [PATCH 19/42] fix: update CORS --- README.md | 1 + deployment/treetracker-wallet-api-mapping.yaml | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/README.md b/README.md index 912572ef..49f04e27 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ +as #API Documentation To view the specs for the new API visit https://editor.swagger.io and load the YAML file from /docs/api/spec/treetracker-token-api.yaml diff --git a/deployment/treetracker-wallet-api-mapping.yaml b/deployment/treetracker-wallet-api-mapping.yaml index 20993630..a81da99d 100644 --- a/deployment/treetracker-wallet-api-mapping.yaml +++ b/deployment/treetracker-wallet-api-mapping.yaml @@ -6,3 +6,13 @@ spec: prefix: /wallet/ service: treetracker-wallet-api rewrite: / + cors: + origins: + - https://forestmatic.com + - https://app.forestmatic.com + - https://test-app.forestmatic.com + - https://staging-app.forestmatic.com + methods: GET, OPTIONS + headers: + - Content-Type + - Authorization From 62b2ca1a146e7db5980577b00f84588fd8e6612a Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 2 Apr 2021 21:18:48 +0000 Subject: [PATCH 20/42] chore(release): 1.12.2 [skip ci] --- CHANGELOG.md | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d2ff785..cc367149 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [1.12.2](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.1...v1.12.2) (2021-04-02) + + +### Bug Fixes + +* update CORS ([8793c73](https://github.com/Greenstand/treetracker-wallet-api/commit/8793c732eabca832ced6af7d98a6b0ef884295dc)) + ## [1.12.1](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.0...v1.12.1) (2021-03-28) diff --git a/package.json b/package.json index 72a02ba6..8bb1eda3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.12.1", + "version": "1.12.2", "description": "https://documenter.getpostman.com/view/10112806/SWTD8H5x?version=latest", "private": true, "main": "server/server.js", From 5036b1e20b08b6c1221a4026a63ae4bdf0070b0d Mon Sep 17 00:00:00 2001 From: Zaven Arra Date: Fri, 2 Apr 2021 14:20:40 -0700 Subject: [PATCH 21/42] fix: syntax error --- deployment/treetracker-wallet-api-mapping.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/treetracker-wallet-api-mapping.yaml b/deployment/treetracker-wallet-api-mapping.yaml index a81da99d..e37ac133 100644 --- a/deployment/treetracker-wallet-api-mapping.yaml +++ b/deployment/treetracker-wallet-api-mapping.yaml @@ -6,7 +6,7 @@ spec: prefix: /wallet/ service: treetracker-wallet-api rewrite: / - cors: + cors: origins: - https://forestmatic.com - https://app.forestmatic.com From 801add8d258334c6f947f052350f65ee82ca8101 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 2 Apr 2021 21:21:43 +0000 Subject: [PATCH 22/42] chore(release): 1.12.3 [skip ci] --- CHANGELOG.md | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc367149..5da82872 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [1.12.3](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.2...v1.12.3) (2021-04-02) + + +### Bug Fixes + +* syntax error ([5036b1e](https://github.com/Greenstand/treetracker-wallet-api/commit/5036b1e20b08b6c1221a4026a63ae4bdf0070b0d)) + ## [1.12.2](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.1...v1.12.2) (2021-04-02) diff --git a/package.json b/package.json index 8bb1eda3..11183af9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.12.2", + "version": "1.12.3", "description": "https://documenter.getpostman.com/view/10112806/SWTD8H5x?version=latest", "private": true, "main": "server/server.js", From 1b711a250d440a2b6bb0c709512e93ba4dd8ea57 Mon Sep 17 00:00:00 2001 From: Zaven Arra Date: Sat, 3 Apr 2021 09:19:56 -0700 Subject: [PATCH 23/42] fix: remove unnecessary CORS --- deployment/treetracker-wallet-api-mapping.yaml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/deployment/treetracker-wallet-api-mapping.yaml b/deployment/treetracker-wallet-api-mapping.yaml index e37ac133..20993630 100644 --- a/deployment/treetracker-wallet-api-mapping.yaml +++ b/deployment/treetracker-wallet-api-mapping.yaml @@ -6,13 +6,3 @@ spec: prefix: /wallet/ service: treetracker-wallet-api rewrite: / - cors: - origins: - - https://forestmatic.com - - https://app.forestmatic.com - - https://test-app.forestmatic.com - - https://staging-app.forestmatic.com - methods: GET, OPTIONS - headers: - - Content-Type - - Authorization From ccecf7ea9bae0fb5bbc3b425ace5d234a69aa6c9 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Sat, 3 Apr 2021 16:20:49 +0000 Subject: [PATCH 24/42] chore(release): 1.12.4 [skip ci] --- CHANGELOG.md | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5da82872..9b5e83c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [1.12.4](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.3...v1.12.4) (2021-04-03) + + +### Bug Fixes + +* remove unnecessary CORS ([1b711a2](https://github.com/Greenstand/treetracker-wallet-api/commit/1b711a250d440a2b6bb0c709512e93ba4dd8ea57)) + ## [1.12.3](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.2...v1.12.3) (2021-04-02) diff --git a/package.json b/package.json index 11183af9..fb656629 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.12.3", + "version": "1.12.4", "description": "https://documenter.getpostman.com/view/10112806/SWTD8H5x?version=latest", "private": true, "main": "server/server.js", From 77a39a556adde7bff62a6067a0688f15307ba131 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Mon, 5 Apr 2021 21:10:11 +0100 Subject: [PATCH 25/42] run yarn lint:fix to automatically fix simple issues --- __tests__/auth.spec.js | 8 +- __tests__/bundle-transfer-cancel.spec.js | 10 +- .../bundle-transfer-create-accept.spec.js | 10 +- __tests__/bundle-transfer-decline.spec.js | 10 +- .../fulfill-bundle-transfer-request.spec.js | 10 +- ...fulfill-explicity-transfer-request.spec.js | 10 +- __tests__/get-tokens.spec.js | 4 +- __tests__/integration/auth.spec.js | 2 +- .../bundle-transfer-decline.spec.js | 2 +- __tests__/integration/testUtils.js | 14 +- __tests__/pending-transfer-cancel.spec.js | 10 +- __tests__/pending-transfer-decline.spec.js | 10 +- .../pending-transfer-wrong-wallet.spec.js | 10 +- __tests__/pending-transfer.spec.js | 10 +- __tests__/seed.js | 8 +- __tests__/seed.spec.js | 2 +- __tests__/session.spec.js | 7 +- __tests__/trust-relationship-api.spec.js | 12 +- __tests__/trust-relationship-manage.spec.js | 10 +- .../trust-relationship-send-cancel.spec.js | 10 +- .../trust-relationship-send-decline.spec.js | 10 +- __tests__/trust-relationship-send.spec.js | 10 +- .../20200826045032-CreateSchemaWallets.js | 8 +- .../20200826045033-AddUUIDExtension.js | 10 +- .../20200826045033-CreateTableTransaction.js | 8 +- .../20200830050917-CreateEnumTransferState.js | 8 +- .../20200830050921-CreateEnumTransferType.js | 8 +- ...0901213040-CreateEnumEntityTrustReqType.js | 8 +- ...0200901213111-CreateEnumEntityTrustType.js | 8 +- ...01213222-CreateEnumEntityTrustStateType.js | 8 +- ...eateEnumTransferStateChangeApprovalType.js | 8 +- ...0200901213252-CreateEnumWalletEventType.js | 8 +- .../20200901213253-CreateTableToken.js | 8 +- .../20200901213254-CreateTableTransfer.js | 8 +- .../20200901222910-CreateTableWallet-Event.js | 8 +- .../20200902014751-CreateTableEntity-Trust.js | 8 +- ...00902014758-CreateTableEntity-Trust-Log.js | 8 +- ...0200902014805-CreateTableTransfer-Audit.js | 8 +- .../20200916235257-CreateTableApi-Key.js | 8 +- .../20200917183542-CreateTableWallet.js | 8 +- .../20201127234338-AllowNullPasswordWallet.js | 8 +- .../20201209064928-RenameTableEntityTrust.js | 8 +- ...0201209065300-RenameTableEntityTrustLog.js | 8 +- ...0211020241-AddDefaultIdTransactionTable.js | 23 +-- ...0210211020257-AddDefaultIdTransferTable.js | 23 +-- .../20210211020301-AddDefaultIdTokenTable.js | 23 +-- .../20210211020304-AddDefaultIdWalletTable.js | 23 +-- .../20210211020331-AddDefaultIdApiKeyTable.js | 23 +-- ...11020340-AddDefaultIdTransferAuditTable.js | 23 +-- ...0211020347-AddDefaultIdWalletEventTable.js | 23 +-- ...0211020352-AddDefaultIdWalletTrustTable.js | 23 +-- ...1020356-AddDefaultIdWalletTrustLogTable.js | 23 +-- ...226234313-AddUniqueConstraintWalletName.js | 8 +- ...0304014730-AddUniqueConstraintCaptureId.js | 8 +- scripts/create/clean-up-duplicates.js | 4 +- scripts/create/create-tokens-csv.js | 4 +- scripts/create/create-tokens-fcc.js | 4 +- scripts/create/create-tokens-kijani.js | 2 +- scripts/create/create-wallet.js | 14 +- scripts/demo/create-demo-wallet.js | 14 +- scripts/user/sha.js | 11 +- server/app.js | 15 +- server/app.spec.js | 2 +- server/database/knex.js | 7 +- server/models/Session.js | 4 +- server/models/Session.spec.js | 3 +- server/models/Token.js | 16 +- server/models/Token.spec.js | 11 +- server/models/TrustRelationship.js | 4 +- server/models/TrustRelationship.spec.js | 1 + server/models/Wallet.js | 166 +++++++++--------- server/models/Wallet.spec.js | 17 +- server/repositories/ApiKeyRepository.js | 2 +- server/repositories/ApiKeyRepository.spec.js | 3 +- server/repositories/BaseRepository.js | 26 +-- server/repositories/BaseRepository.spec.js | 7 +- server/repositories/TokenRepository.js | 2 +- server/repositories/TokenRepository.spec.js | 5 +- server/repositories/TransactionRepository.js | 2 +- .../TransactionRepository.spec.js | 1 + server/repositories/TransferRepository.js | 2 +- .../repositories/TransferRepository.spec.js | 5 +- server/repositories/TrustRepository.js | 4 +- server/repositories/TrustRepository.spec.js | 5 +- server/repositories/WalletRepository.js | 2 +- server/repositories/WalletRepository.spec.js | 1 + server/routes/authRouter.js | 3 +- server/routes/authRouter.spec.js | 6 +- server/routes/tokenRouter.js | 12 +- server/routes/tokenRouter.spec.js | 14 +- server/routes/transferRouter.js | 49 +++--- server/routes/transferRouter.spec.js | 13 +- server/routes/trustRouter.js | 13 +- server/routes/trustRouter.spec.js | 15 +- server/routes/utils.js | 2 +- server/routes/utils.spec.js | 16 +- server/routes/walletRouter.js | 14 +- server/routes/walletRouter.spec.js | 9 +- server/server.js | 5 +- server/serverTest.js | 5 +- server/services/ApiKeyService.js | 8 +- server/services/ApiKeyService.spec.js | 2 +- server/services/JWTService.js | 6 +- server/services/JWTService.spec.js | 2 +- server/services/TokenService.js | 6 +- server/services/TokenService.spec.js | 13 +- server/services/TransferService.js | 2 +- server/services/TransferService.spec.js | 7 +- server/services/TrustService.js | 4 +- server/services/TrustService.spec.js | 3 +- server/services/WalletService.js | 4 +- server/services/WalletService.spec.js | 8 +- server/setup.js | 21 +-- server/utils/HttpError.js | 4 +- 114 files changed, 625 insertions(+), 589 deletions(-) diff --git a/__tests__/auth.spec.js b/__tests__/auth.spec.js index 2100fdc8..214a0948 100644 --- a/__tests__/auth.spec.js +++ b/__tests__/auth.spec.js @@ -1,13 +1,13 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); describe('Authentication', () => { diff --git a/__tests__/bundle-transfer-cancel.spec.js b/__tests__/bundle-transfer-cancel.spec.js index 15f32988..f718b6d8 100644 --- a/__tests__/bundle-transfer-cancel.spec.js +++ b/__tests__/bundle-transfer-cancel.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and accept a bundle transfer', () => { diff --git a/__tests__/bundle-transfer-create-accept.spec.js b/__tests__/bundle-transfer-create-accept.spec.js index 16f1de84..b339213c 100644 --- a/__tests__/bundle-transfer-create-accept.spec.js +++ b/__tests__/bundle-transfer-create-accept.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and accept a bundle transfer', () => { diff --git a/__tests__/bundle-transfer-decline.spec.js b/__tests__/bundle-transfer-decline.spec.js index 885d6d3e..03702b3e 100644 --- a/__tests__/bundle-transfer-decline.spec.js +++ b/__tests__/bundle-transfer-decline.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and accept a bundle transfer', () => { diff --git a/__tests__/fulfill-bundle-transfer-request.spec.js b/__tests__/fulfill-bundle-transfer-request.spec.js index 84e5196e..1983af27 100644 --- a/__tests__/fulfill-bundle-transfer-request.spec.js +++ b/__tests__/fulfill-bundle-transfer-request.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Request and fulfill a bundle transfer', () => { diff --git a/__tests__/fulfill-explicity-transfer-request.spec.js b/__tests__/fulfill-explicity-transfer-request.spec.js index f3ca04c4..f2240566 100644 --- a/__tests__/fulfill-explicity-transfer-request.spec.js +++ b/__tests__/fulfill-explicity-transfer-request.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Request and fulfill an explicit transfer', () => { diff --git a/__tests__/get-tokens.spec.js b/__tests__/get-tokens.spec.js index 375b5f86..f61165e9 100644 --- a/__tests__/get-tokens.spec.js +++ b/__tests__/get-tokens.spec.js @@ -3,11 +3,11 @@ */ require('dotenv').config(); const request = require('supertest'); -const server = require('../server/app'); const { expect } = require('chai'); -const seed = require('./seed'); const sinon = require('sinon'); const chai = require('chai'); +const seed = require('./seed'); +const server = require('../server/app'); chai.use(require('chai-uuid')); describe('GET tokens', () => { diff --git a/__tests__/integration/auth.spec.js b/__tests__/integration/auth.spec.js index 1f19d965..5849f4ac 100644 --- a/__tests__/integration/auth.spec.js +++ b/__tests__/integration/auth.spec.js @@ -1,10 +1,10 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../../server/app"); const { expect } = require('chai'); const log = require('loglevel'); const sinon = require("sinon"); 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"); diff --git a/__tests__/integration/bundle-transfer-decline.spec.js b/__tests__/integration/bundle-transfer-decline.spec.js index cd79a4d7..f2b444f8 100644 --- a/__tests__/integration/bundle-transfer-decline.spec.js +++ b/__tests__/integration/bundle-transfer-decline.spec.js @@ -1,9 +1,9 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../../server/app"); const { expect } = require('chai'); const log = require('loglevel'); const chai = require("chai"); +const server = require("../../server/app"); chai.use(require('chai-uuid')); const Zaven = require("../mock-data/Zaven.json"); const Meisze = require("../mock-data/Meisze.json"); diff --git a/__tests__/integration/testUtils.js b/__tests__/integration/testUtils.js index 8488ae6c..6255fae4 100644 --- a/__tests__/integration/testUtils.js +++ b/__tests__/integration/testUtils.js @@ -1,24 +1,24 @@ -const knex = require("../../server/database/knex"); const uuid = require('uuid'); const log = require("loglevel"); const Crypto = require('crypto'); const generator = require('generate-password'); +const { expect } = require('chai'); const JWTService = require("../../server/services/JWTService"); const Transfer = require("../../server/models/Transfer"); -const { expect } = require('chai'); +const knex = require("../../server/database/knex"); /* * register the user, create password hash, and apiKey */ async function register(user){ const sha512 = function(password, salt){ - var hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ + const hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ hash.update(password); - var value = hash.digest('hex'); + const value = hash.digest('hex'); return value; }; - const salt = Crypto.randomBytes(32).toString('base64') //create a secure salt + const salt = Crypto.randomBytes(32).toString('base64') // create a secure salt const passwordHash = sha512(user.password, salt) const apiKey = generator.generate({ @@ -41,13 +41,13 @@ async function register(user){ id: uuid.v4(), name: user.name, password: passwordHash, - salt: salt, + salt, }).returning("*"); log.info("registered wallet:", result); return { ...result[0], apiKey, - //restore password + // restore password password: user.password, }; } diff --git a/__tests__/pending-transfer-cancel.spec.js b/__tests__/pending-transfer-cancel.spec.js index 1c67fc9c..9db0927b 100644 --- a/__tests__/pending-transfer-cancel.spec.js +++ b/__tests__/pending-transfer-cancel.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and cancel a pending transfer', () => { let bearerToken; diff --git a/__tests__/pending-transfer-decline.spec.js b/__tests__/pending-transfer-decline.spec.js index 9cb4203d..7c750a2a 100644 --- a/__tests__/pending-transfer-decline.spec.js +++ b/__tests__/pending-transfer-decline.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and decline a pending transfer', () => { let bearerToken; diff --git a/__tests__/pending-transfer-wrong-wallet.spec.js b/__tests__/pending-transfer-wrong-wallet.spec.js index 7613adad..beb7fa79 100644 --- a/__tests__/pending-transfer-wrong-wallet.spec.js +++ b/__tests__/pending-transfer-wrong-wallet.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and fail to accept a pending transfer with wrong wallet', () => { let bearerToken; diff --git a/__tests__/pending-transfer.spec.js b/__tests__/pending-transfer.spec.js index e10ddc4a..b1db3490 100644 --- a/__tests__/pending-transfer.spec.js +++ b/__tests__/pending-transfer.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Create and accept a pending transfer', () => { let bearerToken; diff --git a/__tests__/seed.js b/__tests__/seed.js index fc02823f..f6c041e6 100644 --- a/__tests__/seed.js +++ b/__tests__/seed.js @@ -86,7 +86,7 @@ storyOfThisSeed, async function seed() { log.debug('seed api key'); - //TODO should use appropriate hash & salt to populate this table + // TODO should use appropriate hash & salt to populate this table await knex('api_key') .insert({ key: apiKey, @@ -105,7 +105,7 @@ async function seed() { salt: wallet.salt, }); - //walletB + // walletB await knex('wallet') .insert({ id: walletB.id, @@ -114,7 +114,7 @@ async function seed() { salt: walletB.salt, }); - //walletC + // walletC await knex('wallet') .insert({ id: walletC.id, @@ -123,7 +123,7 @@ async function seed() { salt: walletC.salt, }); - //relationships: 'walletB' manage 'walletC' + // relationships: 'walletB' manage 'walletC' await knex('wallet_trust') .insert({ type: "manage", diff --git a/__tests__/seed.spec.js b/__tests__/seed.spec.js index b4819deb..9521a00c 100644 --- a/__tests__/seed.spec.js +++ b/__tests__/seed.spec.js @@ -1,7 +1,7 @@ -const seed = require("./seed"); const {expect} = require("chai"); const Crypto = require('crypto'); const log = require("loglevel"); +const seed = require("./seed"); const knex = require("../server/database/knex"); describe("Seed data into DB", () => { diff --git a/__tests__/session.spec.js b/__tests__/session.spec.js index 466af2da..694e3ceb 100644 --- a/__tests__/session.spec.js +++ b/__tests__/session.spec.js @@ -1,19 +1,20 @@ /* * Test session mechanism */ -const seed = require('./seed'); -const Session = require("../server/models/Session"); const jestExpect = require("expect"); const sinon = require("sinon"); const chai = require("chai"); const sinonChai = require("sinon-chai"); +const Session = require("../server/models/Session"); +const seed = require('./seed'); + chai.use(sinonChai); const {expect} = chai; describe("Session integration", () => { beforeEach(async () => { - //before all, seed data to DB + // before all, seed data to DB await seed.clear(); await seed.seed(); diff --git a/__tests__/trust-relationship-api.spec.js b/__tests__/trust-relationship-api.spec.js index 19c772c0..39397a58 100644 --- a/__tests__/trust-relationship-api.spec.js +++ b/__tests__/trust-relationship-api.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Trust relationship management', () => { @@ -122,7 +122,7 @@ describe('Trust relationship management', () => { it(`${seed.walletB.name} try to request "manage" relationship to ${seed.wallet.name}`, async () => { await seed.clear(); await seed.seed(); - let res = await request(server) + const res = await request(server) .post("/trust_relationships") .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerTokenB}`) diff --git a/__tests__/trust-relationship-manage.spec.js b/__tests__/trust-relationship-manage.spec.js index bffda97b..ab2c16cd 100644 --- a/__tests__/trust-relationship-manage.spec.js +++ b/__tests__/trust-relationship-manage.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Trust relationship: manage', () => { diff --git a/__tests__/trust-relationship-send-cancel.spec.js b/__tests__/trust-relationship-send-cancel.spec.js index cd517302..7b8f8ee4 100644 --- a/__tests__/trust-relationship-send-cancel.spec.js +++ b/__tests__/trust-relationship-send-cancel.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Trust relationship: decline send', () => { let bearerToken; diff --git a/__tests__/trust-relationship-send-decline.spec.js b/__tests__/trust-relationship-send-decline.spec.js index cc43a983..f3f10b2c 100644 --- a/__tests__/trust-relationship-send-decline.spec.js +++ b/__tests__/trust-relationship-send-decline.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Trust relationship: decline send', () => { let bearerToken; diff --git a/__tests__/trust-relationship-send.spec.js b/__tests__/trust-relationship-send.spec.js index 7987495e..7ad4ccf0 100644 --- a/__tests__/trust-relationship-send.spec.js +++ b/__tests__/trust-relationship-send.spec.js @@ -1,16 +1,16 @@ require('dotenv').config() const request = require('supertest'); -const server = require("../server/app"); const { expect } = require('chai'); -const seed = require('./seed'); const log = require('loglevel'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); const sinon = require("sinon"); const chai = require("chai"); +const server = require("../server/app"); +const seed = require('./seed'); +const Transfer = require("../server/models/Transfer"); +const TrustRelationship = require("../server/models/TrustRelationship"); chai.use(require('chai-uuid')); -const apiKey = seed.apiKey; +const {apiKey} = seed; describe('Trust relationship: send', () => { let bearerToken; diff --git a/database/migrations/20200826045032-CreateSchemaWallets.js b/database/migrations/20200826045032-CreateSchemaWallets.js index eaf38385..61baf515 100644 --- a/database/migrations/20200826045032-CreateSchemaWallets.js +++ b/database/migrations/20200826045032-CreateSchemaWallets.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200826045033-AddUUIDExtension.js b/database/migrations/20200826045033-AddUUIDExtension.js index 4e864626..2cf78c82 100644 --- a/database/migrations/20200826045033-AddUUIDExtension.js +++ b/database/migrations/20200826045033-AddUUIDExtension.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,7 +19,7 @@ exports.up = function(db) { }; exports.down = function(db, done) { - //return db.runSql('DROP EXTENSION "uuid-ossp"'); + // return db.runSql('DROP EXTENSION "uuid-ossp"'); done() }; diff --git a/database/migrations/20200826045033-CreateTableTransaction.js b/database/migrations/20200826045033-CreateTableTransaction.js index 2ceb73b3..f186e520 100644 --- a/database/migrations/20200826045033-CreateTableTransaction.js +++ b/database/migrations/20200826045033-CreateTableTransaction.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200830050917-CreateEnumTransferState.js b/database/migrations/20200830050917-CreateEnumTransferState.js index 5ac990a7..e197dc0f 100644 --- a/database/migrations/20200830050917-CreateEnumTransferState.js +++ b/database/migrations/20200830050917-CreateEnumTransferState.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200830050921-CreateEnumTransferType.js b/database/migrations/20200830050921-CreateEnumTransferType.js index 3a0c099e..0ba19542 100644 --- a/database/migrations/20200830050921-CreateEnumTransferType.js +++ b/database/migrations/20200830050921-CreateEnumTransferType.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213040-CreateEnumEntityTrustReqType.js b/database/migrations/20200901213040-CreateEnumEntityTrustReqType.js index 467d5562..20bedb19 100644 --- a/database/migrations/20200901213040-CreateEnumEntityTrustReqType.js +++ b/database/migrations/20200901213040-CreateEnumEntityTrustReqType.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213111-CreateEnumEntityTrustType.js b/database/migrations/20200901213111-CreateEnumEntityTrustType.js index 4d03849d..d822a516 100644 --- a/database/migrations/20200901213111-CreateEnumEntityTrustType.js +++ b/database/migrations/20200901213111-CreateEnumEntityTrustType.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213222-CreateEnumEntityTrustStateType.js b/database/migrations/20200901213222-CreateEnumEntityTrustStateType.js index 585b3341..63232f43 100644 --- a/database/migrations/20200901213222-CreateEnumEntityTrustStateType.js +++ b/database/migrations/20200901213222-CreateEnumEntityTrustStateType.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213241-CreateEnumTransferStateChangeApprovalType.js b/database/migrations/20200901213241-CreateEnumTransferStateChangeApprovalType.js index f05c8278..97c098e8 100644 --- a/database/migrations/20200901213241-CreateEnumTransferStateChangeApprovalType.js +++ b/database/migrations/20200901213241-CreateEnumTransferStateChangeApprovalType.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213252-CreateEnumWalletEventType.js b/database/migrations/20200901213252-CreateEnumWalletEventType.js index 0a63b356..e2dcc08b 100644 --- a/database/migrations/20200901213252-CreateEnumWalletEventType.js +++ b/database/migrations/20200901213252-CreateEnumWalletEventType.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213253-CreateTableToken.js b/database/migrations/20200901213253-CreateTableToken.js index b3ffd0d7..ffbcd141 100644 --- a/database/migrations/20200901213253-CreateTableToken.js +++ b/database/migrations/20200901213253-CreateTableToken.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901213254-CreateTableTransfer.js b/database/migrations/20200901213254-CreateTableTransfer.js index 4df57f1a..b6edb1cd 100644 --- a/database/migrations/20200901213254-CreateTableTransfer.js +++ b/database/migrations/20200901213254-CreateTableTransfer.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200901222910-CreateTableWallet-Event.js b/database/migrations/20200901222910-CreateTableWallet-Event.js index b7a7a90c..89ddd7ae 100644 --- a/database/migrations/20200901222910-CreateTableWallet-Event.js +++ b/database/migrations/20200901222910-CreateTableWallet-Event.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200902014751-CreateTableEntity-Trust.js b/database/migrations/20200902014751-CreateTableEntity-Trust.js index 78b56ffe..f46efc81 100644 --- a/database/migrations/20200902014751-CreateTableEntity-Trust.js +++ b/database/migrations/20200902014751-CreateTableEntity-Trust.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200902014758-CreateTableEntity-Trust-Log.js b/database/migrations/20200902014758-CreateTableEntity-Trust-Log.js index 1782e274..3d0d6eeb 100644 --- a/database/migrations/20200902014758-CreateTableEntity-Trust-Log.js +++ b/database/migrations/20200902014758-CreateTableEntity-Trust-Log.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200902014805-CreateTableTransfer-Audit.js b/database/migrations/20200902014805-CreateTableTransfer-Audit.js index 2c0ada54..ae06d7e5 100644 --- a/database/migrations/20200902014805-CreateTableTransfer-Audit.js +++ b/database/migrations/20200902014805-CreateTableTransfer-Audit.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200916235257-CreateTableApi-Key.js b/database/migrations/20200916235257-CreateTableApi-Key.js index a567cbb1..9c3a7c85 100644 --- a/database/migrations/20200916235257-CreateTableApi-Key.js +++ b/database/migrations/20200916235257-CreateTableApi-Key.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20200917183542-CreateTableWallet.js b/database/migrations/20200917183542-CreateTableWallet.js index 0003f500..8b6a897c 100644 --- a/database/migrations/20200917183542-CreateTableWallet.js +++ b/database/migrations/20200917183542-CreateTableWallet.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20201127234338-AllowNullPasswordWallet.js b/database/migrations/20201127234338-AllowNullPasswordWallet.js index a01a7e4f..7031afa1 100644 --- a/database/migrations/20201127234338-AllowNullPasswordWallet.js +++ b/database/migrations/20201127234338-AllowNullPasswordWallet.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20201209064928-RenameTableEntityTrust.js b/database/migrations/20201209064928-RenameTableEntityTrust.js index 05ade637..91343042 100644 --- a/database/migrations/20201209064928-RenameTableEntityTrust.js +++ b/database/migrations/20201209064928-RenameTableEntityTrust.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20201209065300-RenameTableEntityTrustLog.js b/database/migrations/20201209065300-RenameTableEntityTrustLog.js index 57e3e5e8..d7935875 100644 --- a/database/migrations/20201209065300-RenameTableEntityTrustLog.js +++ b/database/migrations/20201209065300-RenameTableEntityTrustLog.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20210211020241-AddDefaultIdTransactionTable.js b/database/migrations/20210211020241-AddDefaultIdTransactionTable.js index 2ba0c1d4..463063dd 100644 --- a/database/migrations/20210211020241-AddDefaultIdTransactionTable.js +++ b/database/migrations/20210211020241-AddDefaultIdTransactionTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020241-AddDefaultIdTransactionTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020241-AddDefaultIdTransactionTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020241-AddDefaultIdTransactionTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020241-AddDefaultIdTransactionTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020257-AddDefaultIdTransferTable.js b/database/migrations/20210211020257-AddDefaultIdTransferTable.js index 92f08f47..7306a89e 100644 --- a/database/migrations/20210211020257-AddDefaultIdTransferTable.js +++ b/database/migrations/20210211020257-AddDefaultIdTransferTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020257-AddDefaultIdTransferTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020257-AddDefaultIdTransferTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020257-AddDefaultIdTransferTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020257-AddDefaultIdTransferTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020301-AddDefaultIdTokenTable.js b/database/migrations/20210211020301-AddDefaultIdTokenTable.js index e8b321ae..179a0418 100644 --- a/database/migrations/20210211020301-AddDefaultIdTokenTable.js +++ b/database/migrations/20210211020301-AddDefaultIdTokenTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020301-AddDefaultIdTokenTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020301-AddDefaultIdTokenTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020301-AddDefaultIdTokenTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020301-AddDefaultIdTokenTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020304-AddDefaultIdWalletTable.js b/database/migrations/20210211020304-AddDefaultIdWalletTable.js index 5013f3ab..2cb4db92 100644 --- a/database/migrations/20210211020304-AddDefaultIdWalletTable.js +++ b/database/migrations/20210211020304-AddDefaultIdWalletTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020304-AddDefaultIdWalletTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020304-AddDefaultIdWalletTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020304-AddDefaultIdWalletTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020304-AddDefaultIdWalletTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020331-AddDefaultIdApiKeyTable.js b/database/migrations/20210211020331-AddDefaultIdApiKeyTable.js index e1d06760..ec30345d 100644 --- a/database/migrations/20210211020331-AddDefaultIdApiKeyTable.js +++ b/database/migrations/20210211020331-AddDefaultIdApiKeyTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020331-AddDefaultIdApiKeyTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020331-AddDefaultIdApiKeyTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020331-AddDefaultIdApiKeyTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020331-AddDefaultIdApiKeyTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020340-AddDefaultIdTransferAuditTable.js b/database/migrations/20210211020340-AddDefaultIdTransferAuditTable.js index 6c5759ef..3588ffc4 100644 --- a/database/migrations/20210211020340-AddDefaultIdTransferAuditTable.js +++ b/database/migrations/20210211020340-AddDefaultIdTransferAuditTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020340-AddDefaultIdTransferAuditTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020340-AddDefaultIdTransferAuditTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020340-AddDefaultIdTransferAuditTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020340-AddDefaultIdTransferAuditTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020347-AddDefaultIdWalletEventTable.js b/database/migrations/20210211020347-AddDefaultIdWalletEventTable.js index ac9db7e3..3267ee3d 100644 --- a/database/migrations/20210211020347-AddDefaultIdWalletEventTable.js +++ b/database/migrations/20210211020347-AddDefaultIdWalletEventTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020347-AddDefaultIdWalletEventTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020347-AddDefaultIdWalletEventTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020347-AddDefaultIdWalletEventTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020347-AddDefaultIdWalletEventTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020352-AddDefaultIdWalletTrustTable.js b/database/migrations/20210211020352-AddDefaultIdWalletTrustTable.js index 1983f4f8..f6a06654 100644 --- a/database/migrations/20210211020352-AddDefaultIdWalletTrustTable.js +++ b/database/migrations/20210211020352-AddDefaultIdWalletTrustTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020352-AddDefaultIdWalletTrustTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020352-AddDefaultIdWalletTrustTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020352-AddDefaultIdWalletTrustTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020352-AddDefaultIdWalletTrustTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210211020356-AddDefaultIdWalletTrustLogTable.js b/database/migrations/20210211020356-AddDefaultIdWalletTrustLogTable.js index 59260c98..ccf0d92c 100644 --- a/database/migrations/20210211020356-AddDefaultIdWalletTrustLogTable.js +++ b/database/migrations/20210211020356-AddDefaultIdWalletTrustLogTable.js @@ -1,11 +1,12 @@ -'use strict'; -var dbm; -var type; -var seed; -var fs = require('fs'); -var path = require('path'); -var Promise; + +let dbm; +let type; +let seed; +const fs = require('fs'); +const path = require('path'); + +let Promise; /** * We receive the dbmigrate dependency from dbmigrate initially. @@ -19,11 +20,11 @@ exports.setup = function(options, seedLink) { }; exports.up = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020356-AddDefaultIdWalletTrustLogTable-up.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020356-AddDefaultIdWalletTrustLogTable-up.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); @@ -34,11 +35,11 @@ exports.up = function(db) { }; exports.down = function(db) { - var filePath = path.join(__dirname, 'sqls', '20210211020356-AddDefaultIdWalletTrustLogTable-down.sql'); + const filePath = path.join(__dirname, 'sqls', '20210211020356-AddDefaultIdWalletTrustLogTable-down.sql'); return new Promise( function( resolve, reject ) { fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (err) return reject(err); - console.log('received data: ' + data); + console.log(`received data: ${ data}`); resolve(data); }); diff --git a/database/migrations/20210226234313-AddUniqueConstraintWalletName.js b/database/migrations/20210226234313-AddUniqueConstraintWalletName.js index b137b191..7aff616c 100644 --- a/database/migrations/20210226234313-AddUniqueConstraintWalletName.js +++ b/database/migrations/20210226234313-AddUniqueConstraintWalletName.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/database/migrations/20210304014730-AddUniqueConstraintCaptureId.js b/database/migrations/20210304014730-AddUniqueConstraintCaptureId.js index 302cf643..f3e0408b 100644 --- a/database/migrations/20210304014730-AddUniqueConstraintCaptureId.js +++ b/database/migrations/20210304014730-AddUniqueConstraintCaptureId.js @@ -1,8 +1,8 @@ -'use strict'; -var dbm; -var type; -var seed; + +let dbm; +let type; +let seed; /** * We receive the dbmigrate dependency from dbmigrate initially. diff --git a/scripts/create/clean-up-duplicates.js b/scripts/create/clean-up-duplicates.js index 325fb124..3c161ebd 100644 --- a/scripts/create/clean-up-duplicates.js +++ b/scripts/create/clean-up-duplicates.js @@ -34,7 +34,7 @@ function getRandomArbitrary(min, max) { const uuid = row[0] console.log(uuid) - const captures = await trx('trees').select(['id']).where({ uuid: uuid, active: true}) + const captures = await trx('trees').select(['id']).where({ uuid, active: true}) console.log(captures.length) captures.shift() // skip the first one @@ -48,7 +48,7 @@ function getRandomArbitrary(min, max) { await trx.commit(); - //await trx.rollback(); + // await trx.rollback(); knex.destroy() diff --git a/scripts/create/create-tokens-csv.js b/scripts/create/create-tokens-csv.js index 333a3adf..253cb061 100644 --- a/scripts/create/create-tokens-csv.js +++ b/scripts/create/create-tokens-csv.js @@ -51,7 +51,7 @@ function getRandomArbitrary(min, max) { continue } - //console.log('capture ' + capture.uuid); + // console.log('capture ' + capture.uuid); tokenData = { capture_id: capture.uuid, wallet_id: wallet.id @@ -69,7 +69,7 @@ function getRandomArbitrary(min, max) { await trx.rollback(); } else { console.log('Committing changes!') - //await trx.commit(); + // await trx.commit(); } knex.destroy() diff --git a/scripts/create/create-tokens-fcc.js b/scripts/create/create-tokens-fcc.js index e63b0e40..abef05d4 100644 --- a/scripts/create/create-tokens-fcc.js +++ b/scripts/create/create-tokens-fcc.js @@ -33,7 +33,7 @@ function getRandomArbitrary(min, max) { for(capture of rows){ - //console.log('capture ' + capture.uuid); + // console.log('capture ' + capture.uuid); tokenData = { capture_id: capture.uuid, wallet_id: wallet.id @@ -48,7 +48,7 @@ function getRandomArbitrary(min, max) { } await trx.commit(); - //await trx.rollback(); + // await trx.rollback(); knex.destroy() diff --git a/scripts/create/create-tokens-kijani.js b/scripts/create/create-tokens-kijani.js index 933b7d98..cf369726 100644 --- a/scripts/create/create-tokens-kijani.js +++ b/scripts/create/create-tokens-kijani.js @@ -25,7 +25,7 @@ function getRandomArbitrary(min, max) { for(capture of rows){ - //console.log('capture ' + capture.uuid); + // console.log('capture ' + capture.uuid); tokenData = { capture_id: capture.uuid, wallet_id: wallet.id diff --git a/scripts/create/create-wallet.js b/scripts/create/create-wallet.js index 8ed1a8ec..772fa7d1 100644 --- a/scripts/create/create-wallet.js +++ b/scripts/create/create-wallet.js @@ -30,13 +30,13 @@ function getRandomArbitrary(min, max) { }); const sha512 = function(password, salt){ - var hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ + const hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ hash.update(password); - var value = hash.digest('hex'); + const value = hash.digest('hex'); return value; }; - const salt = Crypto.randomBytes(32).toString('base64') //create a secure salt + const salt = Crypto.randomBytes(32).toString('base64') // create a secure salt const passwordHash = sha512(password, salt) const apiKey = generator.generate({ @@ -64,7 +64,7 @@ function getRandomArbitrary(min, max) { const result = await trx('wallet.wallet').insert({ name: username, password: passwordHash, - salt: salt + salt }).returning('*') const wallet = result[0] console.log(wallet) @@ -73,9 +73,9 @@ function getRandomArbitrary(min, max) { knex.destroy() - console.log('wallet ' + username); - console.log('password ' + password); - console.log('api key ' + apiKey); + console.log(`wallet ${ username}`); + console.log(`password ${ password}`); + console.log(`api key ${ apiKey}`); } catch (error) { diff --git a/scripts/demo/create-demo-wallet.js b/scripts/demo/create-demo-wallet.js index e849532c..8f82133e 100644 --- a/scripts/demo/create-demo-wallet.js +++ b/scripts/demo/create-demo-wallet.js @@ -18,9 +18,9 @@ function getRandomArbitrary(min, max) { const Crypto = require('crypto'); const sha512 = function(password, salt){ - var hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ + const hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ hash.update(password); - var value = hash.digest('hex'); + const value = hash.digest('hex'); return value; }; @@ -50,7 +50,7 @@ function getRandomArbitrary(min, max) { const result = await trx('wallet.wallet').insert({ name: username, password: passwordHash, - salt: salt + salt }).returning('*') const wallet = result[0] console.log(wallet) @@ -80,7 +80,7 @@ function getRandomArbitrary(min, max) { ] // insert fake tree captures - let trees = [] + const trees = [] for(i=0; i<5000; i++){ const captureData = { time_created: new Date(), @@ -114,9 +114,9 @@ function getRandomArbitrary(min, max) { knex.destroy() - console.log('wallet ' + username); - console.log('password ' + password); - console.log('apiKey ' + apiKey); + console.log(`wallet ${ username}`); + console.log(`password ${ password}`); + console.log(`apiKey ${ apiKey}`); } catch (error) { diff --git a/scripts/user/sha.js b/scripts/user/sha.js index 632c4fb4..83ea7a70 100644 --- a/scripts/user/sha.js +++ b/scripts/user/sha.js @@ -1,15 +1,16 @@ const Crypto = require('crypto'); + const sha512 = function(password, salt){ - var hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ + const hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ hash.update(password); - var value = hash.digest('hex'); + const value = hash.digest('hex'); return value; }; const key = 'MyGreat38473'; const salt = 'j5qI1qb2rsgVBJvjiXx1isnR4bQW6Yd3'; const hash = sha512(key, salt); -console.log("key: " + key); -console.log("salt: " + salt); -console.log("hash: " + hash); +console.log(`key: ${ key}`); +console.log(`salt: ${ salt}`); +console.log(`hash: ${ hash}`); diff --git a/server/app.js b/server/app.js index 47c355b8..ec9263b9 100644 --- a/server/app.js +++ b/server/app.js @@ -4,6 +4,7 @@ const bodyParser = require('body-parser'); const asyncHandler = require('express-async-handler'); const { check, validationResult } = require('express-validator'); const { body } = require('express-validator'); +const log = require("loglevel"); const HttpError = require("./utils/HttpError"); const authRouter = require('./routes/authRouter.js') const trustRouter = require('./routes/trustRouter.js') @@ -11,7 +12,6 @@ const tokenRouter = require('./routes/tokenRouter.js') const transferRouter = require("./routes/transferRouter"); const walletRouter = require("./routes/walletRouter"); const {errorHandler} = require("./routes/utils"); -const log = require("loglevel"); const helper = require("./routes/utils"); @@ -36,7 +36,7 @@ app.use(helper.handlerWrapper(async (req, _res, next) => { app.use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded app.use(bodyParser.json()); // parse application/json -//routers +// routers app.use('/auth', authRouter); app.use('/tokens', tokenRouter); app.use('/trust_relationships', trustRouter); @@ -53,8 +53,8 @@ app.get('/wallet/:wallet_id/event', asyncHandler(async (req, res, next) => { app.post('/wallet/:wallet_id/trust/request', asyncHandler(async (req, res, next) => { - const type = req.body.type; - //const requestor_wallet_id = req.body.wallet_id; this is in the bearer token + const {type} = req.body; + // const requestor_wallet_id = req.body.wallet_id; this is in the bearer token const requested_wallet_id = req.params.wallet_id; @@ -62,8 +62,8 @@ app.post('/wallet/:wallet_id/trust/request', asyncHandler(async (req, res, next) app.post('/wallet/:wallet_id/trust/approve', asyncHandler(async (req, res, next) => { - const type = req.body.type; - //const wallet_id = req.body.wallet_id; // in the bearer token + const {type} = req.body; + // const wallet_id = req.body.wallet_id; // in the bearer token const approved_wallet_id = req.params.wallet_id; })); @@ -71,7 +71,8 @@ app.post('/wallet/:wallet_id/trust/approve', asyncHandler(async (req, res, next) // Global error handler app.use(errorHandler); -const version = require('../package.json').version +const {version} = require('../package.json') + app.get('*',function (req, res) { res.status(200).send(version) }); diff --git a/server/app.spec.js b/server/app.spec.js index ca987544..e06248aa 100644 --- a/server/app.spec.js +++ b/server/app.spec.js @@ -1,6 +1,6 @@ -const server = require("../server/app"); const request = require('supertest'); const { expect } = require('chai'); +const server = require("./app"); describe("", () => { diff --git a/server/database/knex.js b/server/database/knex.js index 956d6da7..b75167a3 100644 --- a/server/database/knex.js +++ b/server/database/knex.js @@ -1,17 +1,18 @@ require('dotenv').config() const expect = require('expect-runtime'); const connection = require('../../config/config').connectionString; + expect(connection).to.match(/^postgresql:\//); const log = require("loglevel"); -let knexConfig = { +const knexConfig = { client: 'pg', - debug: process.env.NODE_LOG_LEVEL === "debug"? true:false, + debug: process.env.NODE_LOG_LEVEL === "debug", connection, pool: { min:0, max: 100, - afterCreate: function (conn, done) { + afterCreate (conn, done) { conn.query('SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE;', function (err) { if (err) { log.error(err) diff --git a/server/models/Session.js b/server/models/Session.js index f8c9ebb2..5f77bc2e 100644 --- a/server/models/Session.js +++ b/server/models/Session.js @@ -11,9 +11,9 @@ class Session{ getDB(){ if(this.thx){ return this.thx; - }else{ - return knex; } + return knex; + } async beginTransaction(){ diff --git a/server/models/Session.spec.js b/server/models/Session.spec.js index fb082dfc..35479c10 100644 --- a/server/models/Session.spec.js +++ b/server/models/Session.spec.js @@ -1,8 +1,9 @@ -const Session = require("./Session"); const jestExpect = require("expect"); const sinon = require("sinon"); const chai = require("chai"); const sinonChai = require("sinon-chai"); +const Session = require("./Session"); + chai.use(sinonChai); const {expect} = chai; diff --git a/server/models/Token.js b/server/models/Token.js index 3cdd5cb2..705e7f1d 100644 --- a/server/models/Token.js +++ b/server/models/Token.js @@ -1,10 +1,10 @@ const log = require("loglevel"); -const TokenRepository = require("../repositories/TokenRepository"); -const TransactionRepository = require("../repositories/TransactionRepository"); -const HttpError = require("../utils/HttpError"); const { validate: uuidValidate } = require('uuid'); const Joi = require("joi"); const expect = require("expect-runtime"); +const TokenRepository = require("../repositories/TokenRepository"); +const TransactionRepository = require("../repositories/TransactionRepository"); +const HttpError = require("../utils/HttpError"); class Token{ @@ -31,7 +31,7 @@ class Token{ }else{ this._JSON = await this.tokenRepository.getById(this._id); } - //deal with tree links + // deal with tree links const result = { ...this._JSON, links: { @@ -100,18 +100,18 @@ class Token{ const json = await this.toJSON(); if(json.wallet_id === wallet.getId()){ return true; - }else{ - return false; } + return false; + } async beAbleToTransfer(){ const json = await this.toJSON(); if(json.transfer_pending === false){ return true; - }else{ - return false; } + return false; + } async getTransactions(limit, offset = 0){ diff --git a/server/models/Token.spec.js b/server/models/Token.spec.js index 6c119043..fedbd5a1 100644 --- a/server/models/Token.spec.js +++ b/server/models/Token.spec.js @@ -1,19 +1,20 @@ -const Token = require("./Token"); const jestExpect = require("expect"); const sinon = require("sinon"); -const TokenRepository = require("../repositories/TokenRepository"); -const HttpError = require("../utils/HttpError"); 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"); + chai.use(sinonChai); const {expect} = chai; const TransactionRepository = require("../repositories/TransactionRepository"); const Wallet = require("./Wallet"); const Session = require("./Session"); -const uuid = require('uuid'); describe("Token", () => { - let session = new Session(); + const session = new Session(); const tokenId = uuid.v4() const transferId = uuid.v4() diff --git a/server/models/TrustRelationship.js b/server/models/TrustRelationship.js index f2ab78f2..4f0b462d 100644 --- a/server/models/TrustRelationship.js +++ b/server/models/TrustRelationship.js @@ -1,6 +1,6 @@ const HttpError = require("../utils/HttpError"); -//NOTE: currently, don't have model for trust, here just defined some fields -//for this model +// NOTE: currently, don't have model for trust, here just defined some fields +// for this model const TrustRelationship = {} TrustRelationship.ENTITY_TRUST_TYPE = { diff --git a/server/models/TrustRelationship.spec.js b/server/models/TrustRelationship.spec.js index f4297f3a..2957e2fe 100644 --- a/server/models/TrustRelationship.spec.js +++ b/server/models/TrustRelationship.spec.js @@ -2,6 +2,7 @@ const jestExpect = require("expect"); const sinon = require("sinon"); const chai = require("chai"); const sinonChai = require("sinon-chai"); + chai.use(sinonChai); const {expect} = chai; const TrustRelationship = require("./TrustRelationship"); diff --git a/server/models/Wallet.js b/server/models/Wallet.js index d213df0e..cac716dd 100644 --- a/server/models/Wallet.js +++ b/server/models/Wallet.js @@ -1,15 +1,15 @@ +const Crypto = require('crypto'); +const log = require("loglevel"); +const { validate: uuidValidate } = require('uuid'); +const expect = require("expect-runtime"); // TODO: We should use Joi for validation +const Joi = require("joi"); const WalletRepository = require("../repositories/WalletRepository"); const TrustRepository = require("../repositories/TrustRepository"); -const TrustRelationship = require("../models/TrustRelationship"); +const TrustRelationship = require("./TrustRelationship"); const TransferRepository = require("../repositories/TransferRepository"); const HttpError = require("../utils/HttpError"); -const Crypto = require('crypto'); -const log = require("loglevel"); const Transfer = require("./Transfer"); const Token = require("./Token"); -const { validate: uuidValidate } = require('uuid'); -const expect = require("expect-runtime"); //TODO: We should use Joi for validation -const Joi = require("joi"); class Wallet{ @@ -42,7 +42,7 @@ class Wallet{ throw new HttpError(400, 'No password supplied'); } - let walletObject = await this.toJSON(); + const walletObject = await this.toJSON(); const hash = Wallet.sha512(password, walletObject.salt); if (hash !== walletObject.password) { @@ -58,13 +58,13 @@ class Wallet{ throw new HttpError(400, 'No wallet supplied'); } - //check name + // check name try{ await this.walletRepository.getByName(wallet); throw new HttpError(403, `The wallet '${wallet}' has been existed`); }catch(e){ if(e instanceof HttpError && e.code === 404){ - //fine + // fine }else{ throw e; } @@ -173,10 +173,10 @@ class Wallet{ async toJSON(){ if(this._JSON){ return this._JSON; - }else{ + } this._JSON = await this.walletRepository.getById(this._id); return this._JSON; - } + } /* @@ -196,8 +196,8 @@ class Wallet{ /* * Translate the requester/ee to actor/target */ - let actorWallet = requesterWallet; //case of: manage/send - let targetWallet = requesteeWallet; //case of: mange/send + const actorWallet = requesterWallet; // case of: manage/send + const targetWallet = requesteeWallet; // case of: mange/send // if( // requestType === TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive || // requestType === TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield){ @@ -207,16 +207,16 @@ class Wallet{ - //check if the orginator can control the actor + // check if the orginator can control the actor const hasControl = await this.hasControlOver(requesterWallet); if(!hasControl){ throw new HttpError(403, "Have no permission to deal with this actor"); } - //check if the target wallet can accept the request + // check if the target wallet can accept the request await requesteeWallet.checkTrustRequestSentToMe(requestType, this.id); - //create this request + // create this request const trustRelationship = { type: TrustRelationship.getTrustTypeByRequestType(requestType), request_type: requestType, @@ -230,7 +230,7 @@ class Wallet{ return result; } - //check if I (current wallet) can add a new trust like this + // check if I (current wallet) can add a new trust like this async checkDuplicateRequest(trustRelationship){ const trustRelationships = await this.getTrustRelationships(); if( @@ -259,9 +259,9 @@ class Wallet{ ) ){ return true; - }else{ - return false; } + return false; + }) ){ log.debug("Has duplicated trust"); @@ -281,7 +281,7 @@ class Wallet{ * sourceWalletId: the wallet id related to the trust relationship with me, */ async checkTrustRequestSentToMe(requestType, sourceWalletId){ - //pass + // pass } /* @@ -292,9 +292,9 @@ class Wallet{ const trustRelationship = trustRelationships.reduce((a,c) => { if(c.id === trustRelationshipId){ return c; - }else{ - return a; } + return a; + }, undefined); if(!trustRelationship){ throw new HttpError(403, "Have no permission to accept this relationship"); @@ -307,9 +307,9 @@ class Wallet{ async checkManageCircle(trustRelationship){ const trustRelationshipTrusted = await this.getTrustRelationshipsTrusted(); - //just manage type of trust relationship + // just manage type of trust relationship if(trustRelationship.type === TrustRelationship.ENTITY_TRUST_TYPE.manage){ - //if is mange request + // if is mange request if(trustRelationship.request_type === TrustRelationship.ENTITY_TRUST_TYPE.manage){ if(trustRelationshipTrusted.some(e => { if( @@ -326,9 +326,9 @@ class Wallet{ ) ){ return true; - }else{ - return false; } + return false; + })){ throw new HttpError(403, "Operation forbidden, because this would lead to a management circle"); } @@ -348,9 +348,9 @@ class Wallet{ ) ){ return true; - }else{ - return false; } + return false; + })){ throw new HttpError(403, "Operation forbidden, because this would lead to a management circle"); } @@ -366,9 +366,9 @@ class Wallet{ const trustRelationship = trustRelationships.reduce((a,c) => { if(c.id === trustRelationshipId){ return c; - }else{ - return a; } + return a; + }, undefined); if(!trustRelationship){ throw new HttpError(403, "Have no permission to decline this relationship"); @@ -400,7 +400,7 @@ class Wallet{ expect(senderWallet).instanceOf(Wallet); expect(receiveWallet).instanceOf(Wallet); const trustRelationships = await this.getTrustRelationshipsTrusted(); - //check if the trust exist + // check if the trust exist if( trustRelationships.some(trustRelationship => { /* Seems unnecessary @@ -417,9 +417,9 @@ class Wallet{ trustRelationship.request_type === TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send ){ return true; - }else{ - return false; } + return false; + }) || trustRelationships.some(trustRelationship => { @@ -437,16 +437,16 @@ class Wallet{ trustRelationship.request_type === TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive ){ return true; - }else{ - return false; } + return false; + }) ){ log.debug("check trust passed"); return true; - }else{ - return false; } + return false; + } /* @@ -454,7 +454,7 @@ class Wallet{ */ async transfer(sender, receiver, tokens){ // await this.checkDeduct(sender, receiver); - //check tokens belong to sender + // check tokens belong to sender for(const token of tokens){ if(!await token.belongsTo(sender)){ const uuid = await token.getId(); @@ -470,13 +470,13 @@ class Wallet{ const hasTrust = await this.hasTrust(TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, sender, receiver); const hasControlOverSender = await this.hasControlOver(sender); const hasControlOverReceiver = await this.hasControlOver(receiver); - //If has the trust, and is not deduct request (now, if wallet request some token from another wallet, can not pass the transfer directly) + // If has the trust, and is not deduct request (now, if wallet request some token from another wallet, can not pass the transfer directly) if( (hasControlOverSender && hasControlOverReceiver) || (!isDeduct && hasTrust) ){ const tokensId = []; - for(let token of tokens){ + for(const token of tokens){ tokensId.push(token.getId()); } const transfer = await this.transferRepository.create({ @@ -492,11 +492,11 @@ class Wallet{ await this.tokenService.completeTransfer(tokens, transfer); return transfer; - }else{ + } if(hasControlOverSender){ log.debug("OK, no permission, source under control, now pending it"); const tokensId = []; - for(let token of tokens){ + for(const token of tokens){ tokensId.push(token.getId()); } const transfer = await this.transferRepository.create({ @@ -510,10 +510,10 @@ class Wallet{ }); await this.tokenService.pendingTransfer(tokens, transfer); return transfer; - }else if(hasControlOverReceiver){ + }if(hasControlOverReceiver){ log.debug("OK, no permission, receiver under control, now request it"); const tokensId = []; - for(let token of tokens){ + for(const token of tokens){ tokensId.push(token.getId()); } const transfer = await this.transferRepository.create({ @@ -527,22 +527,22 @@ class Wallet{ }); await this.tokenService.pendingTransfer(tokens, transfer); return transfer; - }else{ - //TODO - expect.fail(); } - } + // TODO + expect.fail(); + + } async transferBundle(sender, receiver, bundleSize){ - //check has enough tokens to sender + // check has enough tokens to sender const tokenCount = await this.tokenService.countTokenByWallet(sender); if(tokenCount < bundleSize){ throw new HttpError(403, `Do not have enough tokens to send`); } const isDeduct = await this.isDeduct(sender,receiver); - //If has the trust, and is not deduct request (now, if wallet request some token from another wallet, can not pass the transfer directly) + // If has the trust, and is not deduct request (now, if wallet request some token from another wallet, can not pass the transfer directly) const hasTrust = await this.hasTrust(TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, sender, receiver); const hasControlOverSender = await this.hasControlOver(sender); const hasControlOverReceiver = await this.hasControlOver(receiver); @@ -557,7 +557,7 @@ class Wallet{ state: Transfer.STATE.completed, parameters: { bundle: { - bundleSize: bundleSize, + bundleSize, } } }); @@ -565,7 +565,7 @@ class Wallet{ const tokens = await this.tokenService.getTokensByBundle(sender, bundleSize) await this.tokenService.completeTransfer(tokens, transfer); return transfer; - }else{ + } if(hasControlOverSender){ log.debug("OK, no permission, source under control, now pending it"); const transfer = await this.transferRepository.create({ @@ -575,12 +575,12 @@ class Wallet{ state: Transfer.STATE.pending, parameters: { bundle: { - bundleSize: bundleSize, + bundleSize, } } }); return transfer; - }else if(hasControlOverReceiver){ + }if(hasControlOverReceiver){ log.debug("OK, no permission, receiver under control, now request it"); const transfer = await this.transferRepository.create({ originator_wallet_id: this._id, @@ -589,28 +589,28 @@ class Wallet{ state: Transfer.STATE.requested, parameters: { bundle: { - bundleSize: bundleSize, + bundleSize, } } }); return transfer; - }else{ - //TODO - expect.fail(); } - } + // TODO + expect.fail(); + + } /* * I have control over given wallet */ async hasControlOver(wallet){ - //if the given wallet is me, then pass + // if the given wallet is me, then pass if(wallet.getId() === this._id){ log.debug("The same wallet, control"); return true; - }else{ - //check sub wallet + } + // check sub wallet const result = await this.trustRepository.getByFilter({ or: [ { @@ -639,10 +639,10 @@ class Wallet{ }); if(result.length > 0){ return true; - }else{ - return false; } - } + return false; + + } /* @@ -671,9 +671,9 @@ class Wallet{ transfer.state = Transfer.STATE.completed; const transferJson = await this.transferRepository.update(transfer); - //deal with tokens + // deal with tokens if( - //TODO optimize + // TODO optimize transfer.parameters && transfer.parameters.bundle && transfer.parameters.bundle.bundleSize){ @@ -720,7 +720,7 @@ class Wallet{ transfer.state = Transfer.STATE.cancelled; const transferJson = await this.transferRepository.update(transfer); - //deal with tokens + // deal with tokens const tokens = await this.tokenService.getTokensByPendingTransferId(transfer.id); await this.tokenService.cancelTransfer(tokens, transfer); return transferJson; @@ -747,7 +747,7 @@ class Wallet{ transfer.state = Transfer.STATE.cancelled; const transferJson = await this.transferRepository.update(transfer); - //deal with tokens + // deal with tokens const tokens = await this.tokenService.getTokensByPendingTransferId(transfer.id); await this.tokenService.cancelTransfer(tokens, transfer); return transferJson; @@ -757,7 +757,7 @@ class Wallet{ * Fulfill a requested transfer, if I has the privilege to do so */ async fulfillTransfer(transferId){ - //TODO check privilege + // TODO check privilege const transfer = await this.transferRepository.getById(transferId); const sender = await this.walletService.getById(transfer.source_wallet_id); @@ -771,9 +771,9 @@ class Wallet{ transfer.state = Transfer.STATE.completed; const transferJson = await this.transferRepository.update(transfer); - //deal with tokens + // deal with tokens if( - //TODO optimize + // TODO optimize transfer.parameters && transfer.parameters.bundle && transfer.parameters.bundle.bundleSize){ @@ -795,7 +795,7 @@ class Wallet{ * Specify tokens */ async fulfillTransferWithTokens(transferId, tokens){ - //TODO check privilege + // TODO check privilege const transfer = await this.transferRepository.getById(transferId); const sender = await this.walletService.getById(transfer.source_wallet_id); @@ -809,16 +809,16 @@ class Wallet{ transfer.state = Transfer.STATE.completed; const transferJson = await this.transferRepository.update(transfer); - //deal with tokens + // deal with tokens if( - //TODO optimize + // TODO optimize transfer.parameters && transfer.parameters.bundle && transfer.parameters.bundle.bundleSize){ log.debug("transfer bundle of tokens"); const {source_wallet_id} = transfer; const senderWallet = new Wallet(source_wallet_id, this._session); - //check it + // check it if(tokens.length > transfer.parameters.bundle.bundleSize){ throw new HttpError(403, `Too many tokens to transfer, please provider ${transfer.parameters.bundle.bundleSize} tokens for this transfer`, true); } @@ -833,7 +833,7 @@ class Wallet{ } } - //transfer + // transfer await this.tokenService.completeTransfer(tokens, transfer); }else{ throw new HttpError(403, "No need to specify tokens", true); @@ -879,9 +879,9 @@ class Wallet{ const transfer = transfers.reduce((a,c) => { if(c.id === id){ return c; - }else{ - return a; } + return a; + }, undefined); if(!transfer){ throw new HttpError(404, "Can not find this transfer or it is related to this wallet"); @@ -910,18 +910,18 @@ class Wallet{ const result = await this.hasControlOver(sender); if(result){ return false; - }else{ - return true; } + return true; + } /* * Get all wallet managed by me */ async getSubWallets(){ - let trustRelationships = await this.getTrustRelationships(); + const trustRelationships = await this.getTrustRelationships(); const subWallets = []; - for(let e of trustRelationships){ + for(const e of trustRelationships){ if( e.actor_wallet_id === this._id && e.request_type === TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage && diff --git a/server/models/Wallet.spec.js b/server/models/Wallet.spec.js index 476819f4..7b024f28 100644 --- a/server/models/Wallet.spec.js +++ b/server/models/Wallet.spec.js @@ -1,8 +1,10 @@ -const Wallet = require("./Wallet"); const jestExpect = require("expect"); const sinon = require("sinon"); const chai = require("chai"); const sinonChai = require("sinon-chai"); +const uuid = require('uuid'); +const Wallet = require("./Wallet"); + chai.use(sinonChai); const {expect} = chai; const WalletRepository = require("../repositories/WalletRepository"); @@ -10,16 +12,15 @@ const TrustRepository = require("../repositories/TrustRepository"); const WalletService = require("../services/WalletService"); const TransferRepository = require("../repositories/TransferRepository"); const HttpError = require("../utils/HttpError"); -const TrustRelationship = require("../models/TrustRelationship"); +const TrustRelationship = require("./TrustRelationship"); const Transfer = require("./Transfer"); const Token = require("./Token"); const TokenService = require("../services/TokenService"); const Session = require("./Session"); -const uuid = require('uuid'); describe("Wallet", () => { let walletService; - let session = new Session(); + const session = new Session(); const walletObject = { id: uuid.v4(), @@ -239,7 +240,7 @@ describe("Wallet", () => { }; it("has no trust", async () => { - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([]);//no relationship + const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([]);// no relationship const result = await wallet.hasTrust( TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, wallet, @@ -329,7 +330,7 @@ describe("Wallet", () => { fn2.restore(); }); - //This shouldn't be able to pass anymore, because this is a deduct case, this case do not support yet, check the test for "deduct" + // This shouldn't be able to pass anymore, because this is a deduct case, this case do not support yet, check the test for "deduct" it.skip("don't have trust, receiver under control, should created a transfer request record", async () => { const fn0 = sinon.stub(Token.prototype, "belongsTo").resolves(true); const fn1 = sinon.stub(TransferRepository.prototype, "create").resolves({ @@ -353,7 +354,7 @@ describe("Wallet", () => { fn2.restore(); }); - //This shouldn't be able to pass anymore, because this is a deduct case, this case do not support yet, check the test for "deduct" + // This shouldn't be able to pass anymore, because this is a deduct case, this case do not support yet, check the test for "deduct" it.skip("have trust, should finish successfully", async () => { const fn0 = sinon.stub(Token.prototype, "belongsTo").resolves(true); const fn1 = sinon.stub(wallet, "checkTrust"); @@ -1054,7 +1055,7 @@ describe("Wallet", () => { describe("Deduct", () => { - const wallet = new Wallet({id: uuid.v4()}) //TODO: should create class MockWallet that does not use repository + 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({ diff --git a/server/repositories/ApiKeyRepository.js b/server/repositories/ApiKeyRepository.js index 61146f3d..5174123a 100644 --- a/server/repositories/ApiKeyRepository.js +++ b/server/repositories/ApiKeyRepository.js @@ -1,5 +1,5 @@ -const HttpError = require("../utils/HttpError"); const expect = require("expect-runtime"); +const HttpError = require("../utils/HttpError"); const Session = require("../models/Session"); diff --git a/server/repositories/ApiKeyRepository.spec.js b/server/repositories/ApiKeyRepository.spec.js index 41711e7f..7a3a3014 100644 --- a/server/repositories/ApiKeyRepository.spec.js +++ b/server/repositories/ApiKeyRepository.spec.js @@ -1,6 +1,7 @@ const {expect} = require("chai"); -const knex = require("../database/knex"); const mockKnex = require("mock-knex"); +const knex = require("../database/knex"); + const tracker = mockKnex.getTracker(); const ApiKeyRepository = require("./ApiKeyRepository"); const Session = require("../models/Session"); diff --git a/server/repositories/BaseRepository.js b/server/repositories/BaseRepository.js index a873fa31..6bef117c 100644 --- a/server/repositories/BaseRepository.js +++ b/server/repositories/BaseRepository.js @@ -1,7 +1,7 @@ -const Session = require("../models/Session"); const expect = require("expect-runtime"); -const HttpError = require("../utils/HttpError"); const log = require("loglevel"); +const Session = require("../models/Session"); +const HttpError = require("../utils/HttpError"); class BaseRepository{ @@ -29,22 +29,22 @@ class BaseRepository{ const offset = options && options.offset ? options.offset : 0 const whereBuilder = function(object, builder){ let result = builder; - if(object['and']){ + if(object.and){ expect(Object.keys(object)).lengthOf(1); - expect(object['and']).a(expect.any(Array)); - for(let one of object['and']){ - if(one['or']){ + expect(object.and).a(expect.any(Array)); + for(const one of object.and){ + if(one.or){ result = result.andWhere(subBuilder => whereBuilder(one, subBuilder)); }else{ expect(Object.keys(one)).lengthOf(1); result = result.andWhere(Object.keys(one)[0], Object.values(one)[0]); } } - }else if(object['or']){ + }else if(object.or){ expect(Object.keys(object)).lengthOf(1); - expect(object['or']).a(expect.any(Array)); - for(let one of object['or']){ - if(one['and']){ + expect(object.or).a(expect.any(Array)); + for(const one of object.or){ + if(one.and){ result = result.orWhere(subBuilder => whereBuilder(one, subBuilder)); }else{ expect(Object.keys(one)).lengthOf(1); @@ -74,9 +74,9 @@ class BaseRepository{ } async update(object){ - let objectCopy = {} + const objectCopy = {} Object.assign(objectCopy, object) - const id = object.id + const {id} = object delete objectCopy.id const result = await this._session.getDB()(this._tableName).update(objectCopy).where("id", id).returning("*"); return result[0]; @@ -86,7 +86,7 @@ class BaseRepository{ * update all rows matching given id */ async updateByIds(object, ids){ - let objectCopy = {} + const objectCopy = {} Object.assign(objectCopy, object) delete objectCopy.id const result = await this._session.getDB()(this._tableName).update(objectCopy).whereIn("id", ids); diff --git a/server/repositories/BaseRepository.spec.js b/server/repositories/BaseRepository.spec.js index 0311317d..4f814249 100644 --- a/server/repositories/BaseRepository.spec.js +++ b/server/repositories/BaseRepository.spec.js @@ -2,10 +2,11 @@ const BaseRepository = require("./BaseRepository"); const {expect} = require("chai"); const knex = require("../database/knex"); const mockKnex = require("mock-knex"); + const tracker = mockKnex.getTracker(); const jestExpect = require("expect"); -const Session = require("../models/Session"); const uuid = require('uuid'); +const Session = require("../models/Session"); describe("BaseRepository", () => { let baseRepository; @@ -33,7 +34,7 @@ describe("BaseRepository", () => { expect(entity).property("id").eq(1); }); - //TODO + // TODO it.skip("getById can not find result, should throw 404", () => { }); @@ -251,7 +252,7 @@ describe("BaseRepository", () => { expect(result).eq(1); }); - //TODO + // TODO describe.skip("count support and and or", () => { }); }); diff --git a/server/repositories/TokenRepository.js b/server/repositories/TokenRepository.js index ee2c51ec..fe2c6811 100644 --- a/server/repositories/TokenRepository.js +++ b/server/repositories/TokenRepository.js @@ -1,8 +1,8 @@ +const expect = require("expect-runtime"); const knex = require('../database/knex'); const config = require('../../config/config'); const HttpError = require("../utils/HttpError"); const BaseRepository = require("./BaseRepository"); -const expect = require("expect-runtime"); const Session = require("../models/Session"); class TokenRepository extends BaseRepository{ diff --git a/server/repositories/TokenRepository.spec.js b/server/repositories/TokenRepository.spec.js index dbafe7a9..21a5dca9 100644 --- a/server/repositories/TokenRepository.spec.js +++ b/server/repositories/TokenRepository.spec.js @@ -1,8 +1,9 @@ -const knex = require("../database/knex"); -const TokenRepository = require("./TokenRepository"); const sinon = require("sinon"); const {expect} = require("chai"); const mockKnex = require("mock-knex"); +const TokenRepository = require("./TokenRepository"); +const knex = require("../database/knex"); + const tracker = mockKnex.getTracker(); const Session = require("../models/Session"); diff --git a/server/repositories/TransactionRepository.js b/server/repositories/TransactionRepository.js index 1d72a4b5..689b3f64 100644 --- a/server/repositories/TransactionRepository.js +++ b/server/repositories/TransactionRepository.js @@ -1,5 +1,5 @@ -const BaseRepository = require("./BaseRepository"); const expect = require("expect-runtime"); +const BaseRepository = require("./BaseRepository"); class TransferRepository extends BaseRepository{ constructor(session){ diff --git a/server/repositories/TransactionRepository.spec.js b/server/repositories/TransactionRepository.spec.js index 1d3d6657..61fa71b3 100644 --- a/server/repositories/TransactionRepository.spec.js +++ b/server/repositories/TransactionRepository.spec.js @@ -2,6 +2,7 @@ const TransactionRepository = require("./TransactionRepository"); const {expect} = require("chai"); const knex = require("../database/knex"); const mockKnex = require("mock-knex"); + const tracker = mockKnex.getTracker(); const jestExpect = require("expect"); const Session = require("../models/Session"); diff --git a/server/repositories/TransferRepository.js b/server/repositories/TransferRepository.js index 03801b48..a4a89f30 100644 --- a/server/repositories/TransferRepository.js +++ b/server/repositories/TransferRepository.js @@ -1,7 +1,7 @@ +const expect = require("expect-runtime"); const knex = require("../database/knex"); const Transfer = require("../models/Transfer"); const BaseRepository = require("./BaseRepository"); -const expect = require("expect-runtime"); const Session = require("../models/Session"); class TransferRepository extends BaseRepository{ diff --git a/server/repositories/TransferRepository.spec.js b/server/repositories/TransferRepository.spec.js index 7debd965..b3cc4b24 100644 --- a/server/repositories/TransferRepository.spec.js +++ b/server/repositories/TransferRepository.spec.js @@ -1,7 +1,8 @@ -const TransferRepository = require("./TransferRepository"); const {expect} = require("chai"); -const knex = require("../database/knex"); const mockKnex = require("mock-knex"); +const TransferRepository = require("./TransferRepository"); +const knex = require("../database/knex"); + const tracker = mockKnex.getTracker(); const Session = require("../models/Session"); const uuid = require('uuid'); diff --git a/server/repositories/TrustRepository.js b/server/repositories/TrustRepository.js index 4c165dc4..3b4eac19 100644 --- a/server/repositories/TrustRepository.js +++ b/server/repositories/TrustRepository.js @@ -1,6 +1,6 @@ +const expect = require("expect-runtime"); const HttpError = require("../utils/HttpError"); const BaseRepository = require("./BaseRepository"); -const expect = require("expect-runtime"); const Session = require("../models/Session"); class TrustRepository extends BaseRepository{ @@ -11,7 +11,7 @@ class TrustRepository extends BaseRepository{ } async get(){ - //const trust_relationship_instance = new trust_relationship(1); + // const trust_relationship_instance = new trust_relationship(1); const list = await this._session.getDB().select() .table(this._tableName); return list; diff --git a/server/repositories/TrustRepository.spec.js b/server/repositories/TrustRepository.spec.js index 08048e8b..45b52554 100644 --- a/server/repositories/TrustRepository.spec.js +++ b/server/repositories/TrustRepository.spec.js @@ -1,7 +1,8 @@ -const TrustRepository = require("./TrustRepository"); const {expect} = require("chai"); -const knex = require("../database/knex"); const mockKnex = require("mock-knex"); +const TrustRepository = require("./TrustRepository"); +const knex = require("../database/knex"); + const tracker = mockKnex.getTracker(); const Session = require("../models/Session"); const uuid = require('uuid'); diff --git a/server/repositories/WalletRepository.js b/server/repositories/WalletRepository.js index 883ea4db..629daf2f 100644 --- a/server/repositories/WalletRepository.js +++ b/server/repositories/WalletRepository.js @@ -1,8 +1,8 @@ /* * The model for: entity, wallet, entity table and so on */ -const HttpError = require("../utils/HttpError"); const expect = require("expect-runtime"); +const HttpError = require("../utils/HttpError"); const BaseRepository = require("./BaseRepository"); const Session = require("../models/Session"); diff --git a/server/repositories/WalletRepository.spec.js b/server/repositories/WalletRepository.spec.js index 98020395..697a1e93 100644 --- a/server/repositories/WalletRepository.spec.js +++ b/server/repositories/WalletRepository.spec.js @@ -2,6 +2,7 @@ const WalletRepository = require("./WalletRepository"); const {expect} = require("chai"); const knex = require("../database/knex"); const mockKnex = require("mock-knex"); + const tracker = mockKnex.getTracker(); const jestExpect = require("expect"); const Session = require("../models/Session"); diff --git a/server/routes/authRouter.js b/server/routes/authRouter.js index 83455985..809d64ae 100644 --- a/server/routes/authRouter.js +++ b/server/routes/authRouter.js @@ -1,10 +1,11 @@ const express = require("express"); + const authRouter = express.Router(); +const Joi = require("joi"); const helper = require("./utils"); const Wallet = require("../models/Wallet"); const WalletService = require("../services/WalletService"); const JWTService = require("../services/JWTService"); -const Joi = require("joi"); const Session = require("../models/Session"); authRouter.post( diff --git a/server/routes/authRouter.spec.js b/server/routes/authRouter.spec.js index 71dd7b69..b6988ac5 100644 --- a/server/routes/authRouter.spec.js +++ b/server/routes/authRouter.spec.js @@ -1,11 +1,11 @@ const request = require("supertest"); const express = require("express"); -const authRouter = require("./authRouter"); const {expect} = require("chai"); -const {errorHandler} = require("./utils"); const sinon = require("sinon"); -const ApiKeyService = require("../services/ApiKeyService"); const bodyParser = require('body-parser'); +const authRouter = require("./authRouter"); +const {errorHandler} = require("./utils"); +const ApiKeyService = require("../services/ApiKeyService"); const WalletService = require("../services/WalletService"); const JWTService = require("../services/JWTService"); diff --git a/server/routes/tokenRouter.js b/server/routes/tokenRouter.js index 60777dc4..bf7aff62 100644 --- a/server/routes/tokenRouter.js +++ b/server/routes/tokenRouter.js @@ -1,11 +1,11 @@ const express = require('express'); const { check, validationResult } = require('express-validator'); +const Joi = require("joi"); const helper = require("./utils"); const TokenService = require("../services/TokenService"); const WalletService = require("../services/WalletService"); const HttpError = require("../utils/HttpError"); const Session = require("../models/Session"); -const Joi = require("joi"); const tokenRouter = express.Router(); @@ -19,14 +19,14 @@ tokenRouter.get('/:id', const tokenService = new TokenService(session); const walletService = new WalletService(session); const token = await tokenService.getById(id); - //check permission + // check permission const json = await token.toJSON(); const walletLogin = await walletService.getById(res.locals.wallet_id); let walletIds = [walletLogin.getId()]; const subWallets = await walletLogin.getSubWallets(); walletIds = [...walletIds, ...subWallets.map(e => e.getId())]; if(walletIds.includes(json.wallet_id)){ - //pass + // pass }else{ throw new HttpError(401, "Have no permission to visit this token"); } @@ -97,20 +97,20 @@ tokenRouter.get('/:id/transactions', const tokenService = new TokenService(session); const walletService = new WalletService(session); const token = await tokenService.getById(id); - //check permission + // check permission const json = await token.toJSON(); const walletLogin = await walletService.getById(res.locals.wallet_id); let walletIds = [walletLogin.getId()]; const subWallets = await walletLogin.getSubWallets(); walletIds = [...walletIds, ...subWallets.map(e => e.getId())]; if(walletIds.includes(json.wallet_id)){ - //pass + // pass }else{ throw new HttpError(401, "Have no permission to visit this token"); } const transactions = await token.getTransactions(limit, start); - let response = []; + const response = []; for(const t of transactions){ const transaction = await tokenService.convertToResponse(t); response.push(transaction); diff --git a/server/routes/tokenRouter.spec.js b/server/routes/tokenRouter.spec.js index 962e6600..04b31514 100644 --- a/server/routes/tokenRouter.spec.js +++ b/server/routes/tokenRouter.spec.js @@ -1,11 +1,12 @@ const request = require("supertest"); const express = require("express"); -const tokenRouter = require("./tokenRouter"); const {expect} = require("chai"); -const {errorHandler} = require("./utils"); const sinon = require("sinon"); -const ApiKeyService = require("../services/ApiKeyService"); const bodyParser = require('body-parser'); +const uuid = require('uuid'); +const tokenRouter = require("./tokenRouter"); +const {errorHandler} = require("./utils"); +const ApiKeyService = require("../services/ApiKeyService"); const WalletService = require("../services/WalletService"); const JWTService = require("../services/JWTService"); const HttpError = require("../utils/HttpError"); @@ -14,7 +15,6 @@ const TokenService = require("../services/TokenService"); const Wallet = require("../models/Wallet"); const Transfer = require("../models/Transfer"); const TransferService = require("../services/TransferService"); -const uuid = require('uuid'); describe("tokenRouter", () => { let app; @@ -76,7 +76,7 @@ describe("tokenRouter", () => { expect(res).property("statusCode").eq(200); expect(res.body.tokens).lengthOf(1); expect(res.body.tokens[0]).property("id").eq(token2Id); - expect(res.body.tokens[0]).property("links").property("capture").eq("/webmap/tree?uuid=" + capture2Id); + expect(res.body.tokens[0]).property("links").property("capture").eq(`/webmap/tree?uuid=${ capture2Id}`); }); it("successfully, sub wallet", async () => { @@ -88,7 +88,7 @@ describe("tokenRouter", () => { .get(`/?limit=10&wallet=${wallet2Id}`); expect(res).property("statusCode").eq(200); expect(res.body.tokens[0]).property("id").eq(tokenId); - expect(res.body.tokens[0]).property("links").property("capture").eq("/webmap/tree?uuid=" + captureId); + expect(res.body.tokens[0]).property("links").property("capture").eq(`/webmap/tree?uuid=${ captureId}`); }); it("sub wallet, no permission", async () => { @@ -141,7 +141,7 @@ describe("tokenRouter", () => { .get(`/${tokenId}`); expect(res).property("statusCode").eq(200); expect(res.body).property("id").eq(tokenId); - expect(res.body).property("links").property("capture").eq("/webmap/tree?uuid=" + captureId); + expect(res.body).property("links").property("capture").eq(`/webmap/tree?uuid=${ captureId}`); }); it("/xxx/transactions successfully", async () => { diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 14bee886..04ef8456 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -1,11 +1,12 @@ const express = require("express"); + const transferRouter = express.Router(); +const Joi = require("joi"); const WalletService = require("../services/WalletService"); const TransferService = require("../services/TransferService"); const Wallet = require("../models/Wallet"); const TrustRelationship = require("../models/TrustRelationship"); const helper = require("./utils"); -const Joi = require("joi"); const TokenService = require("../services/TokenService"); const HttpError = require("../utils/HttpError"); const Transfer = require("../models/Transfer"); @@ -19,7 +20,7 @@ transferRouter.post( Joi.assert( req.body, Joi.alternatives() - //if there is tokens field + // if there is tokens field .conditional(Joi.object({ tokens: Joi.any().required(), }).unknown(),{ @@ -44,7 +45,7 @@ transferRouter.post( }) ); const session = new Session(); - //begin transaction + // begin transaction try{ await session.beginTransaction(); const walletService = new WalletService(session); @@ -57,7 +58,7 @@ transferRouter.post( if(req.body.tokens){ const tokens = []; const tokenService = new TokenService(session); - for(let id of req.body.tokens){ + for(const id of req.body.tokens){ const token = await tokenService.getById(id); tokens.push(token); } @@ -79,11 +80,11 @@ transferRouter.post( await session.commitTransaction(); }catch(e){ if(e instanceof HttpError && !e.shouldRollback()){ - //if the error type is HttpError, means the exception has been handled + // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; }else{ - //unknown exception, rollback the transaction + // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } @@ -102,7 +103,7 @@ transferRouter.post('/:transfer_id/accept', }) ); const session = new Session(); - //begin transaction + // begin transaction try{ await session.beginTransaction(); const walletService = new WalletService(session); @@ -114,11 +115,11 @@ transferRouter.post('/:transfer_id/accept', await session.commitTransaction(); }catch(e){ if(e instanceof HttpError && !e.shouldRollback()){ - //if the error type is HttpError, means the exception has been handled + // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; }else{ - //unknown exception, rollback the transaction + // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } @@ -137,7 +138,7 @@ transferRouter.post('/:transfer_id/decline', }) ); const session = new Session(); - //begin transaction + // begin transaction try{ await session.beginTransaction(); const walletService = new WalletService(session); @@ -149,11 +150,11 @@ transferRouter.post('/:transfer_id/decline', await session.commitTransaction(); }catch(e){ if(e instanceof HttpError && !e.shouldRollback()){ - //if the error type is HttpError, means the exception has been handled + // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; }else{ - //unknown exception, rollback the transaction + // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } @@ -172,7 +173,7 @@ transferRouter.delete('/:transfer_id', }) ); const session = new Session(); - //begin transaction + // begin transaction try{ await session.beginTransaction(); const walletService = new WalletService(session); @@ -184,11 +185,11 @@ transferRouter.delete('/:transfer_id', await session.commitTransaction(); }catch(e){ if(e instanceof HttpError && !e.shouldRollback()){ - //if the error type is HttpError, means the exception has been handled + // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; }else{ - //unknown exception, rollback the transaction + // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } @@ -209,7 +210,7 @@ transferRouter.post('/:transfer_id/fulfill', Joi.assert( req.body, Joi.alternatives() - //if there is tokens field + // if there is tokens field .conditional(Joi.object({ tokens: Joi.any().required(), }).unknown(),{ @@ -222,7 +223,7 @@ transferRouter.post('/:transfer_id/fulfill', }) ); const session = new Session(); - //begin transaction + // begin transaction try{ await session.beginTransaction(); const walletService = new WalletService(session); @@ -232,10 +233,10 @@ transferRouter.post('/:transfer_id/fulfill', if(req.body.implicit){ transferJson = await walletLogin.fulfillTransfer(req.params.transfer_id); }else{ - //load tokens + // load tokens const tokens = []; const tokenService = new TokenService(session); - for(let id of req.body.tokens){ + for(const id of req.body.tokens){ const token = await tokenService.getById(id); tokens.push(token); } @@ -246,11 +247,11 @@ transferRouter.post('/:transfer_id/fulfill', await session.commitTransaction(); }catch(e){ if(e instanceof HttpError && !e.shouldRollback()){ - //if the error type is HttpError, means the exception has been handled + // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; }else{ - //unknown exception, rollback the transaction + // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } @@ -287,8 +288,8 @@ transferRouter.get("/", // todo fix filtering by wallet, instead of undefined should take a wallet object with getId() function const result = await walletTransfer.getTransfers(state, undefined , start, limit); const transferService = new TransferService(session); - let json = []; - for(let t of result){ + const json = []; + for(const t of result){ const j = await transferService.convertToResponse(t); json.push(j); } @@ -341,7 +342,7 @@ transferRouter.get('/:transfer_id/tokens', const walletLogin = await walletService.getById(res.locals.wallet_id); const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start || 0)); - let tokensJson = []; + const tokensJson = []; for(const token of tokens){ const json = await token.toJSON(); tokensJson.push(json); diff --git a/server/routes/transferRouter.spec.js b/server/routes/transferRouter.spec.js index 3a473e8f..38c4abe5 100644 --- a/server/routes/transferRouter.spec.js +++ b/server/routes/transferRouter.spec.js @@ -1,14 +1,17 @@ const request = require("supertest"); const express = require("express"); -const transferRouter = require("./transferRouter"); -const {errorHandler} = require("./utils"); 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} = require("./utils"); + chai.use(sinonChai); const {expect} = chai; const ApiKeyService = require("../services/ApiKeyService"); -const bodyParser = require('body-parser'); const WalletService = require("../services/WalletService"); const JWTService = require("../services/JWTService"); const HttpError = require("../utils/HttpError"); @@ -18,13 +21,11 @@ const Wallet = require("../models/Wallet"); const Transfer = require("../models/Transfer"); const TransferService = require("../services/TransferService"); const Session = require("../models/Session"); -const { extractExpectedAssertionsErrors } = require("expect"); const { column } = require("../database/knex"); -const uuid = require('uuid'); describe("transferRouter", () => { let app; - let session = new Session(); + const session = new Session(); const authenticatedWallet = new Wallet(uuid.v4()) diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index de26294a..aa703fad 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -1,14 +1,15 @@ const express = require('express'); + const trustRouter = express.Router(); const { check, validationResult } = require('express-validator'); const assert = require("assert"); +const Joi = require("joi"); const WalletService = require("../services/WalletService"); const TrustService = require("../services/TrustService"); const Wallet = require("../models/Wallet"); const helper = require("./utils"); const Session = require("../models/Session"); const TrustRelationship = require("../models/TrustRelationship"); -const Joi = require("joi"); trustRouter.get('/', helper.apiKeyHandler, @@ -56,8 +57,8 @@ trustRouter.get('/', } } - let trust_relationships_json = []; - for(let t of trust_relationships){ + const trust_relationships_json = []; + for(const t of trust_relationships){ const j = await trustService.convertToResponse(t); trust_relationships_json.push(j); } @@ -122,7 +123,7 @@ trustRouter.post('/:trustRelationshipId/accept', trustRelationshipId: Joi.string().required() }) ) - const trustRelationshipId = req.params.trustRelationshipId; + const {trustRelationshipId} = req.params; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -149,7 +150,7 @@ trustRouter.post('/:trustRelationshipId/decline', trustRelationshipId: Joi.string().required() }) ) - const trustRelationshipId = req.params.trustRelationshipId; + const {trustRelationshipId} = req.params; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -176,7 +177,7 @@ trustRouter.delete('/:trustRelationshipId', trustRelationshipId: Joi.string().required() }) ) - const trustRelationshipId = req.params.trustRelationshipId; + const {trustRelationshipId} = req.params; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); diff --git a/server/routes/trustRouter.spec.js b/server/routes/trustRouter.spec.js index 4fa95c3a..d02ffa88 100644 --- a/server/routes/trustRouter.spec.js +++ b/server/routes/trustRouter.spec.js @@ -1,14 +1,16 @@ const request = require("supertest"); const express = require("express"); -const trustRouter = require("./trustRouter"); -const {errorHandler} = require("./utils"); 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} = require("./utils"); + chai.use(sinonChai); const {expect} = chai; const ApiKeyService = require("../services/ApiKeyService"); -const bodyParser = require('body-parser'); const WalletService = require("../services/WalletService"); const TrustService = require("../services/TrustService"); const JWTService = require("../services/JWTService"); @@ -17,7 +19,6 @@ const Token = require("../models/Token"); const TokenService = require("../services/TokenService"); const Wallet = require("../models/Wallet"); const TrustRelationship = require("../models/TrustRelationship"); -const uuid = require('uuid'); describe("trustRouter", () => { let app; @@ -138,15 +139,15 @@ describe("trustRouter", () => { expect(res.body.trust_relationships).lengthOf(3); }); - //TODO + // TODO it.skip("wrong state string should throw 422", () => { }); - //TODO + // TODO it.skip("wrong type string should throw 422", () => { }); - //TODO + // TODO it.skip("wrong request_type string should throw 422", () => { }); diff --git a/server/routes/utils.js b/server/routes/utils.js index 5127ba47..38e661a1 100644 --- a/server/routes/utils.js +++ b/server/routes/utils.js @@ -2,10 +2,10 @@ * Some utils for router/express */ const log = require("loglevel"); +const {ValidationError} = require("joi"); const HttpError = require("../utils/HttpError"); const ApiKeyService = require("../services/ApiKeyService"); const JWTService = require("../services/JWTService.js"); -const {ValidationError} = require("joi"); const Session = require("../models/Session"); /* diff --git a/server/routes/utils.spec.js b/server/routes/utils.spec.js index 2455cb4d..1d4fa044 100644 --- a/server/routes/utils.spec.js +++ b/server/routes/utils.spec.js @@ -1,11 +1,11 @@ const request = require("supertest"); const express = require("express"); -//const {handlerWrapper, errorHandler} = require("./utils"); -const helper = require("./utils"); +// const {handlerWrapper, errorHandler} = require("./utils"); const {expect} = require("chai"); +const sinon = require("sinon"); +const helper = require("./utils"); const HttpError = require("../utils/HttpError"); const ApiKeyService = require("../services/ApiKeyService"); -const sinon = require("sinon"); const JWTService = require("../services/JWTService"); describe("routers/utils", () => { @@ -92,7 +92,7 @@ describe("routers/utils", () => { it("check failed, should get response with code 401", async () => { const app = express(); - //mock + // mock sinon.stub(ApiKeyService.prototype, "check").rejects(new HttpError(401)); app.get("/test", [ @@ -110,7 +110,7 @@ describe("routers/utils", () => { it("check passed, should get response with code 200", async () => { const app = express(); - //mock + // mock sinon.stub(ApiKeyService.prototype, "check").rejects(new HttpError(401)); app.get("/test", [ @@ -131,7 +131,7 @@ describe("routers/utils", () => { it("pass correct token should pass the verify", async () => { const app = express(); - //mock + // mock sinon.stub(ApiKeyService.prototype, "check").rejects(new HttpError(401)); app.get("/test", [ @@ -153,7 +153,7 @@ describe("routers/utils", () => { it("pass corupt token should get response with code 403", async () => { const app = express(); - //mock + // mock sinon.stub(ApiKeyService.prototype, "check").rejects(new HttpError(401)); app.get("/test", [ @@ -168,7 +168,7 @@ describe("routers/utils", () => { const token = jwt.sign(payload); const res = await request(app) .get("/test") - .set('Authorization', `Bearer ${token.slice(1)}`);//NOTE corupt here + .set('Authorization', `Bearer ${token.slice(1)}`);// NOTE corupt here expect(res.statusCode).eq(403); ApiKeyService.prototype.check.restore(); }); diff --git a/server/routes/walletRouter.js b/server/routes/walletRouter.js index 3016b0e4..837ea20f 100644 --- a/server/routes/walletRouter.js +++ b/server/routes/walletRouter.js @@ -1,11 +1,11 @@ const express = require('express'); +const Joi = require("joi"); +const _ = require('lodash') const helper = require('./utils'); const WalletService = require("../services/WalletService"); const TokenService = require("../services/TokenService"); const TrustService = require("../services/TrustService"); -const Joi = require("joi"); const Session = require("../models/Session"); -const _ = require('lodash') const walletRouter = express.Router(); @@ -37,10 +37,10 @@ walletRouter.get('/', walletsJson.push(json); } - let numStart = parseInt(start); - let numLimit = parseInt(limit); - let numBegin = numStart?numStart-1:0; - let numEnd=numBegin+numLimit; + const numStart = parseInt(start); + const numLimit = parseInt(limit); + const numBegin = numStart?numStart-1:0; + const numEnd=numBegin+numLimit; walletsJson = walletsJson.slice(numBegin, numEnd) res.status(200).json({ @@ -66,7 +66,7 @@ walletRouter.get('/:wallet_id/trust_relationships', req.query.request_type, ); const trust_relationships_json = []; - for(let t of trust_relationships){ + for(const t of trust_relationships){ const j = await trustService.convertToResponse(t); trust_relationships_json.push(j); } diff --git a/server/routes/walletRouter.spec.js b/server/routes/walletRouter.spec.js index 95592f17..588e0b24 100644 --- a/server/routes/walletRouter.spec.js +++ b/server/routes/walletRouter.spec.js @@ -1,13 +1,15 @@ const request = require("supertest"); const express = require("express"); -const walletRouter = require("./walletRouter"); -const {errorHandler} = require("./utils"); 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} = require("./utils"); + chai.use(sinonChai); const {expect} = chai; -const bodyParser = require('body-parser'); const ApiKeyService = require("../services/ApiKeyService"); const WalletService = require("../services/WalletService"); const TokenService = require("../services/TokenService"); @@ -15,7 +17,6 @@ const TrustService = require("../services/TrustService"); const JWTService = require("../services/JWTService"); const HttpError = require("../utils/HttpError"); const Wallet = require("../models/Wallet"); -const uuid = require('uuid'); describe("walletRouter", ()=> { diff --git a/server/server.js b/server/server.js index 21a5cb04..d1ea8143 100644 --- a/server/server.js +++ b/server/server.js @@ -1,11 +1,12 @@ require('dotenv').config() const log = require("loglevel"); -//setup log level +// setup log level require("./setup"); const app = require("./app"); + const port = process.env.NODE_PORT || 3006; app.listen(port,()=>{ - log.info('listening on port:' + port); + log.info(`listening on port:${ port}`); log.debug("debug log level!"); }); diff --git a/server/serverTest.js b/server/serverTest.js index 7c2fb2f8..a4def58f 100644 --- a/server/serverTest.js +++ b/server/serverTest.js @@ -3,14 +3,15 @@ */ require('dotenv').config() const app = require("./app"); + const port = process.env.NODE_PORT || 3006; const seed = require('../__tests__/seed'); -//set the log level +// set the log level require("./setup"); const log = require("loglevel"); app.listen(port,async ()=>{ - log.info('listening on port:' + port); + log.info(`listening on port:${ port}`); log.info("Seed data"); log.debug("debug log level!"); await seed.clear(); diff --git a/server/services/ApiKeyService.js b/server/services/ApiKeyService.js index 4d364b18..89e514d0 100644 --- a/server/services/ApiKeyService.js +++ b/server/services/ApiKeyService.js @@ -1,9 +1,9 @@ const FS = require('fs'); const log = require("loglevel"); const path = require("path"); +const expect = require("expect-runtime"); const HttpError = require("../utils/HttpError"); const ApiKeyRepository = require("../repositories/ApiKeyRepository"); -const expect = require("expect-runtime"); // PRIVATE and PUBLIC key const privateKEY = process.env.PRIVATE_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); @@ -40,8 +40,8 @@ class ApiKeyService{ module.exports = ApiKeyService; -//const authController = {}; -//authController.apiKey = async (req, res, next) => { +// const authController = {}; +// authController.apiKey = async (req, res, next) => { // if (!req.headers['treetracker-api-key']) { // console.log('ERROR: Invalid access - no API key'); // next({ @@ -70,5 +70,5 @@ module.exports = ApiKeyService; // } // // console.log('Valid Access'); // next(); -//}; +// }; diff --git a/server/services/ApiKeyService.spec.js b/server/services/ApiKeyService.spec.js index 70f275e8..368b34d1 100644 --- a/server/services/ApiKeyService.spec.js +++ b/server/services/ApiKeyService.spec.js @@ -1,6 +1,6 @@ -const ApiKeyService = require("./ApiKeyService"); 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"); diff --git a/server/services/JWTService.js b/server/services/JWTService.js index 389335cb..bbfc9a0d 100644 --- a/server/services/JWTService.js +++ b/server/services/JWTService.js @@ -10,8 +10,8 @@ const path = require("path"); const HttpError = require("../utils/HttpError"); // PRIVATE and PUBLIC key -const privateKEY = process.env.PRIVATE_KEY //FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); -const publicKEY = process.env.PUBLIC_KEY //FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key.pub'), 'utf8'); +const privateKEY = process.env.PRIVATE_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); +const publicKEY = process.env.PUBLIC_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key.pub'), 'utf8'); const signingOptions = { issuer: "greenstand", @@ -36,7 +36,7 @@ class JWTService{ if (!authorization) { throw (403, 'ERROR: Authentication, no token supplied for protected path'); } - //accounts for the "Bearer" string before the token + // accounts for the "Bearer" string before the token const tokenArray = authorization.split(' '); const token = tokenArray[1]; let result; diff --git a/server/services/JWTService.spec.js b/server/services/JWTService.spec.js index 3dbfe68d..fce096d0 100644 --- a/server/services/JWTService.spec.js +++ b/server/services/JWTService.spec.js @@ -1,5 +1,5 @@ -const JWTService = require("./JWTService"); const {expect} = require("chai"); +const JWTService = require("./JWTService"); diff --git a/server/services/TokenService.js b/server/services/TokenService.js index 87951c7a..189480e3 100644 --- a/server/services/TokenService.js +++ b/server/services/TokenService.js @@ -1,8 +1,8 @@ +const log = require("loglevel"); +const Joi = require("joi"); const Token = require("../models/Token"); const TokenRepository = require("../repositories/TokenRepository"); const TransactionRepository = require("../repositories/TransactionRepository"); -const log = require("loglevel"); -const Joi = require("joi"); class TokenService{ @@ -10,7 +10,7 @@ class TokenService{ this._session = session this.tokenRepository = new TokenRepository(session); this.transactionRepository = new TransactionRepository(session); - const WalletService = require("../services/WalletService"); + const WalletService = require("./WalletService"); this.walletService = new WalletService(session); } diff --git a/server/services/TokenService.spec.js b/server/services/TokenService.spec.js index 1f9aef73..9ecc85ce 100644 --- a/server/services/TokenService.spec.js +++ b/server/services/TokenService.spec.js @@ -1,22 +1,23 @@ -const TokenService = require("./TokenService"); const sinon = require("sinon"); -const TokenRepository = require("../repositories/TokenRepository"); -const HttpError = require("../utils/HttpError"); 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"); + chai.use(sinonChai); const {expect} = chai; const Wallet = require("../models/Wallet"); const Token = require("../models/Token"); -const WalletService = require("../services/WalletService"); +const WalletService = require("./WalletService"); const Session = require("../models/Session"); const TransactionRepository = require("../repositories/TransactionRepository"); -const uuid = require('uuid'); describe("Token", () => { let tokenService; - let session = new Session(); + const session = new Session(); beforeEach(() => { tokenService = new TokenService(); diff --git a/server/services/TransferService.js b/server/services/TransferService.js index 322dd728..d4c016dd 100644 --- a/server/services/TransferService.js +++ b/server/services/TransferService.js @@ -1,5 +1,5 @@ -const WalletService = require("./WalletService"); const expect = require("expect-runtime"); +const WalletService = require("./WalletService"); class TransferService{ diff --git a/server/services/TransferService.spec.js b/server/services/TransferService.spec.js index 2a1e16f9..f2a70856 100644 --- a/server/services/TransferService.spec.js +++ b/server/services/TransferService.spec.js @@ -1,19 +1,20 @@ const TransferService = require("./TransferService"); 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"); + chai.use(sinonChai); const {expect} = chai; -const Session = require("../models/Session"); const uuid = require('uuid'); +const Session = require("../models/Session"); +const Wallet = require("../models/Wallet"); describe("TransferService", () => { let transferService ; describe("", () => { - let session = new Session(); + const session = new Session(); transferService = new TransferService(session); }); diff --git a/server/services/TrustService.js b/server/services/TrustService.js index d34e92d5..cf6c62f3 100644 --- a/server/services/TrustService.js +++ b/server/services/TrustService.js @@ -1,11 +1,11 @@ -const WalletService = require("./WalletService"); const expect = require("expect-runtime"); +const WalletService = require("./WalletService"); const Session = require("../models/Session"); class TrustService{ constructor(){ - let session = new Session(); + const session = new Session(); this.walletService = new WalletService(session); } diff --git a/server/services/TrustService.spec.js b/server/services/TrustService.spec.js index bae5dda5..5940de1e 100644 --- a/server/services/TrustService.spec.js +++ b/server/services/TrustService.spec.js @@ -5,12 +5,13 @@ const jestExpect = require("expect"); const sinon = require("sinon"); const chai = require("chai"); const sinonChai = require("sinon-chai"); + chai.use(sinonChai); const {expect} = chai; const uuid = require('uuid'); describe("TrustService", () => { - let trustService = new TrustService(); + const trustService = new TrustService(); describe("", () => { }); diff --git a/server/services/WalletService.js b/server/services/WalletService.js index ac6b1ddb..af869cb6 100644 --- a/server/services/WalletService.js +++ b/server/services/WalletService.js @@ -1,8 +1,8 @@ +const expect = require('expect-runtime'); +const { validate: uuidValidate } = require('uuid'); const WalletRepository = require('../repositories/WalletRepository'); const Wallet = require('../models/Wallet'); const HttpError = require("../utils/HttpError"); -const expect = require('expect-runtime'); -const { validate: uuidValidate } = require('uuid'); class WalletService { constructor(session){ diff --git a/server/services/WalletService.spec.js b/server/services/WalletService.spec.js index 408499c0..6ae0e851 100644 --- a/server/services/WalletService.spec.js +++ b/server/services/WalletService.spec.js @@ -1,14 +1,14 @@ -const WalletService = require("./WalletService"); -const WalletRepository = require("../repositories/WalletRepository"); 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 uuid = require('uuid'); describe("WalletService", () => { let walletService; - let session = new Session(); + const session = new Session(); beforeEach(() => { walletService = new WalletService(session); diff --git a/server/setup.js b/server/setup.js index 4415e9f9..868a7d14 100644 --- a/server/setup.js +++ b/server/setup.js @@ -2,6 +2,7 @@ * A file to setup some global setting, like log level */ const log = require("loglevel"); + if(process.env.NODE_LOG_LEVEL){ log.setDefaultLevel(process.env.NODE_LOG_LEVEL); }else{ @@ -11,19 +12,19 @@ if(process.env.NODE_LOG_LEVEL){ const http = require('http') -var loglevelServerSend = function(logger,options) { +const loglevelServerSend = function(logger,options) { if (!logger || !logger.methodFactory) throw new Error('loglevel instance has to be specified in order to be extended') - var _url = options && options.url || 'http://localhost:8000/main/log', - _callOriginal = options && options.callOriginal || false, - _prefix = options && options.prefix, - _originalFactory = logger.methodFactory, - _sendQueue = [], - _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) { - var rawMethod = _originalFactory(methodName, logLevel) + const rawMethod = _originalFactory(methodName, logLevel) return function (message) { if (typeof _prefix === 'string') @@ -31,7 +32,7 @@ var loglevelServerSend = function(logger,options) { else if (typeof _prefix === 'function') message = _prefix(methodName,message) else - message = methodName + ': ' + message + message = `${methodName }: ${ message}` if (_callOriginal) rawMethod(message) @@ -83,7 +84,7 @@ var loglevelServerSend = function(logger,options) { } if(process.env.REMOTE_LOG_URL){ - console.log("Using remote log endpoint: " + process.env.REMOTE_LOG_URL) + console.log(`Using remote log endpoint: ${ process.env.REMOTE_LOG_URL}`) loglevelServerSend(log,{url:process.env.REMOTE_LOG_URL}) } diff --git a/server/utils/HttpError.js b/server/utils/HttpError.js index 16d0695d..908f303a 100644 --- a/server/utils/HttpError.js +++ b/server/utils/HttpError.js @@ -9,8 +9,8 @@ class HttpError extends Error { constructor(code, message, toRollback){ super(message); this.code = code; - //set rollback flag, so the transaction of db would rollback when catch this error - //set default to true + // set rollback flag, so the transaction of db would rollback when catch this error + // set default to true this._toRollback = toRollback || true; } From f4a71f1cc7e6d5b7889c3e228166a52ab4d0c5e6 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Mon, 5 Apr 2021 21:51:57 +0100 Subject: [PATCH 26/42] minor linter fixes --- server/routes/transferRouter.js | 312 ++++++++++++++---------- server/routes/trustRouter.js | 133 +++++----- server/services/ApiKeyService.js | 41 ++-- server/services/TransferService.js | 15 +- server/services/TransferService.spec.js | 49 ++-- server/services/TrustService.js | 1 - server/services/WalletService.js | 1 - server/setup.js | 66 ++--- 8 files changed, 331 insertions(+), 287 deletions(-) diff --git a/server/routes/transferRouter.js b/server/routes/transferRouter.js index 04ef8456..cfb98adc 100644 --- a/server/routes/transferRouter.js +++ b/server/routes/transferRouter.js @@ -1,98 +1,110 @@ -const express = require("express"); +const express = require('express'); const transferRouter = express.Router(); -const Joi = require("joi"); -const WalletService = require("../services/WalletService"); -const TransferService = require("../services/TransferService"); -const Wallet = require("../models/Wallet"); -const TrustRelationship = require("../models/TrustRelationship"); -const helper = require("./utils"); -const TokenService = require("../services/TokenService"); -const HttpError = require("../utils/HttpError"); -const Transfer = require("../models/Transfer"); -const Session = require("../models/Session"); +const Joi = require('joi'); +const { assert } = require('joi'); +const WalletService = require('../services/WalletService'); +const TransferService = require('../services/TransferService'); +const Wallet = require('../models/Wallet'); +const TrustRelationship = require('../models/TrustRelationship'); +const helper = require('./utils'); +const TokenService = require('../services/TokenService'); +const HttpError = require('../utils/HttpError'); +const Transfer = require('../models/Transfer'); +const Session = require('../models/Session'); transferRouter.post( - "/", + '/', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { Joi.assert( req.body, Joi.alternatives() - // if there is tokens field - .conditional(Joi.object({ - tokens: Joi.any().required(), - }).unknown(),{ - then: Joi.object({ - tokens: Joi.array().items(Joi.string()).required().unique(), - sender_wallet: Joi.alternatives().try( - Joi.string(), - ).required(), - receiver_wallet: Joi.alternatives().try( - Joi.string(), - ).required(), - }), - otherwise: Joi.object({ - bundle: Joi.object({ - bundle_size: Joi.number().min(1).max(10000).integer(), - }).required(), - sender_wallet: Joi.string() - .required(), - receiver_wallet: Joi.string() - .required(), - }), - }) + // if there is tokens field + .conditional( + Joi.object({ + tokens: Joi.any().required(), + }).unknown(), + { + then: Joi.object({ + tokens: Joi.array().items(Joi.string()).required().unique(), + sender_wallet: Joi.alternatives().try(Joi.string()).required(), + receiver_wallet: Joi.alternatives().try(Joi.string()).required(), + }), + otherwise: Joi.object({ + bundle: Joi.object({ + bundle_size: Joi.number().min(1).max(10000).integer(), + }).required(), + sender_wallet: Joi.string().required(), + receiver_wallet: Joi.string().required(), + }), + }, + ), ); const session = new Session(); // begin transaction - try{ + try { await session.beginTransaction(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const walletSender = await walletService.getByIdOrName(req.body.sender_wallet); - const walletReceiver = await walletService.getByIdOrName(req.body.receiver_wallet); + const walletSender = await walletService.getByIdOrName( + req.body.sender_wallet, + ); + const walletReceiver = await walletService.getByIdOrName( + req.body.receiver_wallet, + ); let result; - if(req.body.tokens){ + if (req.body.tokens) { const tokens = []; const tokenService = new TokenService(session); - for(const id of req.body.tokens){ - const token = await tokenService.getById(id); + for (const id of req.body.tokens) { + const token = await tokenService.getById(id); tokens.push(token); } - result = await walletLogin.transfer(walletSender, walletReceiver, tokens); - }else{ - result = await walletLogin.transferBundle(walletSender, walletReceiver, req.body.bundle.bundle_size); + result = await walletLogin.transfer( + walletSender, + walletReceiver, + tokens, + ); + } else { + result = await walletLogin.transferBundle( + walletSender, + walletReceiver, + req.body.bundle.bundle_size, + ); } const transferService = new TransferService(session); result = await transferService.convertToResponse(result); - if(result.state === Transfer.STATE.completed){ + if (result.state === Transfer.STATE.completed) { res.status(201).json(result); - }else if( - result.state === Transfer.STATE.pending || - result.state === Transfer.STATE.requested){ + } else if ( + result.state === Transfer.STATE.pending || + result.state === Transfer.STATE.requested + ) { res.status(202).json(result); - }else{ - expect.fail(); + } else { + throw new Error(`Unexpected state ${result.state}`); } await session.commitTransaction(); - }catch(e){ - if(e instanceof HttpError && !e.shouldRollback()){ + } catch (e) { + if (e instanceof HttpError && !e.shouldRollback()) { // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; - }else{ + } else { // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } } - }) + }), ); -transferRouter.post('/:transfer_id/accept', +transferRouter.post( + '/:transfer_id/accept', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { @@ -100,34 +112,39 @@ transferRouter.post('/:transfer_id/accept', req.params, Joi.object({ transfer_id: Joi.string().guid().required(), - }) + }), ); const session = new Session(); // begin transaction - try{ + try { await session.beginTransaction(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const transferJson = await walletLogin.acceptTransfer(req.params.transfer_id); + const transferJson = await walletLogin.acceptTransfer( + req.params.transfer_id, + ); const transferService = new TransferService(session); - const transferJson2 = await transferService.convertToResponse(transferJson); + const transferJson2 = await transferService.convertToResponse( + transferJson, + ); res.status(200).json(transferJson2); await session.commitTransaction(); - }catch(e){ - if(e instanceof HttpError && !e.shouldRollback()){ + } catch (e) { + if (e instanceof HttpError && !e.shouldRollback()) { // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; - }else{ + } else { // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } } - }) + }), ); -transferRouter.post('/:transfer_id/decline', +transferRouter.post( + '/:transfer_id/decline', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { @@ -135,34 +152,39 @@ transferRouter.post('/:transfer_id/decline', req.params, Joi.object({ transfer_id: Joi.string().guid().required(), - }) + }), ); const session = new Session(); // begin transaction - try{ + try { await session.beginTransaction(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const transferJson = await walletLogin.declineTransfer(req.params.transfer_id); + const transferJson = await walletLogin.declineTransfer( + req.params.transfer_id, + ); const transferService = new TransferService(session); - const transferJson2 = await transferService.convertToResponse(transferJson); + const transferJson2 = await transferService.convertToResponse( + transferJson, + ); res.status(200).json(transferJson2); await session.commitTransaction(); - }catch(e){ - if(e instanceof HttpError && !e.shouldRollback()){ + } catch (e) { + if (e instanceof HttpError && !e.shouldRollback()) { // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; - }else{ + } else { // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } } - }) + }), ); -transferRouter.delete('/:transfer_id', +transferRouter.delete( + '/:transfer_id', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { @@ -170,34 +192,39 @@ transferRouter.delete('/:transfer_id', req.params, Joi.object({ transfer_id: Joi.string().guid().required(), - }) + }), ); const session = new Session(); // begin transaction - try{ + try { await session.beginTransaction(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const transferJson = await walletLogin.cancelTransfer(req.params.transfer_id); + const transferJson = await walletLogin.cancelTransfer( + req.params.transfer_id, + ); const transferService = new TransferService(session); - const transferJson2 = await transferService.convertToResponse(transferJson); + const transferJson2 = await transferService.convertToResponse( + transferJson, + ); res.status(200).json(transferJson2); await session.commitTransaction(); - }catch(e){ - if(e instanceof HttpError && !e.shouldRollback()){ + } catch (e) { + if (e instanceof HttpError && !e.shouldRollback()) { // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; - }else{ + } else { // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } } - }) + }), ); -transferRouter.post('/:transfer_id/fulfill', +transferRouter.post( + '/:transfer_id/fulfill', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { @@ -205,100 +232,116 @@ transferRouter.post('/:transfer_id/fulfill', req.params, Joi.object({ transfer_id: Joi.string().guid().required(), - }) + }), ); Joi.assert( req.body, Joi.alternatives() - // if there is tokens field - .conditional(Joi.object({ - tokens: Joi.any().required(), - }).unknown(),{ - then: Joi.object({ - tokens: Joi.array().items(Joi.string()).required().unique(), - }), - otherwise: Joi.object({ - implicit: Joi.boolean().truthy().required(), - }), - }) + // if there is tokens field + .conditional( + Joi.object({ + tokens: Joi.any().required(), + }).unknown(), + { + then: Joi.object({ + tokens: Joi.array().items(Joi.string()).required().unique(), + }), + otherwise: Joi.object({ + implicit: Joi.boolean().truthy().required(), + }), + }, + ), ); const session = new Session(); // begin transaction - try{ + try { await session.beginTransaction(); const walletService = new WalletService(session); const transferService = new TransferService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); let transferJson; - if(req.body.implicit){ - transferJson = await walletLogin.fulfillTransfer(req.params.transfer_id); - }else{ + if (req.body.implicit) { + transferJson = await walletLogin.fulfillTransfer( + req.params.transfer_id, + ); + } else { // load tokens const tokens = []; const tokenService = new TokenService(session); - for(const id of req.body.tokens){ - const token = await tokenService.getById(id); + for (const id of req.body.tokens) { + const token = await tokenService.getById(id); tokens.push(token); } - transferJson = await walletLogin.fulfillTransferWithTokens(req.params.transfer_id, tokens); + transferJson = await walletLogin.fulfillTransferWithTokens( + req.params.transfer_id, + tokens, + ); } - const transferJson2 = await transferService.convertToResponse(transferJson); + const transferJson2 = await transferService.convertToResponse( + transferJson, + ); res.status(200).json(transferJson2); await session.commitTransaction(); - }catch(e){ - if(e instanceof HttpError && !e.shouldRollback()){ + } catch (e) { + if (e instanceof HttpError && !e.shouldRollback()) { // if the error type is HttpError, means the exception has been handled await session.commitTransaction(); throw e; - }else{ + } else { // unknown exception, rollback the transaction await session.rollbackTransaction(); throw e; } } - }) + }), ); -transferRouter.get("/", +transferRouter.get( + '/', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { Joi.assert( req.query, Joi.object({ - state: Joi.string() - .valid(...Object.values(Transfer.STATE)), + state: Joi.string().valid(...Object.values(Transfer.STATE)), wallet: Joi.alternatives().try( Joi.string(), - Joi.number().min(4).max(32) + Joi.number().min(4).max(32), ), limit: Joi.number().min(1).max(1000).required(), - start: Joi.number().min(0).integer().default(0) - }) + start: Joi.number().min(0).integer().default(0), + }), ); - const {state, wallet, limit, start} = req.query; + const { state, wallet, limit, start } = req.query; const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); let walletTransfer = walletLogin; - if(wallet){ + if (wallet) { walletTransfer = await walletService.getByIdOrName(wallet); } // todo fix filtering by wallet, instead of undefined should take a wallet object with getId() function - const result = await walletTransfer.getTransfers(state, undefined , start, limit); + const result = await walletTransfer.getTransfers( + state, + undefined, + start, + limit, + ); const transferService = new TransferService(session); const json = []; - for(const t of result){ + for (const t of result) { const j = await transferService.convertToResponse(t); json.push(j); } - res.status(200).json({transfers: json}); - }) + res.status(200).json({ transfers: json }); + }), ); -transferRouter.get('/:transfer_id', +transferRouter.get( + '/:transfer_id', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { @@ -306,19 +349,24 @@ transferRouter.get('/:transfer_id', req.params, Joi.object({ transfer_id: Joi.string().guid().required(), - }) + }), ); const session = new Session(); const walletService = new WalletService(session); const transferService = new TransferService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const transferObject = await walletLogin.getTransferById(req.params.transfer_id); - const transferJson = await transferService.convertToResponse(transferObject); + const transferObject = await walletLogin.getTransferById( + req.params.transfer_id, + ); + const transferJson = await transferService.convertToResponse( + transferObject, + ); res.status(200).json(transferJson); - }) + }), ); -transferRouter.get('/:transfer_id/tokens', +transferRouter.get( + '/:transfer_id/tokens', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { @@ -326,7 +374,7 @@ transferRouter.get('/:transfer_id/tokens', req.params, Joi.object({ transfer_id: Joi.string().guid().required(), - }) + }), ); Joi.assert( @@ -334,23 +382,27 @@ transferRouter.get('/:transfer_id/tokens', Joi.object({ limit: Joi.number().min(1).max(1000).required(), start: Joi.number().min(0).integer().default(0), - }) + }), ); - const {limit, start} = req.query; + const { limit, start } = req.query; const session = new Session(); const walletService = new WalletService(session); const walletLogin = await walletService.getById(res.locals.wallet_id); - const tokens = await walletLogin.getTokensByTransferId(req.params.transfer_id, Number(limit), Number(start || 0)); + const tokens = await walletLogin.getTokensByTransferId( + req.params.transfer_id, + Number(limit), + Number(start || 0), + ); const tokensJson = []; - for(const token of tokens){ + for (const token of tokens) { const json = await token.toJSON(); tokensJson.push(json); } res.status(200).json({ tokens: tokensJson, }); - }) + }), ); module.exports = transferRouter; diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index aa703fad..0238fa99 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -2,16 +2,17 @@ const express = require('express'); const trustRouter = express.Router(); const { check, validationResult } = require('express-validator'); -const assert = require("assert"); -const Joi = require("joi"); -const WalletService = require("../services/WalletService"); -const TrustService = require("../services/TrustService"); -const Wallet = require("../models/Wallet"); -const helper = require("./utils"); -const Session = require("../models/Session"); -const TrustRelationship = require("../models/TrustRelationship"); +const assert = require('assert'); +const Joi = require('joi'); +const WalletService = require('../services/WalletService'); +const TrustService = require('../services/TrustService'); +const Wallet = require('../models/Wallet'); +const helper = require('./utils'); +const Session = require('../models/Session'); +const TrustRelationship = require('../models/TrustRelationship'); -trustRouter.get('/', +trustRouter.get( + '/', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res, next) => { @@ -23,15 +24,15 @@ trustRouter.get('/', request_type: Joi.string(), start: Joi.number().min(0).default(0).integer(), limit: Joi.number().min(1).max(10000).integer().default(1000), - }) - ) + }), + ); Joi.assert( res.locals, Joi.object({ - wallet_id: Joi.string().required() - }) - ) - const {state, type, request_type, limit, start} = req.query; + wallet_id: Joi.string().required(), + }), + ); + const { state, type, request_type, limit, start } = req.query; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -41,60 +42,67 @@ trustRouter.get('/', type, request_type, Number(start || 0), - Number(limit || 0) + Number(limit || 0), ); const subWallets = await wallet.getSubWallets(); - for(const sw of subWallets){ + for (const sw of subWallets) { const trustRelationships = await sw.getTrustRelationships( req.query.state, req.query.type, req.query.request_type, ); - for(tr of trustRelationships){ - if(trust_relationships.every(e => e.id !== tr.id)){ + for (const tr of trustRelationships) { + if (trust_relationships.every((e) => e.id !== tr.id)) { trust_relationships.push(tr); } } } const trust_relationships_json = []; - for(const t of trust_relationships){ + for (const t of trust_relationships) { const j = await trustService.convertToResponse(t); trust_relationships_json.push(j); } - + res.status(200).json({ trust_relationships: trust_relationships_json, }); }), ); -trustRouter.post('/', +trustRouter.post( + '/', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { Joi.assert( req.body, Joi.object({ - trust_request_type: Joi.string().required().valid(...Object.keys(TrustRelationship.ENTITY_TRUST_REQUEST_TYPE)), + trust_request_type: Joi.string() + .required() + .valid(...Object.keys(TrustRelationship.ENTITY_TRUST_REQUEST_TYPE)), requestee_wallet: Joi.string().required(), - }) + }), ); Joi.assert( res.locals, Joi.object({ - wallet_id: Joi.string().required() - }) - ) - + wallet_id: Joi.string().required(), + }), + ); + const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); const wallet = await walletService.getById(res.locals.wallet_id); - const requesteeWallet = await walletService.getByName(req.body.requestee_wallet); + const requesteeWallet = await walletService.getByName( + req.body.requestee_wallet, + ); let requesterWallet = wallet; - if(req.body.requester_wallet){ - requesterWallet = await walletService.getByName(req.body.requester_wallet); + if (req.body.requester_wallet) { + requesterWallet = await walletService.getByName( + req.body.requester_wallet, + ); } const trust_relationship = await wallet.requestTrustFromAWallet( @@ -102,28 +110,31 @@ trustRouter.post('/', requesterWallet, requesteeWallet, ); - const trust_relationship_json = await trustService.convertToResponse(trust_relationship); + const trust_relationship_json = await trustService.convertToResponse( + trust_relationship, + ); res.status(200).json(trust_relationship_json); - }) + }), ); -trustRouter.post('/:trustRelationshipId/accept', +trustRouter.post( + '/:trustRelationshipId/accept', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { Joi.assert( res.locals, Joi.object({ - wallet_id: Joi.string().required() - }) - ) + wallet_id: Joi.string().required(), + }), + ); Joi.assert( req.params, Joi.object({ - trustRelationshipId: Joi.string().required() - }) - ) - const {trustRelationshipId} = req.params; + trustRelationshipId: Joi.string().required(), + }), + ); + const { trustRelationshipId } = req.params; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -131,26 +142,27 @@ trustRouter.post('/:trustRelationshipId/accept', const json = await wallet.acceptTrustRequestSentToMe(trustRelationshipId); const json2 = await trustService.convertToResponse(json); res.status(200).json(json2); - }) + }), ); -trustRouter.post('/:trustRelationshipId/decline', +trustRouter.post( + '/:trustRelationshipId/decline', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { Joi.assert( res.locals, Joi.object({ - wallet_id: Joi.string().required() - }) - ) + wallet_id: Joi.string().required(), + }), + ); Joi.assert( req.params, Joi.object({ - trustRelationshipId: Joi.string().required() - }) - ) - const {trustRelationshipId} = req.params; + trustRelationshipId: Joi.string().required(), + }), + ); + const { trustRelationshipId } = req.params; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -158,26 +170,27 @@ trustRouter.post('/:trustRelationshipId/decline', const json = await wallet.declineTrustRequestSentToMe(trustRelationshipId); const json2 = await trustService.convertToResponse(json); res.status(200).json(json2); - }) + }), ); -trustRouter.delete('/:trustRelationshipId', +trustRouter.delete( + '/:trustRelationshipId', helper.apiKeyHandler, helper.verifyJWTHandler, helper.handlerWrapper(async (req, res) => { Joi.assert( res.locals, Joi.object({ - wallet_id: Joi.string().required() - }) - ) + wallet_id: Joi.string().required(), + }), + ); Joi.assert( req.params, Joi.object({ - trustRelationshipId: Joi.string().required() - }) - ) - const {trustRelationshipId} = req.params; + trustRelationshipId: Joi.string().required(), + }), + ); + const { trustRelationshipId } = req.params; const session = new Session(); const walletService = new WalletService(session); const trustService = new TrustService(session); @@ -185,7 +198,7 @@ trustRouter.delete('/:trustRelationshipId', const json = await wallet.cancelTrustRequestSentToMe(trustRelationshipId); const json2 = await trustService.convertToResponse(json); res.status(200).json(json2); - }) + }), ); module.exports = trustRouter; diff --git a/server/services/ApiKeyService.js b/server/services/ApiKeyService.js index 89e514d0..de5a2568 100644 --- a/server/services/ApiKeyService.js +++ b/server/services/ApiKeyService.js @@ -1,39 +1,37 @@ const FS = require('fs'); -const log = require("loglevel"); -const path = require("path"); -const expect = require("expect-runtime"); -const HttpError = require("../utils/HttpError"); -const ApiKeyRepository = require("../repositories/ApiKeyRepository"); +const log = require('loglevel'); +const path = require('path'); +const HttpError = require('../utils/HttpError'); +const ApiKeyRepository = require('../repositories/ApiKeyRepository'); // PRIVATE and PUBLIC key -const privateKEY = process.env.PRIVATE_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); -const publicKEY = process.env.PUBLIC_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key.pub'), 'utf8'); +const privateKEY = process.env.PRIVATE_KEY; // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); +const publicKEY = process.env.PUBLIC_KEY; // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key.pub'), 'utf8'); - -class ApiKeyService{ - constructor(session){ +class ApiKeyService { + constructor(session) { this.apiKeyRepository = new ApiKeyRepository(session); } - async check(apiKey){ + async check(apiKey) { if (!apiKey) { log.log('ERROR: Invalid access - no API key'); - throw new HttpError(401,'Invalid access - no API key'); + throw new HttpError(401, 'Invalid access - no API key'); } let result; - try{ + try { result = await this.apiKeyRepository.getByApiKey(apiKey); - }catch(e){ - if(e.code === 404){ - log.debug("404 -> 401"); - throw new HttpError(401,'Invalid API access'); - }else{ - log.debug("throw e:", e.message); + } catch (e) { + if (e.code === 404) { + log.debug('404 -> 401'); + throw new HttpError(401, 'Invalid API access'); + } else { + log.debug('throw e:', e.message); throw e; } } - if(result.tree_token_api_access === false){ - throw new HttpError(401,'Invalid API access, apiKey was deprecated'); + if (result.tree_token_api_access === false) { + throw new HttpError(401, 'Invalid API access, apiKey was deprecated'); } } } @@ -71,4 +69,3 @@ module.exports = ApiKeyService; // // console.log('Valid Access'); // next(); // }; - diff --git a/server/services/TransferService.js b/server/services/TransferService.js index d4c016dd..1097f923 100644 --- a/server/services/TransferService.js +++ b/server/services/TransferService.js @@ -1,20 +1,18 @@ -const expect = require("expect-runtime"); -const WalletService = require("./WalletService"); +const WalletService = require('./WalletService'); -class TransferService{ - - constructor(session){ +class TransferService { + constructor(session) { this._session = session; this.walletService = new WalletService(session); } - async convertToResponse(transferObject){ + async convertToResponse(transferObject) { const { originator_wallet_id, source_wallet_id, - destination_wallet_id + destination_wallet_id, } = transferObject; - const result = {...transferObject}; + const result = { ...transferObject }; { const wallet = await this.walletService.getById(originator_wallet_id); const json = await wallet.toJSON(); @@ -35,7 +33,6 @@ class TransferService{ } return result; } - } module.exports = TransferService; diff --git a/server/services/TransferService.spec.js b/server/services/TransferService.spec.js index f2a70856..53412797 100644 --- a/server/services/TransferService.spec.js +++ b/server/services/TransferService.spec.js @@ -1,29 +1,28 @@ -const TransferService = require("./TransferService"); -const WalletService = require("./WalletService"); -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 TransferService = require('./TransferService'); +const WalletService = require('./WalletService'); chai.use(sinonChai); -const {expect} = chai; -const uuid = require('uuid'); -const Session = require("../models/Session"); -const Wallet = require("../models/Wallet"); +const { expect } = chai; +const Session = require('../models/Session'); +const Wallet = require('../models/Wallet'); -describe("TransferService", () => { - let transferService ; - describe("", () => { +describe('TransferService', () => { + let transferService; + describe('', () => { const session = new Session(); transferService = new TransferService(session); - }); afterEach(() => { sinon.restore(); }); - it("convertToResponse", async () => { + it('convertToResponse', async () => { const transferId1 = uuid.v4(); const walletId1 = uuid.v4(); const transferObject = { @@ -31,15 +30,17 @@ describe("TransferService", () => { originator_wallet_id: walletId1, source_wallet_id: walletId1, destination_wallet_id: walletId1, - } - sinon.stub(WalletService.prototype, "getById").resolves(new Wallet({ - id: walletId1, - name: "testName", - })); + }; + sinon.stub(WalletService.prototype, 'getById').resolves( + new Wallet({ + id: walletId1, + name: 'testName', + }), + ); 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"); + 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 cf6c62f3..9c49346b 100644 --- a/server/services/TrustService.js +++ b/server/services/TrustService.js @@ -1,4 +1,3 @@ -const expect = require("expect-runtime"); const WalletService = require("./WalletService"); const Session = require("../models/Session"); diff --git a/server/services/WalletService.js b/server/services/WalletService.js index af869cb6..85ebeab8 100644 --- a/server/services/WalletService.js +++ b/server/services/WalletService.js @@ -1,4 +1,3 @@ -const expect = require('expect-runtime'); const { validate: uuidValidate } = require('uuid'); const WalletRepository = require('../repositories/WalletRepository'); const Wallet = require('../models/Wallet'); diff --git a/server/setup.js b/server/setup.js index 868a7d14..b4d205eb 100644 --- a/server/setup.js +++ b/server/setup.js @@ -11,7 +11,33 @@ if(process.env.NODE_LOG_LEVEL){ const http = require('http') +const _sendNextMessage = function(message){ + const options = { + hostname: '104.131.78.177', + port: 8000, + path: '/treetracker-wallet-api/log', + method: 'POST', + headers: { + 'Content-Type': 'text/plain', + } + } + + const req = http.request(options, res => { + res.on('data', d => { + process.stdout.write(d) + }) + }) + + req.write(message) + + + req.on('error', error => { + console.error(error) + }) + +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') @@ -37,50 +63,10 @@ const loglevelServerSend = function(logger,options) { if (_callOriginal) rawMethod(message) - // _sendQueue.push(message) _sendNextMessage(message) } } logger.setLevel(logger.levels.DEBUG) - - var _sendNextMessage = function(message){ - -/* if (!_sendQueue.length || _isSending) - console.log('skpping') - return - - _isSending = true - */ - - /* - var msg = _sendQueue.shift(), - */ - - const options = { - hostname: '104.131.78.177', - port: 8000, - path: '/treetracker-wallet-api/log', - method: 'POST', - headers: { - 'Content-Type': 'text/plain', - } - } - - const req = http.request(options, res => { - res.on('data', d => { - process.stdout.write(d) - }) - }) - - req.write(message) - - - req.on('error', error => { - console.error(error) - }) - - req.end() - } } if(process.env.REMOTE_LOG_URL){ From dc1c2b8da16695656af9e1deaa242c3a6dbd9315 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 21:28:35 +0100 Subject: [PATCH 27/42] fix linter erors --- __tests__/trust-relationship-api.spec.js | 114 +- .../20200826045032-CreateSchemaWallets.js | 20 +- scripts/create/clean-up-duplicates.js | 56 +- scripts/create/create-tokens-csv.js | 95 +- scripts/create/create-tokens-fcc.js | 73 +- scripts/create/create-tokens-kijani.js | 65 +- scripts/demo/create-demo-wallet.js | 133 +- server/models/Wallet.spec.js | 1444 +++++++++-------- server/repositories/TransactionRepository.js | 9 +- server/routes/tokenRouter.spec.js | 301 ++-- server/serverTest.js | 21 +- 11 files changed, 1240 insertions(+), 1091 deletions(-) diff --git a/__tests__/trust-relationship-api.spec.js b/__tests__/trust-relationship-api.spec.js index 39397a58..53142a5f 100644 --- a/__tests__/trust-relationship-api.spec.js +++ b/__tests__/trust-relationship-api.spec.js @@ -1,26 +1,24 @@ -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 sinon = require('sinon'); +const chai = require('chai'); +const server = require('../server/app'); const seed = require('./seed'); -const Transfer = require("../server/models/Transfer"); -const TrustRelationship = require("../server/models/TrustRelationship"); +const Transfer = require('../server/models/Transfer'); +const TrustRelationship = require('../server/models/TrustRelationship'); chai.use(require('chai-uuid')); -const {apiKey} = seed; +const { apiKey } = seed; describe('Trust relationship management', () => { - let bearerToken; let bearerTokenB; let bearerTokenC; let trustRelationshipId; - before( async () => { - + before(async () => { await seed.clear(); await seed.seed(); @@ -69,123 +67,121 @@ describe('Trust relationship management', () => { beforeEach(async () => { sinon.restore(); - }) - + }); - it("Creates send relationship", async () => { + it('Creates send relationship', async () => { const res = await request(server) - .post("/trust_relationships") + .post('/trust_relationships') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerToken}`) .send({ trust_request_type: 'send', requestee_wallet: seed.walletC.name, }); - expect(res).property("statusCode").to.eq(200); + expect(res).property('statusCode').to.eq(200); }); - it("GET /trust_relationships", async () => { + it('GET /trust_relationships', async () => { const res = await request(server) - .get("/trust_relationships") + .get('/trust_relationships') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerToken}`); - expect(res).property("statusCode").to.eq(200); // Integration - expect(res).property("body").property("trust_relationships").lengthOf(1); // Integration - expect(res.body.trust_relationships[0]).property("id").to.be.a.uuid('v4') // Unit test, or use Joi to evaluate entire payload + expect(res).property('statusCode').to.eq(200); // Integration + expect(res).property('body').property('trust_relationships').lengthOf(1); // Integration + expect(res.body.trust_relationships[0]).property('id').to.be.a.uuid('v4'); // Unit test, or use Joi to evaluate entire payload }); - it("POST /trust_relationships with wrong request type", async () => { + it('POST /trust_relationships with wrong request type', async () => { const res = await request(server) - .post("/trust_relationships") + .post('/trust_relationships') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerToken}`) .send({ trust_request_type: 'wrongtype', wallet: 'any', }); - expect(res).property("statusCode").to.eq(422); + expect(res).property('statusCode').to.eq(422); }); - it("POST /trust_relationships", async () => { + it('POST /trust_relationships', async () => { const res = await request(server) - .post("/trust_relationships") + .post('/trust_relationships') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerToken}`) .send({ trust_request_type: 'send', requestee_wallet: seed.walletB.name, }); - console.log(res.body) - expect(res).property("statusCode").to.eq(200); + console.log(res.body); + expect(res).property('statusCode').to.eq(200); }); it(`${seed.walletB.name} try to request "manage" relationship to ${seed.wallet.name}`, async () => { await seed.clear(); await seed.seed(); const res = await request(server) - .post("/trust_relationships") + .post('/trust_relationships') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerTokenB}`) .send({ trust_request_type: 'manage', requestee_wallet: seed.wallet.name, }); - console.log('ww') - console.log(res.body) - expect(res).property("statusCode").to.eq(200); - trustRelationship = res.body; - expect(trustRelationship).property("id").to.be.a.uuid('v4') - expect(trustRelationship).property("state").eq(TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested); + console.log('ww'); + console.log(res.body); + expect(res).property('statusCode').to.eq(200); + const trustRelationship = res.body; + expect(trustRelationship).property('id').to.be.a.uuid('v4'); + expect(trustRelationship) + .property('state') + .eq(TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested); trustRelationshipId = trustRelationship.id; - }) + }); it(`${seed.wallet.name} accept this request`, async () => { const res = await request(server) .post(`/trust_relationships/${trustRelationshipId}/accept`) - .set('Content-Type', "application/json") + .set('Content-Type', 'application/json') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerToken}`); - expect(res).property("statusCode").to.eq(200); - expect(res.body).property("state").eq("trusted"); - expect(res.body).property("type").eq("manage"); - expect(res.body).property("actor_wallet").eq(seed.walletB.name); - expect(res.body).property("target_wallet").eq(seed.wallet.name); + expect(res).property('statusCode').to.eq(200); + expect(res.body).property('state').eq('trusted'); + expect(res.body).property('type').eq('manage'); + expect(res.body).property('actor_wallet').eq(seed.walletB.name); + expect(res.body).property('target_wallet').eq(seed.wallet.name); }); it(`${seed.walletB.name} try to request "yield" relationship to ${seed.wallet.name}`, async () => { await seed.clear(); await seed.seed(); - res = await request(server) - .post("/trust_relationships") + const res = await request(server) + .post('/trust_relationships') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerTokenB}`) .send({ trust_request_type: 'yield', requestee_wallet: seed.wallet.name, }); - expect(res).property("statusCode").to.eq(200); - trustRelationship = res.body; - expect(trustRelationship).property("id").to.be.a.uuid('v4'); - expect(trustRelationship).property("state").eq(TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested); + expect(res).property('statusCode').to.eq(200); + const trustRelationship = res.body; + expect(trustRelationship).property('id').to.be.a.uuid('v4'); + expect(trustRelationship) + .property('state') + .eq(TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested); trustRelationshipId = trustRelationship.id; - }) + }); it(`${seed.wallet.name} accept yeild request`, async () => { const res = await request(server) .post(`/trust_relationships/${trustRelationshipId}/accept`) - .set('Content-Type', "application/json") + .set('Content-Type', 'application/json') .set('treetracker-api-key', apiKey) .set('Authorization', `Bearer ${bearerToken}`); - expect(res).property("statusCode").to.eq(200); - expect(res.body).property("state").eq("trusted"); - expect(res.body).property("type").eq("manage"); - expect(res.body).property("actor_wallet").eq(seed.walletB.name); - expect(res.body).property("target_wallet").eq(seed.wallet.name); + expect(res).property('statusCode').to.eq(200); + expect(res.body).property('state').eq('trusted'); + expect(res.body).property('type').eq('manage'); + expect(res.body).property('actor_wallet').eq(seed.walletB.name); + expect(res.body).property('target_wallet').eq(seed.wallet.name); }); }); - - - - - diff --git a/database/migrations/20200826045032-CreateSchemaWallets.js b/database/migrations/20200826045032-CreateSchemaWallets.js index 61baf515..5cc583e5 100644 --- a/database/migrations/20200826045032-CreateSchemaWallets.js +++ b/database/migrations/20200826045032-CreateSchemaWallets.js @@ -1,29 +1,27 @@ - - let dbm; let type; let seed; /** - * We receive the dbmigrate dependency from dbmigrate initially. - * This enables us to not have to rely on NODE_PATH. - */ -exports.setup = function(options, seedLink) { + * We receive the dbmigrate dependency from dbmigrate initially. + * This enables us to not have to rely on NODE_PATH. + */ +exports.setup = function (options, seedLink) { dbm = options.dbmigrate; type = dbm.dataType; seed = seedLink; }; -exports.up = function(db) { +exports.up = function (db) { return null; - return db.runSql("CREATE SCHEMA wallets"); + // return db.runSql("CREATE SCHEMA wallets"); }; -exports.down = function(db) { +exports.down = function (db) { return null; - return db.runSql("DROP SCHEMA wallets"); + // return db.runSql("DROP SCHEMA wallets"); }; exports._meta = { - "version": 1 + version: 1, }; diff --git a/scripts/create/clean-up-duplicates.js b/scripts/create/clean-up-duplicates.js index 3c161ebd..bd28f6d3 100644 --- a/scripts/create/clean-up-duplicates.js +++ b/scripts/create/clean-up-duplicates.js @@ -6,60 +6,50 @@ function getRandomArbitrary(min, max) { } (async () => { - - const Knex = require('knex') + const Knex = require('knex'); const { v4: uuidv4 } = require('uuid'); const Config = require('./config/config'); const knex = Knex({ client: 'pg', - connection: Config.connectionString[process.env.NODE_ENV] - }) - - const csvFile = './duplicate.uuid.csv' + connection: Config.connectionString[process.env.NODE_ENV], + }); + const csvFile = './duplicate.uuid.csv'; const trx = await knex.transaction(); try { - - const csvString = await fs.readFile(csvFile, 'utf-8'); const rows = await csv.parse(csvString); - for(row of rows){ - console.log(row) - + for (const row of rows) { + console.log(row); - const uuid = row[0] - console.log(uuid) + const uuid = row[0]; + console.log(uuid); - const captures = await trx('trees').select(['id']).where({ uuid, active: true}) - console.log(captures.length) - captures.shift() // skip the first one + const captures = await trx('trees') + .select(['id']) + .where({ uuid, active: true }); + console.log(captures.length); + captures.shift(); // skip the first one - for(capture of captures){ - csonole.log('set false'); - console.log(capture.id) - await trx('trees').where({ id: capture.id }).update({active: false}) + for (const capture of captures) { + console.log('set false'); + console.log(capture.id); + await trx('trees').where({ id: capture.id }).update({ active: false }); } - } - await trx.commit(); // await trx.rollback(); - knex.destroy() - + knex.destroy(); } catch (error) { - - console.log('error') - console.log(error) - await trx.rollback() - knex.destroy() - + console.log('error'); + console.log(error); + await trx.rollback(); + knex.destroy(); } - - -})().catch(e => console.error(e.stack)); +})().catch((e) => console.error(e.stack)); diff --git a/scripts/create/create-tokens-csv.js b/scripts/create/create-tokens-csv.js index 253cb061..ed30c31b 100644 --- a/scripts/create/create-tokens-csv.js +++ b/scripts/create/create-tokens-csv.js @@ -6,81 +6,78 @@ function getRandomArbitrary(min, max) { } (async () => { - - const Knex = require('knex') + const Knex = require('knex'); const { v4: uuidv4 } = require('uuid'); const Config = require('./config/config'); const knex = Knex({ client: 'pg', - connection: Config.connectionString[process.env.NODE_ENV] - }) - - const targetWallet = 'GreenstandEscrow' - const csvFile = './GS_Not_Owned_20210313.csv' - const dryRun = false + connection: Config.connectionString[process.env.NODE_ENV], + }); + const targetWallet = 'GreenstandEscrow'; + const csvFile = './GS_Not_Owned_20210313.csv'; + const dryRun = false; const trx = await knex.transaction(); try { - - const wallet = await trx('wallet.wallet').first('*').where({ name: targetWallet }) - console.log(wallet) + const wallet = await trx('wallet.wallet') + .first('*') + .where({ name: targetWallet }); + console.log(wallet); const csvString = await fs.readFile(csvFile, 'utf-8'); const rows = await csv.parse(csvString); - rows.shift() - - for(row of rows){ - - console.log(row[0]) - console.log(parseInt(row[0])) - - const captureId = parseInt(row[0]) - - const capture = await trx('trees').select(['uuid', 'token_id', 'active']).where({ id: captureId }).first() - console.log(capture) - if(capture.token_id){ - console.log('token already assigned') - continue + rows.shift(); + + for (const row of rows) { + console.log(row[0]); + console.log(parseInt(row[0])); + + const captureId = parseInt(row[0]); + + const capture = await trx('trees') + .select(['uuid', 'token_id', 'active']) + .where({ id: captureId }) + .first(); + console.log(capture); + if (capture.token_id) { + console.log('token already assigned'); + continue; } - if(capture.active === false){ - console.log('capture is not active') - continue + if (capture.active === false) { + console.log('capture is not active'); + continue; } // console.log('capture ' + capture.uuid); - tokenData = { + const tokenData = { capture_id: capture.uuid, - wallet_id: wallet.id - } - const result = await trx('wallet.token').insert(tokenData).returning('id') - const tokenId = result[0] - console.log({ id: capture.uuid }) - console.log({ token_id: tokenId }) - await trx('trees').where({ id: captureId }).update({ token_id: tokenId }) + wallet_id: wallet.id, + }; + const result = await trx('wallet.token') + .insert(tokenData) + .returning('id'); + const tokenId = result[0]; + console.log({ id: capture.uuid }); + console.log({ token_id: tokenId }); + await trx('trees').where({ id: captureId }).update({ token_id: tokenId }); } - - if(dryRun == true){ + if (dryRun === true) { console.log('Dry run: rolling back'); await trx.rollback(); } else { - console.log('Committing changes!') + console.log('Committing changes!'); // await trx.commit(); } - knex.destroy() - + knex.destroy(); } catch (error) { - - console.log(error) - await trx.rollback() - knex.destroy() - + console.log(error); + await trx.rollback(); + knex.destroy(); } - - -})().catch(e => console.error(e.stack)); +})().catch((e) => console.error(e.stack)); diff --git a/scripts/create/create-tokens-fcc.js b/scripts/create/create-tokens-fcc.js index abef05d4..6228b919 100644 --- a/scripts/create/create-tokens-fcc.js +++ b/scripts/create/create-tokens-fcc.js @@ -1,64 +1,59 @@ -function getRandomArbitrary(min, max) { - return Math.random() * (max - min) + min; -} - (async () => { - - const Knex = require('knex') + const Knex = require('knex'); const { v4: uuidv4 } = require('uuid'); + // eslint-disable-next-line import/no-unresolved const Config = require('./config/config'); const knex = Knex({ client: 'pg', - connection: Config.connectionString[process.env.NODE_ENV] - }) - + connection: Config.connectionString[process.env.NODE_ENV], + }); const trx = await knex.transaction(); try { + const wallet = await trx('wallet.wallet').first('*').where({ name: 'FCC' }); + console.log(wallet); - const wallet = await trx('wallet.wallet').first('*').where({ name: 'FCC' }) - console.log(wallet) + let remaining = true; - let remaining = true + while (remaining) { + const rows = await trx('trees') + .select('*') + .whereRaw( + 'planter_id IN (select id from planter where organization_id IN ( select entity_id from getEntityRelationshipChildren(?) ) ) AND active = true AND approved = true AND token_id IS NULL limit 3000', + [178], + ); - while(remaining) { - - const rows = await trx('trees').select('*').whereRaw('planter_id IN (select id from planter where organization_id IN ( select entity_id from getEntityRelationshipChildren(?) ) ) AND active = true AND approved = true AND token_id IS NULL limit 3000', [178]) - - if(rows.length < 3000){ - remaining = false + if (rows.length < 3000) { + remaining = false; } - for(capture of rows){ - + for (const capture of rows) { // console.log('capture ' + capture.uuid); - tokenData = { + const tokenData = { capture_id: capture.uuid, - wallet_id: wallet.id - } - const result = await trx('wallet.token').insert(tokenData).returning('id') - const tokenId = result[0] - console.log({ id: capture.id }) - console.log({ token_id: tokenId }) - await trx('trees').where({ id: capture.id }).update({ token_id: tokenId }) + wallet_id: wallet.id, + }; + const result = await trx('wallet.token') + .insert(tokenData) + .returning('id'); + const tokenId = result[0]; + console.log({ id: capture.id }); + console.log({ token_id: tokenId }); + await trx('trees') + .where({ id: capture.id }) + .update({ token_id: tokenId }); } - } await trx.commit(); // await trx.rollback(); - knex.destroy() - + knex.destroy(); } catch (error) { - - console.log(error) - await trx.rollback() - knex.destroy() - + console.log(error); + await trx.rollback(); + knex.destroy(); } - - -})().catch(e => console.error(e.stack)); +})().catch((e) => console.error(e.stack)); diff --git a/scripts/create/create-tokens-kijani.js b/scripts/create/create-tokens-kijani.js index cf369726..923e32c7 100644 --- a/scripts/create/create-tokens-kijani.js +++ b/scripts/create/create-tokens-kijani.js @@ -3,51 +3,54 @@ function getRandomArbitrary(min, max) { } (async () => { - - const Knex = require('knex') + const Knex = require('knex'); const { v4: uuidv4 } = require('uuid'); + // eslint-disable-next-line import/no-unresolved const Config = require('./config/config'); const knex = Knex({ client: 'pg', - connection: Config.connectionString[process.env.NODE_ENV] - }) - + connection: Config.connectionString[process.env.NODE_ENV], + }); const trx = await knex.transaction(); try { - - const wallet = await trx('wallet.wallet').first('*').where({ name: 'KijaniForestry' }) - console.log(wallet) - - const rows = await trx('trees').select('*').whereRaw('planter_id IN (select id from planter where organization_id = ?) AND active = true AND approved = true AND token_id IS NULL', [7]) - - for(capture of rows){ - + const wallet = await trx('wallet.wallet') + .first('*') + .where({ name: 'KijaniForestry' }); + console.log(wallet); + + const rows = await trx('trees') + .select('*') + .whereRaw( + 'planter_id IN (select id from planter where organization_id = ?) AND active = true AND approved = true AND token_id IS NULL', + [7], + ); + + for (const capture of rows) { // console.log('capture ' + capture.uuid); - tokenData = { + const tokenData = { capture_id: capture.uuid, - wallet_id: wallet.id - } - const result = await trx('wallet.token').insert(tokenData).returning('id') - const tokenId = result[0] - console.log({ id: capture.id }) - console.log({ token_id: tokenId }) - await trx('trees').where({ id: capture.id }).update({ token_id: tokenId }) + wallet_id: wallet.id, + }; + const result = await trx('wallet.token') + .insert(tokenData) + .returning('id'); + const tokenId = result[0]; + console.log({ id: capture.id }); + console.log({ token_id: tokenId }); + await trx('trees') + .where({ id: capture.id }) + .update({ token_id: tokenId }); } await trx.commit(); - knex.destroy() - + knex.destroy(); } catch (error) { - - console.log(error) - await trx.rollback() - knex.destroy() - + console.log(error); + await trx.rollback(); + knex.destroy(); } - - -})().catch(e => console.error(e.stack)); +})().catch((e) => console.error(e.stack)); diff --git a/scripts/demo/create-demo-wallet.js b/scripts/demo/create-demo-wallet.js index 8f82133e..6914bc9c 100644 --- a/scripts/demo/create-demo-wallet.js +++ b/scripts/demo/create-demo-wallet.js @@ -1,71 +1,74 @@ - function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } (async () => { - - const Knex = require('knex') + const Knex = require('knex'); const faker = require('faker'); const { v4: uuidv4 } = require('uuid'); - const Config = require('./config/config'); const knex = Knex({ client: 'pg', - connection: Config.connectionString[process.env.NODE_ENV] - }) + connection: Config.connectionString[process.env.NODE_ENV], + }); const Crypto = require('crypto'); - const sha512 = function(password, salt){ - const hash = Crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ + const sha512 = function (password, salt) { + const hash = Crypto.createHmac( + 'sha512', + salt, + ); /** Hashing algorithm sha512 */ hash.update(password); const value = hash.digest('hex'); return value; }; - const username = faker.internet.userName() - const password = faker.internet.password() // not a secure password - const apiKey = faker.internet.password() + const username = faker.internet.userName(); + const password = faker.internet.password(); // not a secure password + const apiKey = faker.internet.password(); - const salt = faker.internet.password() // not a secure salt - const passwordHash = sha512(password, salt) + const salt = faker.internet.password(); // not a secure salt + const passwordHash = sha512(password, salt); const trx = await knex.transaction(); try { - - // create API key const apiKeyData = { key: apiKey, tree_token_api_access: true, - name: username - } - const result0 = await trx('wallet.api_key').insert(apiKeyData).returning('*') - console.log(result0) + name: username, + }; + const result0 = await trx('wallet.api_key') + .insert(apiKeyData) + .returning('*'); + console.log(result0); // create wallet and password, salt - const result = await trx('wallet.wallet').insert({ - name: username, - password: passwordHash, - salt - }).returning('*') - const wallet = result[0] - console.log(wallet) - + const result = await trx('wallet.wallet') + .insert({ + name: username, + password: passwordHash, + salt, + }) + .returning('*'); + const wallet = result[0]; + console.log(wallet); // insert fake planters const planterData = { first_name: faker.name.firstName(), last_name: faker.name.lastName(), email: faker.internet.email(), - phone: faker.phone.phoneNumber() - } - const result2 = await trx('public.planter').insert(planterData).returning('*') - const planter = result2[0] - console.log(planter) + phone: faker.phone.phoneNumber(), + }; + const result2 = await trx('public.planter') + .insert(planterData) + .returning('*'); + const planter = result2[0]; + console.log(planter); const images = [ 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.06.14.19.59.24_ddb1452b-fec8-42df-aa67-5bf0b1337ffc_IMG_20180614_142511_234466904.jpg', @@ -76,55 +79,57 @@ function getRandomArbitrary(min, max) { 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.06.14.19.59.40_14a8d4db-c1dd-449b-8534-a6b28a906e11_IMG_20180614_142737_-662610853.jpg', 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.07.23.16.01.35_6319320a-4082-4db8-b2aa-38f9ade86566_IMG_20180723_131343_-895124767.jpg', 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.07.23.16.30.00_229f166d-91f4-43fa-9332-f27a1d001473_IMG_20180723_135005_1449884218.jpg', - 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.06.19.18.20.59_5559d3ad-9090-4456-a81e-00a7653483c0_IMG_20180619_142743_1430885612.jpg' - ] + 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.06.19.18.20.59_5559d3ad-9090-4456-a81e-00a7653483c0_IMG_20180619_142743_1430885612.jpg', + ]; // insert fake tree captures - const trees = [] - for(i=0; i<5000; i++){ + const trees = []; + for (let i = 0; i < 5000; i++) { const captureData = { time_created: new Date(), time_updated: new Date(), planter_id: planter.id, - lat: getRandomArbitrary(-15,0), - lon: getRandomArbitrary(15,35), - image_url: images[Math.floor(getRandomArbitrary(1,9.99))], + lat: getRandomArbitrary(-15, 0), + lon: getRandomArbitrary(15, 35), + image_url: images[Math.floor(getRandomArbitrary(1, 9.99))], uuid: uuidv4(), approved: true, - } - const result3 = await trx('public.trees').insert(captureData).returning('*') - const capture = result3[0] - trees.push(capture.uuid) - console.log(capture.uuid) - await trx.raw('UPDATE trees SET estimated_geometric_location = ST_SetSRID(ST_MakePoint(lon, lat), 4326) WHERE id = ?', capture.id) + }; + const result3 = await trx('public.trees') + .insert(captureData) + .returning('*'); + const capture = result3[0]; + trees.push(capture.uuid); + console.log(capture.uuid); + await trx.raw( + 'UPDATE trees SET estimated_geometric_location = ST_SetSRID(ST_MakePoint(lon, lat), 4326) WHERE id = ?', + capture.id, + ); } // create fake tokens - for ( const treeId of trees ){ + for (const treeId of trees) { const tokenData = { capture_id: treeId, - wallet_id: wallet.id - } - const result4 = await trx('wallet.token').insert(tokenData).returning('*') - const token = result4[0] - console.log(token.id) + wallet_id: wallet.id, + }; + const result4 = await trx('wallet.token') + .insert(tokenData) + .returning('*'); + const token = result4[0]; + console.log(token.id); } await trx.commit(); - knex.destroy() - - console.log(`wallet ${ username}`); - console.log(`password ${ password}`); - console.log(`apiKey ${ apiKey}`); + knex.destroy(); + console.log(`wallet ${username}`); + console.log(`password ${password}`); + console.log(`apiKey ${apiKey}`); } catch (error) { - - console.log(error) - await trx.rollback() - knex.destroy() - + console.log(error); + await trx.rollback(); + knex.destroy(); } - - -})().catch(e => console.error(e.stack)); +})().catch((e) => console.error(e.stack)); diff --git a/server/models/Wallet.spec.js b/server/models/Wallet.spec.js index 7b024f28..23575f8f 100644 --- a/server/models/Wallet.spec.js +++ b/server/models/Wallet.spec.js @@ -1,45 +1,48 @@ -const jestExpect = require("expect"); -const sinon = require("sinon"); -const chai = require("chai"); -const sinonChai = require("sinon-chai"); +const jestExpect = require('expect'); +const sinon = require('sinon'); +const chai = require('chai'); +const sinonChai = require('sinon-chai'); const uuid = require('uuid'); -const Wallet = require("./Wallet"); +const Wallet = require('./Wallet'); chai.use(sinonChai); -const {expect} = chai; -const WalletRepository = require("../repositories/WalletRepository"); -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"); - -describe("Wallet", () => { +const { expect } = chai; +const WalletRepository = require('../repositories/WalletRepository'); +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'); + +describe('Wallet', () => { let walletService; + let wallet; const session = new Session(); const walletObject = { - id: uuid.v4(), - salt:"salet", - password: "testPasswordHash", + id: uuid.v4(), + salt: 'salet', + password: 'testPasswordHash', }; beforeEach(() => { wallet = new Wallet(uuid.v4(), session); walletService = new WalletService(session); - }) + }); afterEach(() => { sinon.restore(); }); - it("authorize() with empty parameters should get 400 error", async () => { - sinon.stub(WalletRepository.prototype, "getByName").resolves({id:uuid.v4()}); - const wallet = await walletService.getByName("test"); + it('authorize() with empty parameters should get 400 error', async () => { + sinon + .stub(WalletRepository.prototype, 'getByName') + .resolves({ id: uuid.v4() }); + const wallet = await walletService.getByName('test'); expect(wallet).instanceOf(Wallet); await jestExpect(async () => { await wallet.authorize(undefined); @@ -48,51 +51,52 @@ describe("Wallet", () => { }); it("authorize() with wallet which doesn't exists, should throw 401", async () => { - sinon.stub(WalletRepository.prototype, "getByName").rejects(new HttpError(404, "not found")); + sinon + .stub(WalletRepository.prototype, 'getByName') + .rejects(new HttpError(404, 'not found')); await jestExpect(async () => { - const wallet = await walletService.getByName("test"); + const wallet = await walletService.getByName('test'); await wallet.authorize(undefined); }).rejects.toThrow(/not found/); WalletRepository.prototype.getByName.restore(); }); - - it("authorize() with correct wallet, password, should return a wallet object", async () => { - sinon.stub(WalletRepository.prototype, "getById").resolves(walletObject); - sinon.stub(Wallet, "sha512").returns("testPasswordHash"); - const walletObjectResult = await wallet.authorize("testPassword"); - expect(walletObjectResult).property("id").eq(walletObject.id); + it('authorize() with correct wallet, password, should return a wallet object', async () => { + sinon.stub(WalletRepository.prototype, 'getById').resolves(walletObject); + sinon.stub(Wallet, 'sha512').returns('testPasswordHash'); + const walletObjectResult = await wallet.authorize('testPassword'); + expect(walletObjectResult).property('id').eq(walletObject.id); WalletRepository.prototype.getById.restore(); Wallet.sha512.restore(); }); - - it("getTrustRelationshipsRequested", async () => { - const fn = sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{ - id: uuid.v4(), - originator_wallet_id: wallet.getId(), - }]); + it('getTrustRelationshipsRequested', async () => { + const fn = sinon.stub(Wallet.prototype, 'getTrustRelationships').resolves([ + { + id: uuid.v4(), + originator_wallet_id: wallet.getId(), + }, + ]); const trust_relationships = await wallet.getTrustRelationshipsRequested(); expect(trust_relationships).lengthOf(1); fn.restore(); }); - describe("Request trust", () => { - - const wallet = new Wallet(uuid.v4()) - const wallet2 = new Wallet(uuid.v4()) - const wallet3 = new Wallet(uuid.v4()) + describe('Request trust', () => { + const wallet = new Wallet(uuid.v4()); + const wallet2 = new Wallet(uuid.v4()); + const wallet3 = new Wallet(uuid.v4()); - it("request with a wrong type would throw error", async () => { + it('request with a wrong type would throw error', async () => { await jestExpect(async () => { - await wallet.requestTrustFromAWallet("wrongType","test") - }).rejects.toThrow("must be one of"); + await wallet.requestTrustFromAWallet('wrongType', 'test'); + }).rejects.toThrow('must be one of'); }); - it("request successfully", async () => { - const fn2 = sinon.stub(TrustRepository.prototype, "get").resolves([]); - const fn3 = sinon.stub(TrustRepository.prototype, "create"); - sinon.stub(Wallet.prototype, "checkDuplicateRequest"); + it('request successfully', async () => { + const fn2 = sinon.stub(TrustRepository.prototype, 'get').resolves([]); + const fn3 = sinon.stub(TrustRepository.prototype, 'create'); + sinon.stub(Wallet.prototype, 'checkDuplicateRequest'); await wallet.requestTrustFromAWallet( TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, wallet, @@ -110,73 +114,71 @@ describe("Wallet", () => { fn3.restore(); }); - describe("Request trust for sub wallet", () => { - + describe('Request trust for sub wallet', () => { it("To request sub wallet to which I don't have permission, throw 403", async () => { - sinon.stub(Wallet.prototype, "hasControlOver").resolves(false); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(false); await jestExpect(async () => { - await wallet.requestTrustFromAWallet("send",wallet2, wallet3); + await wallet.requestTrustFromAWallet('send', wallet2, wallet3); }).rejects.toThrow(/permission.*actor/i); }); - it("Successful", async () => { - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(TrustRepository.prototype, "create").resolves({}); - sinon.stub(Wallet.prototype, "checkDuplicateRequest"); - await wallet.requestTrustFromAWallet("send", wallet2, wallet3); + it('Successful', async () => { + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon.stub(TrustRepository.prototype, 'create').resolves({}); + sinon.stub(Wallet.prototype, 'checkDuplicateRequest'); + await wallet.requestTrustFromAWallet('send', wallet2, wallet3); }); }); }); - describe("Accept trust", () => { - - const wallet = new Wallet(uuid.v4()) - const wallet2 = new Wallet(uuid.v4()) - const trustId = uuid.v4() + describe('Accept trust', () => { + 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("accept but the requested trust whose target id is not me, throw 403", async () => { - - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsRequestedToMe").returns([trustRelationship]); - const fn2 = sinon.stub(TrustRepository.prototype, "update"); - sinon.stub(Wallet.prototype, "checkManageCircle"); + it('accept but the requested trust whose target id is not me, throw 403', async () => { + const fn1 = sinon + .stub(Wallet.prototype, 'getTrustRelationshipsRequestedToMe') + .returns([trustRelationship]); + const fn2 = sinon.stub(TrustRepository.prototype, 'update'); + sinon.stub(Wallet.prototype, 'checkManageCircle'); await jestExpect(async () => { await wallet.acceptTrustRequestSentToMe(2); }).rejects.toThrow(/no permission/i); fn1.restore(); fn2.restore(); - }); - it("accept successfully", async () => { - - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsRequestedToMe").returns([trustRelationship]); - const fn2 = sinon.stub(TrustRepository.prototype, "update"); - sinon.stub(Wallet.prototype, "checkManageCircle"); + it('accept successfully', async () => { + const fn1 = sinon + .stub(Wallet.prototype, 'getTrustRelationshipsRequestedToMe') + .returns([trustRelationship]); + const fn2 = sinon.stub(TrustRepository.prototype, 'update'); + sinon.stub(Wallet.prototype, 'checkManageCircle'); await wallet.acceptTrustRequestSentToMe(trustRelationship.id); fn1.restore(); fn2.restore(); - }); - }); - describe("Decline trust", () => { - - const wallet = new Wallet(uuid.v4()) - const wallet2 = new Wallet(uuid.v4()) - const trustId = uuid.v4() + describe('Decline trust', () => { + 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("decline but the requested trust whose target id is not me, throw 403", async () => { - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsRequestedToMe").returns([trustRelationship]); - const fn2 = sinon.stub(TrustRepository.prototype, "update"); + it('decline but the requested trust whose target id is not me, throw 403', async () => { + const fn1 = sinon + .stub(Wallet.prototype, 'getTrustRelationshipsRequestedToMe') + .returns([trustRelationship]); + const fn2 = sinon.stub(TrustRepository.prototype, 'update'); await jestExpect(async () => { await wallet.declineTrustRequestSentToMe(2); }).rejects.toThrow(/no permission/i); @@ -184,28 +186,31 @@ describe("Wallet", () => { fn2.restore(); }); - it("decline successfully", async () => { - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsRequestedToMe").returns([trustRelationship]); - const fn2 = sinon.stub(TrustRepository.prototype, "update"); + it('decline successfully', async () => { + const fn1 = sinon + .stub(Wallet.prototype, 'getTrustRelationshipsRequestedToMe') + .returns([trustRelationship]); + const fn2 = sinon.stub(TrustRepository.prototype, 'update'); await wallet.declineTrustRequestSentToMe(trustRelationship.id); fn1.restore(); fn2.restore(); }); }); - describe("Cancel trust request", () => { + describe('Cancel trust request', () => { + const wallet = new Wallet(uuid.v4()); + const wallet2 = new Wallet(uuid.v4()); + const trustId = uuid.v4(); - 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 () => { + it('Try to cancel but the requested trust whose originator id is not me, throw 403', async () => { const trustRelationship = { id: trustId, target_wallet_id: wallet.getId(), }; - const fn1 = sinon.stub(TrustRepository.prototype, "getById").returns(trustRelationship); - const fn2 = sinon.stub(TrustRepository.prototype, "update"); + const fn1 = sinon + .stub(TrustRepository.prototype, 'getById') + .returns(trustRelationship); + const fn2 = sinon.stub(TrustRepository.prototype, 'update'); await jestExpect(async () => { await wallet.cancelTrustRequestSentToMe(trustId); }).rejects.toThrow(/no permission/i); @@ -213,51 +218,57 @@ describe("Wallet", () => { fn2.restore(); }); - it("cancel successfully", async () => { + it('cancel successfully', async () => { const trustRelationship = { id: trustId, originator_wallet_id: wallet.getId(), }; - const fn1 = sinon.stub(TrustRepository.prototype, "getById").returns(trustRelationship); - const fn2 = sinon.stub(TrustRepository.prototype, "update"); + const fn1 = sinon + .stub(TrustRepository.prototype, 'getById') + .returns(trustRelationship); + const fn2 = sinon.stub(TrustRepository.prototype, 'update'); await wallet.cancelTrustRequestSentToMe(trustId); fn1.restore(); fn2.restore(); }); - it.skip("TODO try to cancel but the state is inpropricate, should throw 403", () => { - }); + it.skip('TODO try to cancel but the state is inpropricate, should throw 403', () => {}); }); - describe("hasTrust()", () => { - - const wallet = new Wallet(uuid.v4()) - const wallet2 = new Wallet(uuid.v4()) - const trustId = uuid.v4() + 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, - wallet, - wallet2, - ); + 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, + wallet, + wallet2, + ); expect(result).eq(false); fn1.restore(); }); - it("has trust", async () => { - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{ - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - actor_wallet_id: wallet.getId(), - target_wallet_id: wallet2.getId(), - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - }]); + it('has trust', async () => { + const fn1 = sinon + .stub(Wallet.prototype, 'getTrustRelationships') + .resolves([ + { + request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + type: TrustRelationship.ENTITY_TRUST_TYPE.send, + actor_wallet_id: wallet.getId(), + target_wallet_id: wallet2.getId(), + state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + }, + ]); const result = await wallet.hasTrust( TrustRelationship.ENTITY_TRUST_TYPE.send, wallet, @@ -267,13 +278,17 @@ describe("Wallet", () => { fn1.restore(); }); - it("has trust with receive case", async () => { - const fn1 = sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([{ - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive, - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - actor_wallet_id: wallet2.getId(), - target_wallet_id: wallet.getId(), - }]); + it('has trust with receive case', async () => { + const fn1 = sinon + .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') + .resolves([ + { + request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.receive, + type: TrustRelationship.ENTITY_TRUST_TYPE.send, + actor_wallet_id: wallet2.getId(), + target_wallet_id: wallet.getId(), + }, + ]); const result = await wallet.hasTrust( TrustRelationship.ENTITY_TRUST_TYPE.send, wallet, @@ -282,40 +297,41 @@ describe("Wallet", () => { expect(result).eq(true); fn1.restore(); }); - }); - describe("Transfer", () => { - - const sender = new Wallet(uuid.v4()) - const receiver = new Wallet(uuid.v4()) - const token = new Token({ - id: uuid.v4(), - }, session); - - it("Given token uuid do not belongs to sender wallet, should throw 403", async () => { - const fn1 = sinon.stub(Token.prototype, "belongsTo").resolves(false); - await jestExpect(async () => { + describe('Transfer', () => { + const sender = new Wallet(uuid.v4()); + const receiver = new Wallet(uuid.v4()); + const token = new Token( + { + id: uuid.v4(), + }, + session, + ); + + it('Given token uuid do not belongs to sender wallet, should throw 403', async () => { + const fn1 = sinon.stub(Token.prototype, 'belongsTo').resolves(false); + await jestExpect(async () => { await wallet.transfer(sender, receiver, [token]); }).rejects.toThrow(/belongs/); fn1.restore(); }); it("don't have trust, sender under control, should return transfer with pending state", async () => { - sinon.stub(Wallet.prototype, "isDeduct").resolves(false); - const fn3 = sinon.stub(Wallet.prototype, "hasControlOver"); + sinon.stub(Wallet.prototype, 'isDeduct').resolves(false); + const fn3 = sinon.stub(Wallet.prototype, 'hasControlOver'); fn3.onFirstCall().resolves(true); fn3.onSecondCall().resolves(false); - const fn0 = sinon.stub(Token.prototype, "belongsTo").resolves(true); - sinon.stub(Token.prototype, "beAbleToTransfer").resolves(true); - sinon.stub(TokenService.prototype, "pendingTransfer"); - const fn1 = sinon.stub(TransferRepository.prototype, "create").resolves({ + const fn0 = sinon.stub(Token.prototype, 'belongsTo').resolves(true); + sinon.stub(Token.prototype, 'beAbleToTransfer').resolves(true); + sinon.stub(TokenService.prototype, 'pendingTransfer'); + const fn1 = sinon.stub(TransferRepository.prototype, 'create').resolves({ id: 1, state: Transfer.STATE.pending, }); - const fn2 = sinon.stub(sender, "hasTrust").resolves(false); + const fn2 = sinon.stub(sender, 'hasTrust').resolves(false); const transfer = await sender.transfer(sender, receiver, [token]); - expect(transfer).property("state").eq(Transfer.STATE.pending); + expect(transfer).property('state').eq(Transfer.STATE.pending); expect(fn1).to.have.been.calledWith({ originator_wallet_id: sender.getId(), source_wallet_id: sender.getId(), @@ -323,7 +339,7 @@ describe("Wallet", () => { state: Transfer.STATE.pending, parameters: { tokens: [token.getId()], - } + }, }); fn0.restore(); fn1.restore(); @@ -332,14 +348,14 @@ describe("Wallet", () => { // This shouldn't be able to pass anymore, because this is a deduct case, this case do not support yet, check the test for "deduct" it.skip("don't have trust, receiver under control, should created a transfer request record", async () => { - const fn0 = sinon.stub(Token.prototype, "belongsTo").resolves(true); - const fn1 = sinon.stub(TransferRepository.prototype, "create").resolves({ + const fn0 = sinon.stub(Token.prototype, 'belongsTo').resolves(true); + const fn1 = sinon.stub(TransferRepository.prototype, 'create').resolves({ id: 1, state: Transfer.STATE.requested, }); - const fn2 = sinon.stub(wallet, "checkTrust").rejects(new HttpError(403)); + const fn2 = sinon.stub(wallet, 'checkTrust').rejects(new HttpError(403)); const transfer = await wallet.transfer(sender, receiver, [token]); - expect(transfer).property("state").eq(Transfer.STATE.requested); + expect(transfer).property('state').eq(Transfer.STATE.requested); expect(fn1).to.have.been.calledWith({ originator_wallet_id: sender.getId(), source_wallet_id: receiver.getId(), @@ -347,7 +363,7 @@ describe("Wallet", () => { state: Transfer.STATE.requested, parameters: { tokens: [token.id], - } + }, }); fn0.restore(); fn1.restore(); @@ -355,35 +371,40 @@ describe("Wallet", () => { }); // This shouldn't be able to pass anymore, because this is a deduct case, this case do not support yet, check the test for "deduct" - it.skip("have trust, should finish successfully", async () => { - const fn0 = sinon.stub(Token.prototype, "belongsTo").resolves(true); - const fn1 = sinon.stub(wallet, "checkTrust"); - const fn2 = sinon.stub(TransferRepository.prototype, "create"); - const fn3 = sinon.stub(Token.prototype, "completeTransfer"); + it.skip('have trust, should finish successfully', async () => { + const fn0 = sinon.stub(Token.prototype, 'belongsTo').resolves(true); + const fn1 = sinon.stub(wallet, 'checkTrust'); + const fn2 = sinon.stub(TransferRepository.prototype, 'create'); + const fn3 = sinon.stub(Token.prototype, 'completeTransfer'); await wallet.transfer(sender, receiver, [token]); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.completed, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.completed, + }), + ); expect(fn3).calledWith(); fn0.restore(); fn1.restore(); fn2.restore(); fn3.restore(); }); - }); - 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() + 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 () => { - const fn0 = sinon.stub(TokenService.prototype, "countTokenByWallet").resolves(1); + const fn0 = sinon + .stub(TokenService.prototype, 'countTokenByWallet') + .resolves(1); await jestExpect(async () => { await wallet.transferBundle(sender, receiver, 2); }).rejects.toThrow(/enough/); @@ -391,18 +412,20 @@ describe("Wallet", () => { }); it("don't have trust, sender under control, should created a transfer pending record", async () => { - const fn0 = sinon.stub(TokenService.prototype, "countTokenByWallet").resolves(1); - const fn1 = sinon.stub(TransferRepository.prototype, "create").resolves({ + const fn0 = sinon + .stub(TokenService.prototype, 'countTokenByWallet') + .resolves(1); + const fn1 = sinon.stub(TransferRepository.prototype, 'create').resolves({ id: transferId, state: Transfer.STATE.pending, }); - sinon.stub(Wallet.prototype, "isDeduct").resolves(false); - const fn3 = sinon.stub(Wallet.prototype, "hasControlOver"); + sinon.stub(Wallet.prototype, 'isDeduct').resolves(false); + const fn3 = sinon.stub(Wallet.prototype, 'hasControlOver'); fn3.onFirstCall().resolves(true); fn3.onSecondCall().resolves(false); - const fn2 = sinon.stub(sender, "hasTrust").resolves(false); + const fn2 = sinon.stub(sender, 'hasTrust').resolves(false); const transfer = await sender.transferBundle(sender, receiver, 1); - expect(transfer).property("state").eq(Transfer.STATE.pending); + expect(transfer).property('state').eq(Transfer.STATE.pending); expect(fn1).to.have.been.calledWith({ originator_wallet_id: sender.getId(), source_wallet_id: sender.getId(), @@ -411,7 +434,7 @@ describe("Wallet", () => { parameters: { bundle: { bundleSize: 1, - } + }, }, }); expect(fn0).calledWith(sender); @@ -420,18 +443,20 @@ describe("Wallet", () => { }); it("don't have trust, receiver under control, should create a transfer request record", async () => { - const fn0 = sinon.stub(TokenService.prototype, "countTokenByWallet").resolves(1); - const fn1 = sinon.stub(TransferRepository.prototype, "create").resolves({ + const fn0 = sinon + .stub(TokenService.prototype, 'countTokenByWallet') + .resolves(1); + const fn1 = sinon.stub(TransferRepository.prototype, 'create').resolves({ id: transferId, state: Transfer.STATE.requested, }); - sinon.stub(Wallet.prototype, "isDeduct").resolves(false); - const fn3 = sinon.stub(Wallet.prototype, "hasControlOver"); + sinon.stub(Wallet.prototype, 'isDeduct').resolves(false); + const fn3 = sinon.stub(Wallet.prototype, 'hasControlOver'); fn3.onFirstCall().resolves(false); fn3.onSecondCall().resolves(true); - const fn2 = sinon.stub(receiver, "hasTrust").resolves(false); + const fn2 = sinon.stub(receiver, 'hasTrust').resolves(false); const transfer = await receiver.transferBundle(sender, receiver, 1); - expect(transfer).property("state").eq(Transfer.STATE.requested); + expect(transfer).property('state').eq(Transfer.STATE.requested); expect(fn1).to.have.been.calledWith({ originator_wallet_id: receiver.getId(), source_wallet_id: sender.getId(), @@ -440,7 +465,7 @@ describe("Wallet", () => { parameters: { bundle: { bundleSize: 1, - } + }, }, }); fn0.restore(); @@ -448,20 +473,24 @@ describe("Wallet", () => { fn2.restore(); }); - it("have trust, not deduct, should finish successfully", async () => { - const fn0 = sinon.stub(TokenService.prototype, "countTokenByWallet").resolves(1); - const fn1 = sinon.stub(Wallet.prototype, "hasTrust").resolves(true); - sinon.stub(Wallet.prototype, "isDeduct").resolves(false); - const fn2 = sinon.stub(TransferRepository.prototype, "create"); - const fn3 = sinon.stub(TokenService.prototype, "completeTransfer"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - const fn4 = sinon.stub(TokenService.prototype, "getTokensByBundle").resolves([ - new Token(uuid.v4(), session) - ]); + it('have trust, not deduct, should finish successfully', async () => { + const fn0 = sinon + .stub(TokenService.prototype, 'countTokenByWallet') + .resolves(1); + const fn1 = sinon.stub(Wallet.prototype, 'hasTrust').resolves(true); + sinon.stub(Wallet.prototype, 'isDeduct').resolves(false); + const fn2 = sinon.stub(TransferRepository.prototype, 'create'); + const fn3 = sinon.stub(TokenService.prototype, 'completeTransfer'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + const fn4 = sinon + .stub(TokenService.prototype, 'getTokensByBundle') + .resolves([new Token(uuid.v4(), session)]); await wallet.transferBundle(sender, receiver, 1); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.completed, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.completed, + }), + ); expect(fn3).calledWith(); fn0.restore(); fn1.restore(); @@ -470,89 +499,104 @@ describe("Wallet", () => { fn4.restore(); }); - it("have trust, is deduct, should pending", async () => { - const fn0 = sinon.stub(TokenService.prototype, "countTokenByWallet").resolves(1); - const fn1 = sinon.stub(Wallet.prototype, "hasTrust").resolves(true); - sinon.stub(Wallet.prototype, "isDeduct").resolves(true); - const fn2 = sinon.stub(TransferRepository.prototype, "create"); - const fn3 = sinon.stub(Token.prototype, "completeTransfer"); - const fn4 = sinon.stub(TokenService.prototype, "getTokensByBundle").resolves([ - new Token(uuid.v4(), session) - ]); - const fn5 = sinon.stub(Wallet.prototype, "hasControlOver"); + it('have trust, is deduct, should pending', async () => { + const fn0 = sinon + .stub(TokenService.prototype, 'countTokenByWallet') + .resolves(1); + const fn1 = sinon.stub(Wallet.prototype, 'hasTrust').resolves(true); + sinon.stub(Wallet.prototype, 'isDeduct').resolves(true); + const fn2 = sinon.stub(TransferRepository.prototype, 'create'); + const fn3 = sinon.stub(Token.prototype, 'completeTransfer'); + const fn4 = sinon + .stub(TokenService.prototype, 'getTokensByBundle') + .resolves([new Token(uuid.v4(), session)]); + const fn5 = sinon.stub(Wallet.prototype, 'hasControlOver'); fn5.onCall(0).resolves(false); fn5.onCall(1).resolves(true); await wallet.transferBundle(sender, receiver, 1); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.requested, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.requested, + }), + ); fn0.restore(); fn1.restore(); fn2.restore(); fn3.restore(); fn4.restore(); }); - }); - 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").resolves([{id:uuid.v4()}]); + 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') + .resolves([{ id: uuid.v4() }]); const result = await wallet.getPendingTransfers(); expect(result).lengthOf(1); fn1.restore(); }); }); - describe("acceptTransfer", () => { - - const sender = new Wallet(uuid.v4()) - const receiver = new Wallet(uuid.v4()) - const token = new Token({ - id: uuid.v4(), - }, session); - const transferId = uuid.v4() + describe('acceptTransfer', () => { + 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("can not accept transfer who's state isn't pending", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({ + sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, state: Transfer.STATE.requested, - }); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([token]); - sinon.stub(Token.prototype, "completeTransfer"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([token]); + sinon.stub(Token.prototype, 'completeTransfer'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await jestExpect(async () => { await wallet.acceptTransfer(transferId); }).rejects.toThrow(/pending/); }); - it("acceptTransfer", async () => { + it('acceptTransfer', async () => { const walletId1 = uuid.v4(); const walletId2 = uuid.v4(); - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, state: Transfer.STATE.pending, source_wallet_id: walletId1, destination_wallet_id: walletId2, - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn3 = sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([ token ]); - const fn4 = sinon.stub(TokenService.prototype, "completeTransfer"); - const fn5 = sinon.stub(WalletService.prototype, "getById"); - const fn6 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn3 = sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([token]); + const fn4 = sinon.stub(TokenService.prototype, 'completeTransfer'); + const fn5 = sinon.stub(WalletService.prototype, 'getById'); + const fn6 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await wallet.acceptTransfer(transferId); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.completed, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.completed, + }), + ); expect(fn4).calledWith(); fn1.restore(); fn2.restore(); @@ -562,26 +606,30 @@ describe("Wallet", () => { fn6.restore(); }); - it("acceptTransfer with bundle", async () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + it('acceptTransfer with bundle', async () => { + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, source_wallet_id: receiver.getId(), state: Transfer.STATE.pending, parameters: { bundle: { bundleSize: 1, - } + }, }, - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn4 = sinon.stub(TokenService.prototype, "completeTransfer"); - const fn5 = sinon.stub(TokenService.prototype, "getTokensByBundle").resolves([ token ]); - const fn6 = sinon.stub(WalletService.prototype, "getById"); - const fn7 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn4 = sinon.stub(TokenService.prototype, 'completeTransfer'); + const fn5 = sinon + .stub(TokenService.prototype, 'getTokensByBundle') + .resolves([token]); + const fn6 = sinon.stub(WalletService.prototype, 'getById'); + const fn7 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await receiver.acceptTransfer(transferId); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.completed, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.completed, + }), + ); expect(fn5).calledWith(sinon.match.any, 1); expect(fn4).calledWith(); fn1.restore(); @@ -593,46 +641,56 @@ describe("Wallet", () => { }); }); - describe("declineTransfer", () => { - - const wallet = new Wallet(uuid.v4()) - 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("fail to decline if transfer state is neither the pending nor requested", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({id:transferId}); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([token.id]); - sinon.stub(Token.prototype, "cancelTransfer"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + describe('declineTransfer', () => { + const wallet = new Wallet(uuid.v4()); + 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('fail to decline if transfer state is neither the pending nor requested', async () => { + sinon + .stub(TransferRepository.prototype, 'getById') + .resolves({ id: transferId }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([token.id]); + sinon.stub(Token.prototype, 'cancelTransfer'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await jestExpect(async () => { await wallet.declineTransfer(transferId); }).rejects.toThrow(/state/); }); it("Can decline a 'pending' transfer for a managed wallet", async () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, state: Transfer.STATE.pending, source_wallet_id: sender.getId(), destination_wallet_id: receiver.getId(), - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn3 = sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([token]); - const fn4 = sinon.stub(TokenService.prototype, "cancelTransfer"); - const fn5 = sinon.stub(WalletService.prototype, "getById"); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn3 = sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([token]); + const fn4 = sinon.stub(TokenService.prototype, 'cancelTransfer'); + const fn5 = sinon.stub(WalletService.prototype, 'getById'); fn5.onCall(0).resolves(sender); fn5.onCall(1).resolves(receiver); - const fn6 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + const fn6 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await wallet.declineTransfer(transferId); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.cancelled, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.cancelled, + }), + ); expect(fn4).calledWith(); expect(fn6).calledWith(receiver); fn1.restore(); @@ -644,23 +702,27 @@ describe("Wallet", () => { }); it("Can decline a 'requested' transfer for a managed wallet", async () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ - id:transferId, + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ + id: transferId, state: Transfer.STATE.requested, source_wallet_id: sender.getId(), destination_wallet_id: receiver.getId(), - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn3 = sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([token]); - const fn4 = sinon.stub(TokenService.prototype, "cancelTransfer"); - const fn5 = sinon.stub(WalletService.prototype, "getById"); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn3 = sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([token]); + const fn4 = sinon.stub(TokenService.prototype, 'cancelTransfer'); + const fn5 = sinon.stub(WalletService.prototype, 'getById'); fn5.onCall(0).resolves(sender); fn5.onCall(1).resolves(receiver); - const fn6 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + const fn6 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await wallet.declineTransfer(transferId); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.cancelled, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.cancelled, + }), + ); expect(fn4).calledWith(); expect(fn6).calledWith(sender); fn1.restore(); @@ -672,34 +734,40 @@ describe("Wallet", () => { }); }); - describe("cancelTransfer", () => { - - 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() + describe('cancelTransfer', () => { + 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 () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, state: Transfer.STATE.pending, source_wallet_id: wallet2.getId(), destination_wallet_id: wallet3.getId(), - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn3 = sinon.stub(WalletService.prototype, "getById"); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn3 = sinon.stub(WalletService.prototype, 'getById'); fn3.onCall(0).resolves(wallet2); fn3.onCall(1).resolves(wallet3); - const fn4 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([]); - sinon.stub(TokenService.prototype, "cancelTransfer"); + const fn4 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([]); + sinon.stub(TokenService.prototype, 'cancelTransfer'); await wallet.cancelTransfer(transferId); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.cancelled, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.cancelled, + }), + ); expect(fn4).calledWith(wallet2); fn1.restore(); fn2.restore(); @@ -708,23 +776,27 @@ describe("Wallet", () => { }); it("Can cancel a 'requested' transfer", async () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, state: Transfer.STATE.requested, source_wallet_id: wallet2.getId(), destination_wallet_id: wallet3.getId(), - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn3 = sinon.stub(WalletService.prototype, "getById"); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn3 = sinon.stub(WalletService.prototype, 'getById'); fn3.onCall(0).resolves(wallet2); fn3.onCall(1).resolves(wallet3); - const fn4 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([]); - sinon.stub(TokenService.prototype, "cancelTransfer"); + const fn4 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([]); + sinon.stub(TokenService.prototype, 'cancelTransfer'); await wallet.cancelTransfer(1); - expect(fn2).calledWith(sinon.match({ - state: Transfer.STATE.cancelled, - })); + expect(fn2).calledWith( + sinon.match({ + state: Transfer.STATE.cancelled, + }), + ); expect(fn4).calledWith(wallet3); fn1.restore(); fn2.restore(); @@ -733,26 +805,30 @@ 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 () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + 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 () => { + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, source_wallet_id: wallet.getId(), state: Transfer.STATE.requested, - }); - const fn2 = sinon.stub(TransferRepository.prototype, "update"); - const fn3 = sinon.stub(WalletService.prototype, "getById"); - const fn4 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(TokenService.prototype, "completeTransfer"); - sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([]); + }); + const fn2 = sinon.stub(TransferRepository.prototype, 'update'); + const fn3 = sinon.stub(WalletService.prototype, 'getById'); + const fn4 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon.stub(TokenService.prototype, 'completeTransfer'); + sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([]); await wallet.fulfillTransfer(transferId); fn1.restore(); fn2.restore(); @@ -761,12 +837,16 @@ describe("Wallet", () => { }); it("have no control over the transfer's sender , should throw 403 no permission", async () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves([{ - id: transferId, - source_wallet_id: wallet2.getId(), - }]); - const fn2 = sinon.stub(WalletService.prototype, "getById"); - const fn3 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(false); + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves([ + { + id: transferId, + source_wallet_id: wallet2.getId(), + }, + ]); + const fn2 = sinon.stub(WalletService.prototype, 'getById'); + const fn3 = sinon + .stub(Wallet.prototype, 'hasControlOver') + .resolves(false); await jestExpect(async () => { await wallet.fulfillTransfer(transferId); }).rejects.toThrow(/permission/); @@ -776,12 +856,12 @@ describe("Wallet", () => { }); it("the transfer's state is not requested, should throw 403 forbidden", async () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getById").resolves({ + const fn1 = sinon.stub(TransferRepository.prototype, 'getById').resolves({ id: transferId, source_wallet_id: wallet.getId(), - }); - const fn2 = sinon.stub(WalletService.prototype, "getById"); - const fn3 = sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + }); + const fn2 = sinon.stub(WalletService.prototype, 'getById'); + const fn3 = sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await jestExpect(async () => { await wallet.fulfillTransfer(transferId); }).rejects.toThrow(/forbidden/); @@ -791,223 +871,255 @@ describe("Wallet", () => { }); }); - describe("fulfillTransferWithTokens", () => { - - const wallet = new Wallet(uuid.v4()) - const wallet2 = new Wallet(uuid.v4()) - const token = new Token({ - id: uuid.v4(), - }, session); - const token2 = new Token({ - id: uuid.v4(), - }, session); - const transferId = uuid.v4() - - it("fulfillTransfer successfully", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({ - id:1, + describe('fulfillTransferWithTokens', () => { + const wallet = new Wallet(uuid.v4()); + const wallet2 = new Wallet(uuid.v4()); + const token = new Token( + { + id: uuid.v4(), + }, + session, + ); + const token2 = new Token( + { + id: uuid.v4(), + }, + session, + ); + const transferId = uuid.v4(); + + it('fulfillTransfer successfully', async () => { + sinon.stub(TransferRepository.prototype, 'getById').resolves({ + id: 1, source_wallet_id: wallet.getId(), state: Transfer.STATE.requested, - parameters:{ + parameters: { bundle: { bundleSize: 1, - } - } - }); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(Token.prototype, "toJSON").resolves({uuid:"xxx"}); - sinon.stub(Token.prototype, "belongsTo").resolves(true); - sinon.stub(TokenService.prototype, "completeTransfer"); + }, + }, + }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon.stub(Token.prototype, 'toJSON').resolves({ uuid: 'xxx' }); + sinon.stub(Token.prototype, 'belongsTo').resolves(true); + sinon.stub(TokenService.prototype, 'completeTransfer'); await wallet.fulfillTransferWithTokens(1, [token]); }); - it("Should not set tokens for non-bundle case", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({ - id:1, + it('Should not set tokens for non-bundle case', async () => { + sinon.stub(TransferRepository.prototype, 'getById').resolves({ + id: 1, source_wallet_id: wallet.getId(), state: Transfer.STATE.requested, - parameters:{ - } - }); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + parameters: {}, + }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await jestExpect(async () => { await wallet.fulfillTransferWithTokens(1, [token]); }).rejects.toThrow(/no need/i); }); - it("Too many tokens", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({ - id:1, + it('Too many tokens', async () => { + sinon.stub(TransferRepository.prototype, 'getById').resolves({ + id: 1, source_wallet_id: wallet.getId(), state: Transfer.STATE.requested, - parameters:{ + parameters: { bundle: { bundleSize: 1, - } - } - }); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(Token.prototype, "toJSON").resolves({uuid:"xxx"}); - sinon.stub(Token.prototype, "belongsTo").resolves(true); - sinon.stub(Token.prototype, "completeTransfer"); + }, + }, + }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon.stub(Token.prototype, 'toJSON').resolves({ uuid: 'xxx' }); + sinon.stub(Token.prototype, 'belongsTo').resolves(true); + sinon.stub(Token.prototype, 'completeTransfer'); await jestExpect(async () => { await wallet.fulfillTransferWithTokens(1, [token, token2]); }).rejects.toThrow(/too many/i); }); - it("Too few tokens", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({ - id:1, + it('Too few tokens', async () => { + sinon.stub(TransferRepository.prototype, 'getById').resolves({ + id: 1, source_wallet_id: wallet.getId(), state: Transfer.STATE.requested, - parameters:{ + parameters: { bundle: { bundleSize: 1, - } - } - }); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + }, + }, + }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); await jestExpect(async () => { await wallet.fulfillTransferWithTokens(1, []); }).rejects.toThrow(/too few/i); }); - it("Specified token do not belongs to the wallet", async () => { - sinon.stub(TransferRepository.prototype, "getById").resolves({ - id:transferId, + it('Specified token do not belongs to the wallet', async () => { + sinon.stub(TransferRepository.prototype, 'getById').resolves({ + id: transferId, source_wallet_id: wallet.getId(), state: Transfer.STATE.requested, - parameters:{ + parameters: { bundle: { bundleSize: 1, - } - } - }); - sinon.stub(TransferRepository.prototype, "update"); - sinon.stub(WalletService.prototype, "getById"); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - sinon.stub(Token.prototype, "toJSON").resolves({uuid:"xxx"}); - sinon.stub(Token.prototype, "belongsTo").resolves(false); + }, + }, + }); + sinon.stub(TransferRepository.prototype, 'update'); + sinon.stub(WalletService.prototype, 'getById'); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + sinon.stub(Token.prototype, 'toJSON').resolves({ uuid: 'xxx' }); + sinon.stub(Token.prototype, 'belongsTo').resolves(false); await jestExpect(async () => { await wallet.fulfillTransferWithTokens(transferId, [token]); }).rejects.toThrow(/belongs to/i); }); - }); - 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 () => { - const fn1 = sinon.stub(TransferRepository.prototype, "getByFilter").resolves([{id:transferId}]); + 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 () => { + const fn1 = sinon + .stub(TransferRepository.prototype, 'getByFilter') + .resolves([{ id: transferId }]); const result = await wallet.getTransfers( Transfer.STATE.requested, wallet2, ); expect(result).lengthOf(1); - expect(fn1).calledWith( - { - and: [{ + expect(fn1).calledWith({ + and: [ + { or: [ { source_wallet_id: wallet.getId(), - },{ + }, + { destination_wallet_id: wallet.getId(), - },{ + }, + { originator_wallet_id: wallet.getId(), - } + }, ], - },{ + }, + { state: Transfer.STATE.requested, - },{ + }, + { or: [ { source_wallet_id: wallet2.getId(), - },{ + }, + { destination_wallet_id: wallet2.getId(), - },{ + }, + { originator_wallet_id: wallet2.getId(), - } + }, ], - }] - } - ); + }, + ], + }); fn1.restore(); }); - }); - 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); + 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); expect(result).eq(true); }); - it("hasControlOver should pass if manage/yield trust exists", async () => { - const fn = sinon.stub(TrustRepository.prototype, "getByFilter").resolves([{}]); - const result = await wallet.hasControlOver(wallet2); + it('hasControlOver should pass if manage/yield trust exists', async () => { + const fn = sinon + .stub(TrustRepository.prototype, 'getByFilter') + .resolves([{}]); + const result = await wallet.hasControlOver(wallet2); expect(result).eq(true); expect(fn).calledWith({ or: [ { - and: [{ - actor_wallet_id: wallet.getId(), - },{ - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, - },{ - target_wallet_id: wallet2.getId(), - },{ - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - }], - },{ - and: [{ - actor_wallet_id: wallet2.getId(), - },{ - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, - },{ - target_wallet_id: wallet.getId(), - },{ - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - }] - } - ] + and: [ + { + actor_wallet_id: wallet.getId(), + }, + { + request_type: + TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.manage, + }, + { + target_wallet_id: wallet2.getId(), + }, + { + state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + }, + ], + }, + { + and: [ + { + actor_wallet_id: wallet2.getId(), + }, + { + request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.yield, + }, + { + target_wallet_id: wallet.getId(), + }, + { + state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + }, + ], + }, + ], }); }); }); - 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 () => { - const fn = sinon.stub(TrustRepository.prototype, "getByFilter").resolves([{id:trustId}]); + 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 () => { + const fn = sinon + .stub(TrustRepository.prototype, 'getByFilter') + .resolves([{ id: trustId }]); const result = await wallet.getTrustRelationships( TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, TrustRelationship.ENTITY_TRUST_TYPE.send, @@ -1015,237 +1127,270 @@ describe("Wallet", () => { ); expect(result).lengthOf(1); expect(fn).calledWith({ - and: [{ - state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - },{ - type: TrustRelationship.ENTITY_TRUST_TYPE.send, - },{ - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, - },{ - or: [{ - actor_wallet_id: wallet.getId(), - },{ - target_wallet_id: wallet.getId(), - },{ - originator_wallet_id: wallet.getId(), - }] - }] + and: [ + { + state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, + }, + { + type: TrustRelationship.ENTITY_TRUST_TYPE.send, + }, + { + request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + }, + { + or: [ + { + actor_wallet_id: wallet.getId(), + }, + { + target_wallet_id: wallet.getId(), + }, + { + originator_wallet_id: wallet.getId(), + }, + ], + }, + ], }); fn.restore(); }); - it("without filters", async () => { - const fn = sinon.stub(TrustRepository.prototype, "getByFilter").resolves([{id:trustId}]); + it('without filters', async () => { + const fn = sinon + .stub(TrustRepository.prototype, 'getByFilter') + .resolves([{ id: trustId }]); const result = await wallet.getTrustRelationships(); expect(result).lengthOf(1); expect(fn).calledWith({ - and: [{ - or: [{ - actor_wallet_id: wallet.getId(), - },{ - target_wallet_id: wallet.getId(), - },{ - originator_wallet_id: wallet.getId(), - }] - }] + and: [ + { + or: [ + { + actor_wallet_id: wallet.getId(), + }, + { + target_wallet_id: wallet.getId(), + }, + { + originator_wallet_id: wallet.getId(), + }, + ], + }, + ], }); fn.restore(); }); }); - describe("Deduct", () => { - - 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 () => { + describe('Deduct', () => { + 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); expect(result).eq(false); }); - it("The sender is my sub wallet, should return false", async () => { - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); + it('The sender is my sub wallet, should return false', async () => { + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); const result = await wallet.isDeduct(sender, receiver); expect(result).eq(false); }); // TODO: deduction is not supported yet it.skip("The sender isn't my sub wallet, should throw 403", async () => { - sinon.stub(Wallet.prototype, "hasControlOver").resolves(false); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(false); const result = await wallet.isDeduct(sender, receiver); expect(result).eq(true); }); }); - describe("getSubWallet", () => { - - const wallet = new Wallet(uuid.v4()) - const subWallet = new Wallet(uuid.v4()) + describe('getSubWallet', () => { + const wallet = new Wallet(uuid.v4()); + const subWallet = new Wallet(uuid.v4()); - it("get sub wallet successfully", async () => { - sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{ - 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, - }]); - sinon.stub(WalletService.prototype, "getById").resolves(subWallet); + it('get sub wallet successfully', async () => { + sinon.stub(Wallet.prototype, 'getTrustRelationships').resolves([ + { + 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, + }, + ]); + sinon.stub(WalletService.prototype, 'getById').resolves(subWallet); const wallets = await wallet.getSubWallets(); expect(wallets).lengthOf(1); }); - it("get sub wallet which is state of yield", async () => { - sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{ - 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, - }]); - sinon.stub(WalletService.prototype, "getById").resolves(subWallet); + it('get sub wallet which is state of yield', async () => { + sinon.stub(Wallet.prototype, 'getTrustRelationships').resolves([ + { + 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, + }, + ]); + sinon.stub(WalletService.prototype, 'getById').resolves(subWallet); const wallets = await wallet.getSubWallets(); expect(wallets).lengthOf(1); }); }); - describe("getTrustRelationshipsRequestedToMe", () => { - + describe('getTrustRelationshipsRequestedToMe', () => { const wallet = new Wallet(uuid.v4()); const subWallet = new Wallet(uuid.v4()); - const wallet2 = new Wallet(uuid.v4()) + const wallet2 = new Wallet(uuid.v4()); - it("get one", async () => { - sinon.stub(Wallet.prototype, "getSubWallets").resolves([]); - sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([{ - actor_wallet_id: wallet2.getId(), - target_wallet_id: wallet.getId(), - request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, - }]); - const list = await wallet.getTrustRelationshipsRequestedToMe() + it('get one', async () => { + sinon.stub(Wallet.prototype, 'getSubWallets').resolves([]); + sinon.stub(Wallet.prototype, 'getTrustRelationships').resolves([ + { + actor_wallet_id: wallet2.getId(), + target_wallet_id: wallet.getId(), + request_type: TrustRelationship.ENTITY_TRUST_REQUEST_TYPE.send, + }, + ]); + const list = await wallet.getTrustRelationshipsRequestedToMe(); expect(list).lengthOf(1); }); - it("get one requested to my sub wallet", async () => { - sinon.stub(Wallet.prototype, "getSubWallets").resolves([subWallet]); - const fn = sinon.stub(Wallet.prototype, "getTrustRelationships") - fn.onCall(0).resolves([{ - actor_wallet_id: wallet2.getId(), - target_wallet_id: wallet.getId(), - request_type: TrustRelationship.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, - }]); - const list = await wallet.getTrustRelationshipsRequestedToMe() + it('get one requested to my sub wallet', async () => { + sinon.stub(Wallet.prototype, 'getSubWallets').resolves([subWallet]); + const fn = sinon.stub(Wallet.prototype, 'getTrustRelationships'); + fn.onCall(0).resolves([ + { + actor_wallet_id: wallet2.getId(), + target_wallet_id: wallet.getId(), + request_type: TrustRelationship.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, + }, + ]); + const list = await wallet.getTrustRelationshipsRequestedToMe(); expect(list).lengthOf(2); }); }); - describe("checkManageRecycle", () => { - + describe('checkManageRecycle', () => { const walletA = new Wallet(uuid.v4()); - const walletB = new Wallet(uuid.v4()) - const trustIdA = uuid.v4() - const trustIdB = uuid.v4() + const walletB = new Wallet(uuid.v4()); + const trustIdA = uuid.v4(); + const trustIdB = uuid.v4(); - it("A manage B, now B request to manage A, should throw error", async () => { + 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, 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, actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), - } - sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([trustRelationshipTrusted]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') + .resolves([trustRelationshipTrusted]); await jestExpect(async () => { await walletA.checkManageCircle(trustRelationshipRequested); }).rejects.toThrow(/circle/); }); - it("A manage B, now A request to yield B, should throw error", async () => { + 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, 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, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), - } - sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([trustRelationshipTrusted]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') + .resolves([trustRelationshipTrusted]); await jestExpect(async () => { await walletA.checkManageCircle(trustRelationshipRequested); }).rejects.toThrow(/circle/); }); - it("A yield B, now B request to yield A, should throw error", async () => { + 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, 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, actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), - } - sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([trustRelationshipTrusted]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') + .resolves([trustRelationshipTrusted]); await jestExpect(async () => { await walletA.checkManageCircle(trustRelationshipRequested); }).rejects.toThrow(/circle/); }); - it("A yield B, now A request to manage B, should throw error", async () => { + 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, 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, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), - } - sinon.stub(Wallet.prototype, "getTrustRelationshipsTrusted").resolves([trustRelationshipTrusted]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationshipsTrusted') + .resolves([trustRelationshipTrusted]); await jestExpect(async () => { await walletA.checkManageCircle(trustRelationshipRequested); }).rejects.toThrow(/circle/); }); }); - describe("checkDuplicateRequest", () => { - + describe('checkDuplicateRequest', () => { const walletA = new Wallet(uuid.v4()); - const walletB = new Wallet(uuid.v4()) - const trustIdA = uuid.v4() - const trustIdB = uuid.v4() + const walletB = new Wallet(uuid.v4()); + const trustIdA = uuid.v4(); + const trustIdB = uuid.v4(); - it("A send B trust has been requested, now request again, should throw error", async () => { + 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, @@ -1253,7 +1398,7 @@ describe("Wallet", () => { actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, - } + }; const trustRelationshipRequesting = { id: trustIdB, type: TrustRelationship.ENTITY_TRUST_TYPE.send, @@ -1261,22 +1406,24 @@ describe("Wallet", () => { actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, - } - sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([trustRelationshipRequested]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationships') + .resolves([trustRelationshipRequested]); await jestExpect(async () => { await wallet.checkDuplicateRequest(trustRelationshipRequesting); }).rejects.toThrow(/has been/); }); - it("A send B trust has been trusted, now request B receive A, should throw error", async () => { + it('A send B trust has been trusted, now request B receive A, should throw error', async () => { const trustRelationshipRequested = { - id: trustIdA, + id: trustIdA, type: TrustRelationship.ENTITY_TRUST_TYPE.send, request_type: TrustRelationship.ENTITY_TRUST_TYPE.send, actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.trusted, - } + }; const trustRelationshipRequesting = { id: trustIdB, type: TrustRelationship.ENTITY_TRUST_TYPE.send, @@ -1284,14 +1431,16 @@ describe("Wallet", () => { actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, - } - sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([trustRelationshipRequested]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationships') + .resolves([trustRelationshipRequested]); await jestExpect(async () => { await wallet.checkDuplicateRequest(trustRelationshipRequesting); }).rejects.toThrow(/has been/); }); - it("A manage B trust has been requested, now request B yield A, should throw error", async () => { + 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, @@ -1299,7 +1448,7 @@ describe("Wallet", () => { actor_wallet_id: walletA.getId(), target_wallet_id: walletB.getId(), state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, - } + }; const trustRelationshipRequesting = { id: trustIdB, type: TrustRelationship.ENTITY_TRUST_TYPE.manage, @@ -1307,64 +1456,67 @@ describe("Wallet", () => { actor_wallet_id: walletB.getId(), target_wallet_id: walletA.getId(), state: TrustRelationship.ENTITY_TRUST_STATE_TYPE.requested, - } - sinon.stub(Wallet.prototype, "getTrustRelationships").resolves([trustRelationshipRequested]); + }; + sinon + .stub(Wallet.prototype, 'getTrustRelationships') + .resolves([trustRelationshipRequested]); await jestExpect(async () => { await wallet.checkDuplicateRequest(trustRelationshipRequesting); }).rejects.toThrow(/has been/); }); }); - describe("getTransferById", () => { - - const transferId = uuid.v4() + describe('getTransferById', () => { + const transferId = uuid.v4(); - it("Successfully", async () => { - sinon.stub(Wallet.prototype, "getTransfers").resolves([{ - id: transferId , - }]); + it('Successfully', async () => { + sinon.stub(Wallet.prototype, 'getTransfers').resolves([ + { + id: transferId, + }, + ]); const transfer = await wallet.getTransferById(transferId); - expect(transfer).property("id").eq(transferId); + expect(transfer).property('id').eq(transferId); }); - it("Not fond", async () => { - sinon.stub(Wallet.prototype, "getTransfers").resolves([]); + it('Not fond', async () => { + sinon.stub(Wallet.prototype, 'getTransfers').resolves([]); await jestExpect(async () => { await wallet.getTransferById(1); }).rejects.toThrow(/not find/); }); }); - describe("getTokensByTransferId", () => { - - const token = new Token(uuid.v4()) - const transferId = uuid.v4() + describe('getTokensByTransferId', () => { + const token = new Token(uuid.v4()); + const transferId = uuid.v4(); - it("Completed transfer", async () => { - const transfer = { + it('Completed transfer', async () => { + const transfer = { id: transferId, state: Transfer.STATE.completed, }; - sinon.stub(Wallet.prototype, "getTransferById").resolves(transfer); - const fn = sinon.stub(TokenService.prototype, "getTokensByTransferId").resolves([token]); + sinon.stub(Wallet.prototype, 'getTransferById').resolves(transfer); + const fn = sinon + .stub(TokenService.prototype, 'getTokensByTransferId') + .resolves([token]); const tokens = await wallet.getTokensByTransferId(transferId); expect(tokens).lengthOf(1); expect(fn).calledWith(transferId); }); - it("Pending/requested transfer", async () => { - const transfer = { + it('Pending/requested transfer', async () => { + const transfer = { id: transferId, state: Transfer.STATE.pending, }; - sinon.stub(Wallet.prototype, "getTransferById").resolves(transfer); - const fn = sinon.stub(TokenService.prototype, "getTokensByPendingTransferId").resolves([token]); + sinon.stub(Wallet.prototype, 'getTransferById').resolves(transfer); + const fn = sinon + .stub(TokenService.prototype, 'getTokensByPendingTransferId') + .resolves([token]); const tokens = await wallet.getTokensByTransferId(transferId); expect(tokens).lengthOf(1); expect(fn).calledWith(transferId); }); - }); - - }); diff --git a/server/repositories/TransactionRepository.js b/server/repositories/TransactionRepository.js index 689b3f64..45cec3ef 100644 --- a/server/repositories/TransactionRepository.js +++ b/server/repositories/TransactionRepository.js @@ -1,9 +1,8 @@ -const expect = require("expect-runtime"); -const BaseRepository = require("./BaseRepository"); +const BaseRepository = require('./BaseRepository'); -class TransferRepository extends BaseRepository{ - constructor(session){ - super("transaction", session); +class TransferRepository extends BaseRepository { + constructor(session) { + super('transaction', session); this._session = session; } } diff --git a/server/routes/tokenRouter.spec.js b/server/routes/tokenRouter.spec.js index 04b31514..ebc39ef2 100644 --- a/server/routes/tokenRouter.spec.js +++ b/server/routes/tokenRouter.spec.js @@ -1,30 +1,30 @@ -const request = require("supertest"); -const express = require("express"); -const {expect} = require("chai"); -const sinon = require("sinon"); +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} = require("./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", () => { +const tokenRouter = require('./tokenRouter'); +const { errorHandler } = require('./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; const authenticatedWallet = { - id: uuid.v4() - } + id: uuid.v4(), + }; beforeEach(() => { - sinon.stub(ApiKeyService.prototype, "check"); - sinon.stub(JWTService.prototype, "verify").returns({ + sinon.stub(ApiKeyService.prototype, 'check'); + sinon.stub(JWTService.prototype, 'verify').returns({ id: authenticatedWallet.id, }); app = express(); @@ -32,193 +32,206 @@ describe("tokenRouter", () => { app.use(bodyParser.json()); // parse application/json app.use(tokenRouter); app.use(errorHandler); - }) + }); afterEach(() => { sinon.restore(); - }) + }); - describe("get tokens, GET /", () => { - 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() + describe('get tokens, GET /', () => { + 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 + capture_id: captureId, }); const token2 = new Token({ id: token2Id, wallet_id: wallet2Id, - capture_id: capture2Id + capture_id: capture2Id, }); const wallet = new Wallet(walletId); const wallet2 = new Wallet(wallet2Id); - - it("limit parameters missed", async () => { - const res = await request(app) - .get("/"); - expect(res).property("statusCode").eq(422); + it('limit parameters missed', async () => { + const res = await request(app).get('/'); + expect(res).property('statusCode').eq(422); }); - it("successfully, default wallet", async () => { - sinon.stub(TokenService.prototype, "getByOwner").resolves([token2]); - sinon.stub(WalletService.prototype, "getById").resolves(wallet); - const res = await request(app) - .get("/?limit=10&start=1"); - expect(res).property("statusCode").eq(200); + it('successfully, default wallet', async () => { + sinon.stub(TokenService.prototype, 'getByOwner').resolves([token2]); + sinon.stub(WalletService.prototype, 'getById').resolves(wallet); + const res = await request(app).get('/?limit=10&start=1'); + expect(res).property('statusCode').eq(200); expect(res.body.tokens).lengthOf(1); - expect(res.body.tokens[0]).property("id").eq(token2Id); - expect(res.body.tokens[0]).property("links").property("capture").eq(`/webmap/tree?uuid=${ capture2Id}`); + expect(res.body.tokens[0]).property('id').eq(token2Id); + expect(res.body.tokens[0]) + .property('links') + .property('capture') + .eq(`/webmap/tree?uuid=${capture2Id}`); }); - it("successfully, sub wallet", async () => { - sinon.stub(TokenService.prototype, "getByOwner").resolves([token]); - sinon.stub(WalletService.prototype, "getById").resolves(wallet); - sinon.stub(WalletService.prototype, "getByName").resolves(wallet2); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(true); - const res = await request(app) - .get(`/?limit=10&wallet=${wallet2Id}`); - expect(res).property("statusCode").eq(200); - expect(res.body.tokens[0]).property("id").eq(tokenId); - expect(res.body.tokens[0]).property("links").property("capture").eq(`/webmap/tree?uuid=${ captureId}`); + it('successfully, sub wallet', async () => { + sinon.stub(TokenService.prototype, 'getByOwner').resolves([token]); + sinon.stub(WalletService.prototype, 'getById').resolves(wallet); + sinon.stub(WalletService.prototype, 'getByName').resolves(wallet2); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(true); + const res = await request(app).get(`/?limit=10&wallet=${wallet2Id}`); + expect(res).property('statusCode').eq(200); + expect(res.body.tokens[0]).property('id').eq(tokenId); + expect(res.body.tokens[0]) + .property('links') + .property('capture') + .eq(`/webmap/tree?uuid=${captureId}`); }); - it("sub wallet, no permission", async () => { - sinon.stub(TokenService.prototype, "getByOwner").resolves([token]); - sinon.stub(WalletService.prototype, "getById").resolves(wallet); - sinon.stub(WalletService.prototype, "getByName").resolves(wallet2); - sinon.stub(Wallet.prototype, "hasControlOver").resolves(false); - const res = await request(app) - .get("/?limit=10&wallet=B"); - expect(res).property("statusCode").eq(403); + it('sub wallet, no permission', async () => { + sinon.stub(TokenService.prototype, 'getByOwner').resolves([token]); + sinon.stub(WalletService.prototype, 'getById').resolves(wallet); + sinon.stub(WalletService.prototype, 'getByName').resolves(wallet2); + sinon.stub(Wallet.prototype, 'hasControlOver').resolves(false); + const res = await request(app).get('/?limit=10&wallet=B'); + expect(res).property('statusCode').eq(403); }); }); - - 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() + 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 + capture_id: captureId, }); const token2 = new Token({ id: token2Id, wallet_id: wallet2Id, - capture_id: capture2Id + 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); - sinon.stub(WalletService.prototype, "getById").resolves(wallet); - sinon.stub(Wallet.prototype, "getSubWallets").resolves([]); - sinon.stub(TokenService.prototype, "convertToResponse").resolves({ + it('/test-uuid successfully', async () => { + sinon.stub(TokenService.prototype, 'getById').resolves(token); + sinon.stub(WalletService.prototype, 'getById').resolves(wallet); + sinon.stub(Wallet.prototype, 'getSubWallets').resolves([]); + sinon.stub(TokenService.prototype, 'convertToResponse').resolves({ token: tokenId, sender_wallet: walletId, receiver_wallet: wallet2Id, }); - const res = await request(app) - .get(`/${tokenId}`); - expect(res).property("statusCode").eq(200); - expect(res.body).property("id").eq(tokenId); - expect(res.body).property("links").property("capture").eq(`/webmap/tree?uuid=${ captureId}`); + const res = await request(app).get(`/${tokenId}`); + expect(res).property('statusCode').eq(200); + expect(res.body).property('id').eq(tokenId); + expect(res.body) + .property('links') + .property('capture') + .eq(`/webmap/tree?uuid=${captureId}`); }); - it("/xxx/transactions successfully", async () => { - sinon.stub(TokenService.prototype, "getById").resolves(token); - sinon.stub(token, "toJSON").resolves({ + it('/xxx/transactions successfully', async () => { + sinon.stub(TokenService.prototype, 'getById').resolves(token); + sinon.stub(token, 'toJSON').resolves({ wallet_id: walletId, }); - sinon.stub(token, "getTransactions").resolves([{ - id: transactionId, - }]); - sinon.stub(WalletService.prototype, "getById").resolves(wallet); - sinon.stub(TokenService.prototype, "convertToResponse").resolves({ + sinon.stub(token, 'getTransactions').resolves([ + { + id: transactionId, + }, + ]); + sinon.stub(WalletService.prototype, 'getById').resolves(wallet); + sinon.stub(TokenService.prototype, 'convertToResponse').resolves({ token: tokenId, sender_wallet: walletId, receiver_wallet: wallet2Id, }); - sinon.stub(Wallet.prototype, "getSubWallets").resolves([]); - const res = await request(app) - .get(`/${tokenId}/transactions/?limit=1`); - expect(res).property("statusCode").eq(200); + sinon.stub(Wallet.prototype, 'getSubWallets').resolves([]); + const res = await request(app).get(`/${tokenId}/transactions/?limit=1`); + expect(res).property('statusCode').eq(200); expect(res.body.history).lengthOf(1); - expect(res.body.history[0]).property("token").eq(tokenId); - expect(res.body.history[0]).property("sender_wallet").eq(walletId); - expect(res.body.history[0]).property("receiver_wallet").eq(wallet2Id); + expect(res.body.history[0]).property('token').eq(tokenId); + expect(res.body.history[0]).property('sender_wallet').eq(walletId); + expect(res.body.history[0]).property('receiver_wallet').eq(wallet2Id); }); - it("/{token_uuid}/transactions: limit parameters missed", async () => { - const res = await request(app) - .get(`/${transactionId}/transactions`); - expect(res).property("statusCode").eq(422); + it('/{token_uuid}/transactions: limit parameters missed', async () => { + const res = await request(app).get(`/${transactionId}/transactions`); + expect(res).property('statusCode').eq(422); }); - it("/{token_uuid}/transactions limit and offset successfully", async () => { - sinon.stub(TokenService.prototype, "getById").resolves(token); - sinon.stub(token, "toJSON").resolves({ + it('/{token_uuid}/transactions limit and offset successfully', async () => { + sinon.stub(TokenService.prototype, 'getById').resolves(token); + sinon.stub(token, 'toJSON').resolves({ wallet_id: walletId, }); - const getTransactionsStub = sinon.stub(token, "getTransactions") + const getTransactionsStub = sinon.stub(token, 'getTransactions'); getTransactionsStub.resolves([ - {id: uuid.v4()}, {id: uuid.v4()}, {id: uuid.v4()} + { id: uuid.v4() }, + { id: uuid.v4() }, + { id: uuid.v4() }, + ]); + sinon.stub(WalletService.prototype, 'getById').resolves(wallet); + sinon + .stub(TokenService.prototype, 'convertToResponse') + .resolves({ + token: tokenId, + sender_wallet: authenticatedWallet, + receiver_wallet: wallet2Id, + }) + .onCall(0) + .resolves({ + token: tokenId, + sender_wallet: 'number5', + receiver_wallet: 'number5', + }) + .onCall(1) + .resolves({ + token: tokenId, + sender_wallet: 'number6', + receiver_wallet: 'number6', + }) + .onCall(2) + .resolves({ + token: tokenId, + sender_wallet: 'number7', + receiver_wallet: 'number7', + }); + sinon.stub(Wallet.prototype, 'getSubWallets').resolves([]); + + const limit = '3'; + const offset = '5'; + const res = await request(app).get( + `/${tokenId}/transactions?limit=${limit}&start=${offset}`, + ); + expect(res).property('statusCode').eq(200); + expect(getTransactionsStub.getCall(0).args).deep.to.equal([ + limit, + offset, ]); - sinon.stub(WalletService.prototype, "getById").resolves(wallet); - sinon.stub(TokenService.prototype, "convertToResponse").resolves({ - token: tokenId, - sender_wallet: authenticatedWallet, - receiver_wallet: wallet2Id, - }).onCall(0).resolves({ - token: tokenId, - sender_wallet: "number5", - receiver_wallet: "number5", - }).onCall(1).resolves({ - token: tokenId, - sender_wallet: "number6", - receiver_wallet: "number6", - }).onCall(2).resolves({ - token: tokenId, - sender_wallet: "number7", - receiver_wallet: "number7", - }); - sinon.stub(Wallet.prototype, "getSubWallets").resolves([]); - - const limit = "3" - const offset = "5" - const res = await request(app) - .get(`/${tokenId}/transactions?limit=${limit}&start=${offset}`); - expect(res).property("statusCode").eq(200); - expect(getTransactionsStub.getCall(0).args).deep.to.equal([limit, offset]) expect(res.body.history).lengthOf(3); - expect(res.body.history[0]).property("sender_wallet").eq("number5"); - expect(res.body.history[0]).property("receiver_wallet").eq("number5"); + expect(res.body.history[0]).property('sender_wallet').eq('number5'); + expect(res.body.history[0]).property('receiver_wallet').eq('number5'); - expect(res.body.history[1]).property("sender_wallet").eq("number6"); - expect(res.body.history[1]).property("receiver_wallet").eq("number6"); + expect(res.body.history[1]).property('sender_wallet').eq('number6'); + expect(res.body.history[1]).property('receiver_wallet').eq('number6'); - expect(res.body.history[2]).property("sender_wallet").eq("number7"); - expect(res.body.history[2]).property("receiver_wallet").eq("number7"); + expect(res.body.history[2]).property('sender_wallet').eq('number7'); + expect(res.body.history[2]).property('receiver_wallet').eq('number7'); }); }); - }); diff --git a/server/serverTest.js b/server/serverTest.js index a4def58f..08e0f4f4 100644 --- a/server/serverTest.js +++ b/server/serverTest.js @@ -1,19 +1,20 @@ /* * A test server for testing, seed some initial data into the DB */ -require('dotenv').config() -const app = require("./app"); +require('dotenv').config(); +const log = require('loglevel'); + +const app = require('./app'); const port = process.env.NODE_PORT || 3006; const seed = require('../__tests__/seed'); // set the log level -require("./setup"); -const log = require("loglevel"); +require('./setup'); -app.listen(port,async ()=>{ - log.info(`listening on port:${ port}`); - log.info("Seed data"); - log.debug("debug log level!"); - await seed.clear(); - await seed.seed(); +app.listen(port, async () => { + log.info(`listening on port:${port}`); + log.info('Seed data'); + log.debug('debug log level!'); + await seed.clear(); + await seed.seed(); }); From be7f4b29ae07364a76c8590483f20b22c8650c94 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 21:29:03 +0100 Subject: [PATCH 28/42] fix linter errors --- server/models/Token.js | 90 ++++++++++++-------------- server/repositories/TrustRepository.js | 49 +++++++------- server/services/JWTService.js | 38 +++++------ 3 files changed, 85 insertions(+), 92 deletions(-) diff --git a/server/models/Token.js b/server/models/Token.js index 705e7f1d..dc672421 100644 --- a/server/models/Token.js +++ b/server/models/Token.js @@ -1,20 +1,19 @@ -const log = require("loglevel"); +const log = require('loglevel'); const { validate: uuidValidate } = require('uuid'); -const Joi = require("joi"); -const expect = require("expect-runtime"); -const TokenRepository = require("../repositories/TokenRepository"); -const TransactionRepository = require("../repositories/TransactionRepository"); -const HttpError = require("../utils/HttpError"); - -class Token{ - - constructor(idOrJSON, session){ - if(uuidValidate(idOrJSON)){ +const Joi = require('joi'); +const expect = require('expect-runtime'); +const TokenRepository = require('../repositories/TokenRepository'); +const TransactionRepository = require('../repositories/TransactionRepository'); +const HttpError = require('../utils/HttpError'); + +class Token { + constructor(idOrJSON, session) { + if (uuidValidate(idOrJSON)) { this._id = idOrJSON; - }else if(typeof idOrJSON === "object" && uuidValidate(idOrJSON.id) ){ + } else if (typeof idOrJSON === 'object' && uuidValidate(idOrJSON.id)) { this._id = idOrJSON.id; this._JSON = idOrJSON; - }else{ + } else { throw new HttpError(500, `wrong contructor:${idOrJSON}`); } this.tokenRepository = new TokenRepository(session); @@ -22,34 +21,33 @@ class Token{ this._session = session; } - getId(){ + getId() { return this._id; } - async toJSON(){ - if(this._JSON){ - }else{ + async toJSON() { + if (!this._JSON) { this._JSON = await this.tokenRepository.getById(this._id); } // deal with tree links const result = { ...this._JSON, links: { - capture: `/webmap/tree?uuid=${this._JSON.capture_id}` - } - } + capture: `/webmap/tree?uuid=${this._JSON.capture_id}`, + }, + }; return result; } - clearJSON(){ + clearJSON() { this._JSON = undefined; } /* * To transfer this token according the transfer object */ - async completeTransfer(transfer){ - log.debug("Token complete transfer"); + async completeTransfer(transfer) { + log.debug('Token complete transfer'); await this.tokenRepository.update({ id: this._id, transfer_pending: false, @@ -67,12 +65,8 @@ class Token{ /* * To pending this token on the given transfer */ - async pendingTransfer(transfer){ - - Joi.assert( - transfer.id, - Joi.string().guid() - ) + async pendingTransfer(transfer) { + Joi.assert(transfer.id, Joi.string().guid()); await this.tokenRepository.update({ id: this._id, @@ -81,46 +75,42 @@ class Token{ }); } - async cancelTransfer(transfer){ - log.debug("Token cancel transfer"); + async cancelTransfer(transfer) { + log.debug('Token cancel transfer'); await this.tokenRepository.update({ id: this._id, transfer_pending: false, - transfer_pending_id: null + transfer_pending_id: null, }); } - async belongsTo(wallet){ - - Joi.assert( - wallet.getId(), - Joi.string().guid() - ) + async belongsTo(wallet) { + Joi.assert(wallet.getId(), Joi.string().guid()); const json = await this.toJSON(); - if(json.wallet_id === wallet.getId()){ + if (json.wallet_id === wallet.getId()) { return true; } - return false; - + return false; } - async beAbleToTransfer(){ + async beAbleToTransfer() { const json = await this.toJSON(); - if(json.transfer_pending === false){ + if (json.transfer_pending === false) { return true; } - return false; - + return false; } - async getTransactions(limit, offset = 0){ - const transactions = await this.transactionRepository.getByFilter({ - token_id: this._id, - }, {limit, offset}); + async getTransactions(limit, offset = 0) { + const transactions = await this.transactionRepository.getByFilter( + { + token_id: this._id, + }, + { limit, offset }, + ); return transactions; } - } module.exports = Token; diff --git a/server/repositories/TrustRepository.js b/server/repositories/TrustRepository.js index 3b4eac19..5ee4f008 100644 --- a/server/repositories/TrustRepository.js +++ b/server/repositories/TrustRepository.js @@ -1,47 +1,50 @@ -const expect = require("expect-runtime"); -const HttpError = require("../utils/HttpError"); -const BaseRepository = require("./BaseRepository"); -const Session = require("../models/Session"); - -class TrustRepository extends BaseRepository{ - constructor(session){ - super("wallet_trust", session); - this._tableName = "wallet_trust"; +const HttpError = require('../utils/HttpError'); +const BaseRepository = require('./BaseRepository'); +const Session = require('../models/Session'); + +class TrustRepository extends BaseRepository { + constructor(session) { + super('wallet_trust', session); + this._tableName = 'wallet_trust'; this._session = session; } - async get(){ + async get() { // const trust_relationship_instance = new trust_relationship(1); - const list = await this._session.getDB().select() - .table(this._tableName); + const list = await this._session.getDB().select().table(this._tableName); return list; } - async getByOriginatorId(id){ - const list = await this._session.getDB().select() + async getByOriginatorId(id) { + const list = await this._session + .getDB() + .select() .table(this._tableName) - .where("originator_wallet_id", id); + .where('originator_wallet_id', id); return list; } - async getByTargetId(id){ - const list = await this._session.getDB().select() + async getByTargetId(id) { + const list = await this._session + .getDB() + .select() .table(this._tableName) - .where("target_wallet_id", id); + .where('target_wallet_id', id); return list; } - async getTrustedByOriginatorId(id){ - const list = await this._session.getDB().select() + async getTrustedByOriginatorId(id) { + const list = await this._session + .getDB() + .select() .table(this._tableName) .where({ originator_wallet_id: id, - state: require("../models/TrustRelationship").ENTITY_TRUST_STATE_TYPE.trusted, + state: require('../models/TrustRelationship').ENTITY_TRUST_STATE_TYPE + .trusted, }); return list; } - } - module.exports = TrustRepository; diff --git a/server/services/JWTService.js b/server/services/JWTService.js index bbfc9a0d..101063b9 100644 --- a/server/services/JWTService.js +++ b/server/services/JWTService.js @@ -1,40 +1,41 @@ /* ________________________________________________________________________ * JWT Issuance upon prior authorization, login * ________________________________________________________________________ -*/ + */ 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"); +const log = require('loglevel'); +const path = require('path'); +const HttpError = require('../utils/HttpError'); // PRIVATE and PUBLIC key -const privateKEY = process.env.PRIVATE_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); -const publicKEY = process.env.PUBLIC_KEY // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key.pub'), 'utf8'); +const privateKEY = process.env.PRIVATE_KEY; // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key'), 'utf8'); +const publicKEY = process.env.PUBLIC_KEY; // FS.readFileSync(path.resolve(__dirname, '../../config/jwtRS256.key.pub'), 'utf8'); const signingOptions = { - issuer: "greenstand", - expiresIn: "365d", - algorithm: "RS256", + issuer: 'greenstand', + expiresIn: '365d', + algorithm: 'RS256', }; const verifyOptions = { - issuer: "greenstand", - expiresIn: "365d", - algorithms: ["RS256"], + issuer: 'greenstand', + expiresIn: '365d', + algorithms: ['RS256'], }; - -class JWTService{ - - sign(payload){ +class JWTService { + sign(payload) { return JWTTools.sign(payload, privateKEY, signingOptions); } verify(authorization) { if (!authorization) { - throw (403, 'ERROR: Authentication, no token supplied for protected path'); + throw new Error( + 403, + 'ERROR: Authentication, no token supplied for protected path', + ); } // accounts for the "Bearer" string before the token const tokenArray = authorization.split(' '); @@ -49,12 +50,11 @@ class JWTService{ } result = decod; }); - }else{ + } else { throw new HttpError(403, 'ERROR: Authentication, token not verified'); } return result; } - } module.exports = JWTService; From ab46af38831b5a5e9bad39d4ad0cf908c1c978eb Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 21:29:34 +0100 Subject: [PATCH 29/42] add linter config --- .eslintrc.json | 29 +++- .gitignore | 3 +- package-lock.json | 399 ++++++++++++++++++++++++++++++++++++++++++++-- package.json | 1 + 4 files changed, 411 insertions(+), 21 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 87466287..aa47d6b8 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,8 +1,10 @@ { "env": { - "node": true + "node": true, + "mocha": true, + "commonjs": true }, - "plugins": ["prettier"], + "plugins": ["prettier", "simple-import-sort", "eslint-plugin-import"], "extends": [ "airbnb-base", "prettier" @@ -11,5 +13,26 @@ "ecmaVersion": 12 }, "rules": { - } + "simple-import-sort/imports": "error", + "no-underscore-dangle": "off", + "camelcase":"off", + "no-unused-vars":"warn", + "func-names": "off", + "no-param-reassign": "warn", + "consistent-return":"warn", + "no-restricted-syntax":"warn", + "global-require":"off", + "radix":"off", + "no-await-in-loop":"off", + "class-methods-use-this":"warn", + "no-return-await":"warn", + "no-new-wrappers": "warn", + "prefer-destructuring": "warn", + "no-shadow":"warn", + "import/order": "warn", + "no-unused-expressions": "warn", + "import/no-extraneous-dependencies": "warn" , + "import/no-unresolved": "warn", + "no-plusplus":"warn", + "no-continue":"off" } } diff --git a/.gitignore b/.gitignore index 31bcff5b..ab61c36e 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ jwtRS256.key.pub keygen.sh database.json .env -.env.test \ No newline at end of file +.env.test +.vscode \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index fac96b36..922ae92d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.11.1", + "version": "1.12.1", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -905,14 +905,108 @@ "dev": true }, "array-includes": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz", - "integrity": "sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.3.tgz", + "integrity": "sha512-gcem1KlBU7c9rB+Rq8/3PPKsK2kjqeEBa3bD5kkQo4nYlOHQCJqIJFqBXDEfwaRuYTT4E+FxA9xez7Gf/e3Q7A==", "dev": true, "requires": { + "call-bind": "^1.0.2", "define-properties": "^1.1.3", - "es-abstract": "^1.17.0", + "es-abstract": "^1.18.0-next.2", + "get-intrinsic": "^1.1.1", "is-string": "^1.0.5" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz", + "integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "get-intrinsic": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", + "is-negative-zero": "^2.0.1", + "is-regex": "^1.1.2", + "is-string": "^1.0.5", + "object-inspect": "^1.9.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.0" + } + }, + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, + "is-negative-zero": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", + "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", + "dev": true + }, + "is-regex": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz", + "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz", + "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "string.prototype.trimend": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string.prototype.trimstart": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + } } }, "array-slice": { @@ -926,13 +1020,106 @@ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=" }, "array.prototype.flat": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz", - "integrity": "sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.4.tgz", + "integrity": "sha512-4470Xi3GAPAjZqFcljX2xzckv1qeKPizoNkiS0+O4IoPR2ZNpcjE0pkhdihlDouK+x6QOast26B4Q/O9DJnwSg==", "dev": true, "requires": { + "call-bind": "^1.0.0", "define-properties": "^1.1.3", - "es-abstract": "^1.17.0-next.1" + "es-abstract": "^1.18.0-next.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz", + "integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "get-intrinsic": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", + "is-negative-zero": "^2.0.1", + "is-regex": "^1.1.2", + "is-string": "^1.0.5", + "object-inspect": "^1.9.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.0" + } + }, + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, + "is-negative-zero": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", + "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", + "dev": true + }, + "is-regex": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz", + "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz", + "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "string.prototype.trimend": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string.prototype.trimstart": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + } } }, "arrify": { @@ -1225,6 +1412,16 @@ } } }, + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -2417,6 +2614,11 @@ "prettier-linter-helpers": "^1.0.0" } }, + "eslint-plugin-simple-import-sort": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-simple-import-sort/-/eslint-plugin-simple-import-sort-7.0.0.tgz", + "integrity": "sha512-U3vEDB5zhYPNfxT5TYR7u01dboFZp+HNpnGhkDB2g/2E4wZ/g1Q9Ton8UwCLfRV9yAKyYqDh62oHOamvkFxsvw==" + }, "eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -3045,6 +3247,17 @@ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" }, + "get-intrinsic": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", + "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + } + }, "get-stdin": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", @@ -3185,6 +3398,12 @@ "function-bind": "^1.1.1" } }, + "has-bigints": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", + "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", + "dev": true + }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -3476,6 +3695,12 @@ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, + "is-bigint": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.1.tgz", + "integrity": "sha512-J0ELF4yHFxHy0cmSxZuheDOz2luOdVvqjwmEcj8H/L1JHeuEDSDbeRP+Dk9kFVk5RTFzbucJ2Kb9F7ixY2QaCg==", + "dev": true + }, "is-binary-path": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", @@ -3484,6 +3709,15 @@ "binary-extensions": "^2.0.0" } }, + "is-boolean-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.0.tgz", + "integrity": "sha512-a7Uprx8UtD+HWdyYwnD1+ExtTgqQtD2k/1yJgtXP6wnMm8byhkoTZRl+95LLThpzNZJ5aEvi46cdH+ayMFRwmA==", + "dev": true, + "requires": { + "call-bind": "^1.0.0" + } + }, "is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", @@ -3620,6 +3854,12 @@ } } }, + "is-number-object": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.4.tgz", + "integrity": "sha512-zohwelOAur+5uXtk8O3GPQ1eAcu4ZX3UwxQhUlfFFMNpUd83gXgjbhJh6HmB6LUNV/ieOLQuDwJO3dWJosUeMw==", + "dev": true + }, "is-obj": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", @@ -5058,15 +5298,107 @@ } }, "object.values": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz", - "integrity": "sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA==", + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.3.tgz", + "integrity": "sha512-nkF6PfDB9alkOUxpf1HNm/QlkeW3SReqL5WXeBLpEJJnlPSvRaDQpW3gQTksTN3fgJX4hL42RzKyOin6ff3tyw==", "dev": true, "requires": { + "call-bind": "^1.0.2", "define-properties": "^1.1.3", - "es-abstract": "^1.17.0-next.1", - "function-bind": "^1.1.1", + "es-abstract": "^1.18.0-next.2", "has": "^1.0.3" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz", + "integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "get-intrinsic": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", + "is-negative-zero": "^2.0.1", + "is-regex": "^1.1.2", + "is-string": "^1.0.5", + "object-inspect": "^1.9.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.0" + } + }, + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, + "is-negative-zero": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", + "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", + "dev": true + }, + "is-regex": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz", + "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz", + "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "string.prototype.trimend": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string.prototype.trimstart": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + } } }, "on-finished": { @@ -5873,9 +6205,9 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "semver": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.2.tgz", - "integrity": "sha1-x6BxWKgL7dBSNVt3DYLWZA+AO+c=", + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", "dev": true }, "semver-compare": { @@ -6742,6 +7074,26 @@ "is-typedarray": "^1.0.0" } }, + "unbox-primitive": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", + "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has-bigints": "^1.0.1", + "has-symbols": "^1.0.2", + "which-boxed-primitive": "^1.0.2" + }, + "dependencies": { + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + } + } + }, "unc-path-regex": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", @@ -6972,6 +7324,19 @@ "isexe": "^2.0.0" } }, + "which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "requires": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + } + }, "which-module": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", diff --git a/package.json b/package.json index 72a02ba6..927f4f0d 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "body-parser": "^1.18.2", "chai-uuid": "^1.0.6", "dotenv": "^8.2.0", + "eslint-plugin-simple-import-sort": "^7.0.0", "expect": "^26.4.2", "express": "^4.16.2", "express-async-handler": "^1.1.4", From 811ab59239b1b5c2e4c472eddd64798c5860359f Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 21:30:43 +0100 Subject: [PATCH 30/42] fix more linter errors --- server/repositories/TokenRepository.js | 31 +++++++++++++++----------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/server/repositories/TokenRepository.js b/server/repositories/TokenRepository.js index fe2c6811..62c9500b 100644 --- a/server/repositories/TokenRepository.js +++ b/server/repositories/TokenRepository.js @@ -1,21 +1,26 @@ -const expect = require("expect-runtime"); +const expect = require('expect-runtime'); const knex = require('../database/knex'); const config = require('../../config/config'); -const HttpError = require("../utils/HttpError"); -const BaseRepository = require("./BaseRepository"); -const Session = require("../models/Session"); +const HttpError = require('../utils/HttpError'); +const BaseRepository = require('./BaseRepository'); +const Session = require('../models/Session'); -class TokenRepository extends BaseRepository{ - constructor(session){ - super("token", session); - this._tableName = "token"; +class TokenRepository extends BaseRepository { + constructor(session) { + super('token', session); + this._tableName = 'token'; this._session = session; } - async getById(id){ - const result = await this._session.getDB()(this._tableName).where("id", id) + async getById(id) { + const result = await this._session + .getDB()(this._tableName) + .where('id', id) .first(); - expect(result,() => new HttpError(404, `can not found token by id:${id}`)).match({ + expect( + result, + () => new HttpError(404, `can not found token by id:${id}`), + ).match({ id: expect.any(String), }); return result; @@ -24,14 +29,14 @@ class TokenRepository extends BaseRepository{ /* * select transaction table by transfer id, return matched tokens */ - async getByTransferId(transferId, limit, offset = 0){ + async getByTransferId(transferId, limit, offset = 0) { return await this._session.getDB().raw(` SELECT "token".* FROM "token" JOIN "transaction" ON "token".id = "transaction".token_id WHERE "transaction".transfer_id = ${transferId} LIMIT ${limit} - OFFSET ${offset}`) + OFFSET ${offset}`); } } From ab253e4c4d4eee35c87d413a9373fd65174ca15f Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 21:56:33 +0100 Subject: [PATCH 31/42] update readme --- README.md | 118 +++++++++++++++++++++++++++--------------------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 49f04e27..0a55f219 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,10 @@ - as -#API Documentation +#API Documentation To view the specs for the new API visit https://editor.swagger.io and load the YAML file from /docs/api/spec/treetracker-token-api.yaml - # Getting Started - + ## Project Setup Fork this repository to your account and clone from this forked copy. @@ -17,7 +15,8 @@ Open terminal, navigate to a folder to install this project, and run the below c git clone https://github.com/[YOUR GITHUB USERNAME]/treetracker-wallet-api.git ``` -Install all necessary dependencies: + +Install all necessary dependencies: ``` npm install @@ -37,8 +36,10 @@ cat jwtRS256.key.pub ### Database Setup You can use docker-compose, to start a database. To do that: + 1. download and install docker -2. set your /database/database.json file to be: +2. set your /database/database.json file to be: + ``` { "dev": { @@ -52,16 +53,20 @@ You can use docker-compose, to start a database. To do that: } } ``` + your .env file to have a line ``` DATABASE_URL=postgresql://wallet_user:secret@localhost:5432/wallet_user ``` -3. run ```docker-compose up ``` to run the database (or ```docker-compose up -d``` to run detached) -4. then run migrations + +3. run `docker-compose up ` to run the database (or `docker-compose up -d` to run detached) +4. then run migrations + ``` ./node_modules/db-migrate/bin/db-migrate --env dev up -``` +``` + 5. that's it, your db should be running Don't forget to set PUBLIC_KEY and PRIVATE_KEY as described below. @@ -72,31 +77,15 @@ To connect to the database, we need a user and a database. We can either use the To create a new user (role): -` -CREATE ROLE "username" WITH - LOGIN - SUPERUSER - CREATEDB - CREATEROLE - INHERIT - NOREPLICATION - CONNECTION LIMIT -1; -` +`CREATE ROLE "username" WITH LOGIN SUPERUSER CREATEDB CREATEROLE INHERIT NOREPLICATION CONNECTION LIMIT -1;` To set the password: -` -ALTER USER username WITH PASSWORD 'password'; -` +`ALTER USER username WITH PASSWORD 'password';` To create a new database: -` -CREATE DATABASE dbname - WITH - OWNER = username - ENCODING = 'UTF8'; -` +`CREATE DATABASE dbname WITH OWNER = username ENCODING = 'UTF8';` We recommend setting up your Postgres server/database locally and assigning setting up your environment variables in an .env file in your root repository: @@ -116,12 +105,13 @@ If you are using the postgres user: DATABASE_URL="postgresql://postgres@localhost:5432/[database_name]"; ``` -See the .env.example file for the format and structure. +See the .env.example file for the format and structure. Here are some resources to get started on local database set up and migration: -* https://postgresapp.com -* pgAdmin and DBeaver are great GUI options to use for navigating your local db -* https://www.postgresql.org/docs/9.1/app-pgdump.html + +- https://postgresapp.com +- pgAdmin and DBeaver are great GUI options to use for navigating your local db +- https://www.postgresql.org/docs/9.1/app-pgdump.html Next, create a new wallets schema in your local database. Navigate to the database folder and create a database.json file populated with the credentials for your local server: @@ -138,6 +128,7 @@ Next, create a new wallets schema in your local database. Navigate to the databa } } ``` + To quickly build the necessary tables for your wallets schema, run: ``` @@ -152,28 +143,39 @@ If you have not installed db-migrate globally, while in the database folder, you See here to learn more about db-migrate: https://db-migrate.readthedocs.io/en/latest/ -### Setting up env variables +### Setting up env variables in your .env file you have (you can look at env.example) + ``` ... PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nXXXXXXXXXXXXXXXX\n-----END PUBLIC KEY-----" PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nXXXXXXXXXXXXXXXXXXXXX\n-----END RSA PRIVATE KEY-----" ... ``` -Copy and paste the PUBLIC_KEY and PRIVATE_KEY strings above exactly as is. Then, go to your jwtRS256.key.pub and jwtRS256.key files generated earlier in your config folder and remove all the new lines. Replace the "XXXXX.." with the key codes between the BEGIN PUBLIC KEY and END PUBLIC KEY sections (pasted as a single line) from your respective jwtRS256.key.pub and jwtRS256.key files. **Don't just copy and paste the whole block from these files into these sections since we need to preserve this format with the "\n" injected into the strings here. -## Troubleshooting -If you run into issue: +Copy and paste the PUBLIC_KEY and PRIVATE_KEY strings above exactly as is. Then, go to your jwtRS256.key.pub and jwtRS256.key files generated earlier in your config folder and remove all the new lines. Replace the "XXXXX.." with the key codes between the BEGIN PUBLIC KEY and END PUBLIC KEY sections (pasted as a single line) from your respective jwtRS256.key.pub and jwtRS256.key files. \*\*Don't just copy and paste the whole block from these files into these sections since we need to preserve this format with the "\n" injected into the strings here. + +### We are using linter to keep the project in shape + +if you are using VScode as your IDE, you can set up linter to run on save, which is very handy +you can set it up by going to Preferences > Settings > Workspace > Formatting > Format on Save + +## Troubleshooting + +If you run into issue: + ``` ifError got unwanted exception: function uuid_generate_v4() does not exist ``` + Delete and recreate your wallets schema and then inside your postgres connection in terminal, run to install the required extension ``` -\c +\c CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; ``` + Now re-run the "db-migrate --env dev up" command in your normal terminal in the database directory. Now you should be all set up and ready to go! @@ -182,30 +184,29 @@ Now you should be all set up and ready to go! This project use multiple layer structure to build the whole system. Similar with MVC structure: -![layers](/layers.png "layers") - +![layers](/layers.png 'layers') -* **Protocol layer** +- **Protocol layer** Wallet API offers RESTFul API interace based on HTTP protocol. We use Express to handle all HTTP requests. The Express-routers work like the controller role in MVC, they receive the requests and parameters from client, and translate it and dispatch tasks to appropriate business objects. Then receive the result from them, translate to the 'view', the JSON response, to client. -* **Service layer** +- **Service layer** -Both service layer and model layer are where all the business logic is located. Comparing to the Model , `service` object don't have state (stateless). +Both service layer and model layer are where all the business logic is located. Comparing to the Model , `service` object don't have state (stateless). Please put business logic code into service object when it is hard to put them into the `Model` object. Because we didn't use Factory or dependency injection to create object, so service layer also can be used as Factory to create `model` object. -* **Model layer** +- **Model layer** -The business model, major business logic is here. They are real object, in the perspective of object oriented programming: they have states, they have the method to do stuff. +The business model, major business logic is here. They are real object, in the perspective of object oriented programming: they have states, they have the method to do stuff. There are more discussion about this, check below selection. -* **Repository layer** +- **Repository layer** Repository is responsible for communicate with the real database, this isolation brings flexibility for us, for example, we can consider replace the implementation of the storage infrastructure in the future. @@ -233,9 +234,9 @@ Because we are not using ORM (Object Relationship Mapping) and not using object Thanks Knex, we can use it to easily retrieve objects from SQL DB, but they are simple value object, not model. -So the trade-off way we are using is building model object JUST with the identity (e.g. primary key), but don't have any other properties, if we want to visit them, require the DB(repository) at the moment. +So the trade-off way we are using is building model object JUST with the identity (e.g. primary key), but don't have any other properties, if we want to visit them, require the DB(repository) at the moment. -In some case, to reduce the traffic to the DB, model can cache the JSON object from DB by contructor the model object with it. In this case, the outside code which is using this model should be responsible for keep the cached JSON (in model object) consistent with the DB status. +In some case, to reduce the traffic to the DB, model can cache the JSON object from DB by contructor the model object with it. In this case, the outside code which is using this model should be responsible for keep the cached JSON (in model object) consistent with the DB status. ### Seting up DB transaction @@ -257,7 +258,7 @@ try{ const tokens = []; const tokenService = new TokenService(session); for(let uuid of req.body.tokens){ - const token = await tokenService.getByUUID(uuid); + const token = await tokenService.getByUUID(uuid); tokens.push(token); } result = await walletLogin.transfer(walletSender, walletReceiver, tokens); @@ -269,7 +270,7 @@ try{ if(result.state === Transfer.STATE.completed){ res.status(201).json(result); }else if( - result.state === Transfer.STATE.pending || + result.state === Transfer.STATE.pending || result.state === Transfer.STATE.requested){ res.status(202).json(result); }else{ @@ -292,16 +293,15 @@ try{ By wrapping all the code in a try/catch block, if everything goes well, when the code reach to the line `await session.commitTransaction()`, all those changing happned in this code block would be commited to DB. If somthine went wrong, there are three cases: -1. If this is a unkown error, for example, the DB lib thrown something like: connection to DB is broken, then the transaction would rollback to the start point. +1. If this is a unkown error, for example, the DB lib thrown something like: connection to DB is broken, then the transaction would rollback to the start point. 2. If this is a error thrown by ourselves, we can chose to commit or rollback by setting the flag in HttpError: - ``` throw new HttpError(403, `the token:${json.uuid} do not belongs to sender walleter`, true); ``` -The third parameter `true` means please rollback. (This is the default case for HttpError); +The third parameter `true` means please rollback. (This is the default case for HttpError); 3. If set the HttpError's `toRollback` (the third parameter) to false, then, the transaction would commit anyway. @@ -322,7 +322,7 @@ someService = { } ``` -There are two way to compose object, Class or direct literal object in Javascript, this project we suggest use Class to build object, like: model, service, repository, even though they are stateless objects. This is because generally to say, Class brings more flexibility for future choices, all the things literal object and do, Class can do it too, but literal object can not do all the things Class can do. +There are two way to compose object, Class or direct literal object in Javascript, this project we suggest use Class to build object, like: model, service, repository, even though they are stateless objects. This is because generally to say, Class brings more flexibility for future choices, all the things literal object and do, Class can do it too, but literal object can not do all the things Class can do. One things should be considered in future is the database transaction, if we use Class and create new instance ever time, then it's possible for us to pass the transition session object into the object to do things in a database transaction session. @@ -338,9 +338,9 @@ throw new HttpError(403, 'Do not have permission to do this operation...'); The protocol layer would catch the object and return to client with this response: -* Status code: 403 +- Status code: 403 -* Response body: +- Response body: ``` { @@ -391,7 +391,7 @@ log.debug("..."); log.info("..."); ``` -* The default log level +- The default log level The default log level is `info`, the change it temporarily, when developing, set the env: `NODE_LOG_LEVEL`, for example: @@ -424,6 +424,7 @@ npm run test-integration ``` ## Database seeding test + In order to efficiently run our integration tests, we rely on automated database seeding/clearing functions to mock database entries. To test these functions, run: ``` @@ -504,13 +505,12 @@ Chai is not good for testing/catching errors throwing from internal stack. We ar }).rejects.toThrow(/can not find entity/); ``` - # Contributing Create your local git branch and rebase it from the shared master branch. Please make sure to 1) npm install and 2) delete and rebuild your local database wallet schema using the migrations (as illustrated in the Database Setup section above) to capture any latest updates/changes. Please follow this convention for commit messages [here](https://www.conventionalcommits.org/en/v1.0.0/) -Any developers joining the project should feel free to review any outstanding pull requests and assign themselves to any open tickets on the Issues list. You can make a draft pull request as you are working on any open issue that interests you, and any changes you make on your local branch can be continually synced with this draft until you are ready to submit. Remember to push your changes up to your forked repository and then make any pull requests from your forked branch to the Greenstand master repository branch. +Any developers joining the project should feel free to review any outstanding pull requests and assign themselves to any open tickets on the Issues list. You can make a draft pull request as you are working on any open issue that interests you, and any changes you make on your local branch can be continually synced with this draft until you are ready to submit. Remember to push your changes up to your forked repository and then make any pull requests from your forked branch to the Greenstand master repository branch. -When you are ready to submit a pull request, please rebase your branch off of the shared master branch again to integrate any new updates in the codebase before submitting. +When you are ready to submit a pull request, please rebase your branch off of the shared master branch again to integrate any new updates in the codebase before submitting. From b3d55b8a63652b998481edba31da60d8f560854c Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 21:58:37 +0100 Subject: [PATCH 32/42] turn linter back on --- .../workflows/treetracker-wallet-api-pull-request-ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/treetracker-wallet-api-pull-request-ci.yml b/.github/workflows/treetracker-wallet-api-pull-request-ci.yml index ee5f39e3..5ff6db15 100644 --- a/.github/workflows/treetracker-wallet-api-pull-request-ci.yml +++ b/.github/workflows/treetracker-wallet-api-pull-request-ci.yml @@ -42,9 +42,9 @@ jobs: - name: npm clean install run: npm ci working-directory: ${{ env.project-directory }} - #- name: run ESLint - # run: npm run lint - #working-directory: ${{ env.project-directory }} + - name: run ESLint + run: npm run lint + working-directory: ${{ env.project-directory }} - name: run db-migrate run: npm run db-migrate-ci From f5b76e215f493bd78702d7fb1c6a9e97b6ff543e Mon Sep 17 00:00:00 2001 From: zo-chu Date: Tue, 6 Apr 2021 22:03:18 +0100 Subject: [PATCH 33/42] fix indentation in yaml --- ...treetracker-wallet-api-pull-request-ci.yml | 71 ++++++++++--------- 1 file changed, 36 insertions(+), 35 deletions(-) diff --git a/.github/workflows/treetracker-wallet-api-pull-request-ci.yml b/.github/workflows/treetracker-wallet-api-pull-request-ci.yml index 5ff6db15..f1368891 100644 --- a/.github/workflows/treetracker-wallet-api-pull-request-ci.yml +++ b/.github/workflows/treetracker-wallet-api-pull-request-ci.yml @@ -8,7 +8,7 @@ on: branches: - master -env: +env: project-directory: ./ jobs: @@ -34,41 +34,42 @@ jobs: --health-retries 5 steps: - - uses: actions/checkout@v2 - - name: Use Node.js 12.x - uses: actions/setup-node@v1 - with: - node-version: '12.x' - - name: npm clean install - run: npm ci - working-directory: ${{ env.project-directory }} + - uses: actions/checkout@v2 + - name: Use Node.js 12.x + uses: actions/setup-node@v1 + with: + node-version: '12.x' + - name: npm clean install + run: npm ci + working-directory: ${{ env.project-directory }} + - name: run ESLint - run: npm run lint - working-directory: ${{ env.project-directory }} + run: npm run lint + working-directory: ${{ env.project-directory }} + + - name: run db-migrate + run: npm run db-migrate-ci + working-directory: ${{ env.project-directory }} + env: + DATABASE_URL: postgresql://postgres:postgres@postgres/postgres - - name: run db-migrate - run: npm run db-migrate-ci - working-directory: ${{ env.project-directory }} - env: - DATABASE_URL: postgresql://postgres:postgres@postgres/postgres + - name: run unit tests + run: npm run test-unit-ci + working-directory: ${{ env.project-directory }} + env: + DATABASE_URL: postgresql://postgres:postgres@postgres/postgres + CI: true - - name: run unit tests - run: npm run test-unit-ci - working-directory: ${{ env.project-directory }} - env: - DATABASE_URL: postgresql://postgres:postgres@postgres/postgres - CI: true - - - name: run integration tests - run: npm run test-integration-ci - working-directory: ${{ env.project-directory }} - env: - DATABASE_URL: postgresql://postgres:postgres@postgres/postgres - CI: true + - name: run integration tests + run: npm run test-integration-ci + working-directory: ${{ env.project-directory }} + env: + DATABASE_URL: postgresql://postgres:postgres@postgres/postgres + CI: true - - name: run repository tests - run: npm run test-repository - working-directory: ${{ env.project-directory }} - env: - DATABASE_URL: postgresql://postgres:postgres@postgres/postgres - CI: true + - name: run repository tests + run: npm run test-repository + working-directory: ${{ env.project-directory }} + env: + DATABASE_URL: postgresql://postgres:postgres@postgres/postgres + CI: true From bc89858e2bae0f8373c66a7c2ca8d4ae1c911c32 Mon Sep 17 00:00:00 2001 From: Zaven Arra Date: Thu, 8 Apr 2021 18:30:48 -0700 Subject: [PATCH 34/42] chore: scripts --- scripts/create/create-tokens-csv.js | 2 +- scripts/demo/create-demo-wallet.js | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/scripts/create/create-tokens-csv.js b/scripts/create/create-tokens-csv.js index 333a3adf..791f2461 100644 --- a/scripts/create/create-tokens-csv.js +++ b/scripts/create/create-tokens-csv.js @@ -18,7 +18,7 @@ function getRandomArbitrary(min, max) { const targetWallet = 'GreenstandEscrow' const csvFile = './GS_Not_Owned_20210313.csv' - const dryRun = false + const dryRun = true const trx = await knex.transaction(); diff --git a/scripts/demo/create-demo-wallet.js b/scripts/demo/create-demo-wallet.js index e849532c..eb3a0755 100644 --- a/scripts/demo/create-demo-wallet.js +++ b/scripts/demo/create-demo-wallet.js @@ -79,9 +79,14 @@ function getRandomArbitrary(min, max) { 'https://treetracker-dev.nyc3.digitaloceanspaces.com/2018.06.19.18.20.59_5559d3ad-9090-4456-a81e-00a7653483c0_IMG_20180619_142743_1430885612.jpg' ] + const planterImages = [ + 'https://treetracker-production-images.s3.eu-central-1.amazonaws.com/2020.11.19.15.23.46_8.42080836_-13.17032878_3c58d106-1893-493c-986b-061f66009b5a_IMG_20201118_110629_7276172223528929867.jpg', + 'https://treetracker-production-images.s3.eu-central-1.amazonaws.com/2020.11.17.12.45.48_8.42419553_-13.16719857_11d157fb-1bb0-4497-a7d7-7c16ce658158_IMG_20201117_104118_1916638584657622896.jpg' + ] + // insert fake tree captures let trees = [] - for(i=0; i<5000; i++){ + for(i=0; i<1000; i++){ const captureData = { time_created: new Date(), time_updated: new Date(), @@ -89,6 +94,7 @@ function getRandomArbitrary(min, max) { lat: getRandomArbitrary(-15,0), lon: getRandomArbitrary(15,35), image_url: images[Math.floor(getRandomArbitrary(1,9.99))], + planter_photo_url: planterImages[Math.floor(getRandomArbitrary(1,1.99))], uuid: uuidv4(), approved: true, } From 2ee2c78b5b9622d0d6d047c9a3dcb6804a2c612b Mon Sep 17 00:00:00 2001 From: zo-chu Date: Mon, 12 Apr 2021 23:00:27 +0100 Subject: [PATCH 35/42] fix new linting errors --- scripts/create/create-tokens-csv.js | 4 ---- scripts/demo/create-demo-wallet.js | 15 +++++---------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/scripts/create/create-tokens-csv.js b/scripts/create/create-tokens-csv.js index 0e01cb0e..84f6b0a0 100644 --- a/scripts/create/create-tokens-csv.js +++ b/scripts/create/create-tokens-csv.js @@ -19,10 +19,6 @@ function getRandomArbitrary(min, max) { const csvFile = './GS_Not_Owned_20210313.csv'; const dryRun = true; - const targetWallet = 'GreenstandEscrow'; - const csvFile = './GS_Not_Owned_20210313.csv'; - const dryRun = false; - const trx = await knex.transaction(); try { diff --git a/scripts/demo/create-demo-wallet.js b/scripts/demo/create-demo-wallet.js index e53ab605..61ae1462 100644 --- a/scripts/demo/create-demo-wallet.js +++ b/scripts/demo/create-demo-wallet.js @@ -15,13 +15,12 @@ function getRandomArbitrary(min, max) { const Crypto = require('crypto'); const sha512 = function (password, salt) { - var hash = Crypto.createHmac( + const hash = Crypto.createHmac( 'sha512', salt, ); /** Hashing algorithm sha512 */ hash.update(password); - var value = hash.digest('hex'); - return value; + return hash.digest('hex'); }; const username = faker.internet.userName(); @@ -51,7 +50,7 @@ function getRandomArbitrary(min, max) { .insert({ name: username, password: passwordHash, - salt: salt, + salt, }) .returning('*'); const wallet = result[0]; @@ -88,8 +87,8 @@ function getRandomArbitrary(min, max) { ]; // insert fake tree captures - let trees = []; - for (i = 0; i < 1000; i++) { + const trees = []; + for (let i = 0; i < 1000; i++) { const captureData = { time_created: new Date(), time_updated: new Date(), @@ -131,10 +130,6 @@ function getRandomArbitrary(min, max) { knex.destroy(); - console.log('wallet ' + username); - console.log('password ' + password); - console.log('apiKey ' + apiKey); - console.log(`wallet ${username}`); console.log(`password ${password}`); console.log(`apiKey ${apiKey}`); From 50052d205043f80aff46842e767bbd9999029bc6 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Mon, 12 Apr 2021 23:12:37 +0100 Subject: [PATCH 36/42] fix 10000 api limit to be 1000 --- server/routes/trustRouter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index 9ad7b27c..24819326 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -23,7 +23,7 @@ trustRouter.get( type: Joi.string(), request_type: Joi.string(), offset: Joi.number().min(0).default(0).integer(), - limit: Joi.number().min(1).max(10000).integer().default(1000), + limit: Joi.number().min(1).max(1000).integer().default(1000), }), ); Joi.assert( From 4dad0091ecee1e0c1bcf024f3e950ef583b08c7d Mon Sep 17 00:00:00 2001 From: zo-chu Date: Wed, 14 Apr 2021 21:17:34 +0100 Subject: [PATCH 37/42] erase unused vars around code change --- server/routes/trustRouter.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/server/routes/trustRouter.js b/server/routes/trustRouter.js index 24819326..e6fd7394 100644 --- a/server/routes/trustRouter.js +++ b/server/routes/trustRouter.js @@ -1,12 +1,9 @@ const express = require('express'); const trustRouter = express.Router(); -const { check, validationResult } = require('express-validator'); -const assert = require('assert'); const Joi = require('joi'); const WalletService = require('../services/WalletService'); const TrustService = require('../services/TrustService'); -const Wallet = require('../models/Wallet'); const helper = require('./utils'); const Session = require('../models/Session'); const TrustRelationship = require('../models/TrustRelationship'); @@ -15,7 +12,7 @@ trustRouter.get( '/', helper.apiKeyHandler, helper.verifyJWTHandler, - helper.handlerWrapper(async (req, res, next) => { + helper.handlerWrapper(async (req, res) => { Joi.assert( req.query, Joi.object({ From 7ca6eae539b094312a383a679b783ad323f0ba36 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Wed, 14 Apr 2021 21:22:17 +0100 Subject: [PATCH 38/42] yarn test pre-commit hook --- .huskyrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.huskyrc b/.huskyrc index 80a43e4d..41023fbd 100644 --- a/.huskyrc +++ b/.huskyrc @@ -1 +1 @@ -{"hooks":{"commit-msg":"commitlint -E HUSKY_GIT_PARAMS"}} +{"hooks":{"commit-msg":"commitlint -E HUSKY_GIT_PARAMS", "lint": "yarn lint"}} From 52bfc3792193a457e12faba0ac43fba515004e5a Mon Sep 17 00:00:00 2001 From: zo-chu Date: Wed, 14 Apr 2021 21:24:48 +0100 Subject: [PATCH 39/42] test --- .huskyrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.huskyrc b/.huskyrc index 41023fbd..9813b6b6 100644 --- a/.huskyrc +++ b/.huskyrc @@ -1 +1 @@ -{"hooks":{"commit-msg":"commitlint -E HUSKY_GIT_PARAMS", "lint": "yarn lint"}} +{"hooks":{"lint": "yarn lint", "commit-msg":"commitlint -E HUSKY_GIT_PARAMS" }} From c0c05d87c30412fb12194641b32ebe08af8056c0 Mon Sep 17 00:00:00 2001 From: zo-chu Date: Wed, 14 Apr 2021 21:28:40 +0100 Subject: [PATCH 40/42] run lint as pre- commit --- .huskyrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.huskyrc b/.huskyrc index 9813b6b6..6ac0557e 100644 --- a/.huskyrc +++ b/.huskyrc @@ -1 +1 @@ -{"hooks":{"lint": "yarn lint", "commit-msg":"commitlint -E HUSKY_GIT_PARAMS" }} +{"hooks":{"pre-commit": "npm run lint", "commit-msg":"commitlint -E HUSKY_GIT_PARAMS" }} From e3656f55f3bbc2b9f98d44af29e8ac258cffda2f Mon Sep 17 00:00:00 2001 From: zo-chu Date: Wed, 14 Apr 2021 21:44:52 +0100 Subject: [PATCH 41/42] fix: downgraded husky version to support node-run env required by IDEs --- package-lock.json | 310 +++++++++++++++++++++++++++++++++++++++------- package.json | 2 +- 2 files changed, 269 insertions(+), 43 deletions(-) diff --git a/package-lock.json b/package-lock.json index 922ae92d..3a269a34 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.12.1", + "version": "1.12.4", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -1422,6 +1422,32 @@ "get-intrinsic": "^1.0.2" } }, + "caller-callsite": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/caller-callsite/-/caller-callsite-2.0.0.tgz", + "integrity": "sha1-hH4PzgoiN1CpoCfFSzNzGtMVQTQ=", + "dev": true, + "requires": { + "callsites": "^2.0.0" + }, + "dependencies": { + "callsites": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-2.0.0.tgz", + "integrity": "sha1-BuuE8A7qQT2oav/vrL/7Ngk7PFA=", + "dev": true + } + } + }, + "caller-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-2.0.0.tgz", + "integrity": "sha1-Ro+DBE42mrIBD6xfBs7uFbsssfQ=", + "dev": true, + "requires": { + "caller-callsite": "^2.0.0" + } + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -1682,12 +1708,6 @@ "dot-prop": "^5.1.0" } }, - "compare-versions": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.6.0.tgz", - "integrity": "sha512-W6Af2Iw1z4CB7q4uU4hv646dW9GQuBM+YpC0UvUCWSD8w90SJjp+ujJuXaEMtAXBtSqGfMPuFOVn4/+FlaqfBA==", - "dev": true - }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", @@ -2733,6 +2753,57 @@ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" }, + "execa": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "dev": true, + "requires": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + } + } + }, "expand-brackets": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", @@ -3083,15 +3154,6 @@ "path-exists": "^4.0.0" } }, - "find-versions": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/find-versions/-/find-versions-3.2.0.tgz", - "integrity": "sha512-P8WRou2S+oe222TOCHitLy8zj+SIsVJh52VP4lvXkaFVnOFFdoWv1H1Jjvel1aI6NCFOAaeAVm8qrI0odiLcww==", - "dev": true, - "requires": { - "semver-regex": "^2.0.0" - } - }, "findup-sync": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-3.0.0.tgz", @@ -3495,33 +3557,77 @@ } }, "husky": { - "version": "4.3.5", - "resolved": "https://registry.npmjs.org/husky/-/husky-4.3.5.tgz", - "integrity": "sha512-E5S/1HMoDDaqsH8kDF5zeKEQbYqe3wL9zJDyqyYqc8I4vHBtAoxkDBGXox0lZ9RI+k5GyB728vZdmnM4bYap+g==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/husky/-/husky-3.1.0.tgz", + "integrity": "sha512-FJkPoHHB+6s4a+jwPqBudBDvYZsoQW5/HBuMSehC8qDiCe50kpcxeqFoDSlow+9I6wg47YxBoT3WxaURlrDIIQ==", "dev": true, "requires": { - "chalk": "^4.0.0", + "chalk": "^2.4.2", "ci-info": "^2.0.0", - "compare-versions": "^3.6.0", - "cosmiconfig": "^7.0.0", - "find-versions": "^3.2.0", + "cosmiconfig": "^5.2.1", + "execa": "^1.0.0", + "get-stdin": "^7.0.0", "opencollective-postinstall": "^2.0.2", "pkg-dir": "^4.2.0", "please-upgrade-node": "^3.2.0", - "slash": "^3.0.0", - "which-pm-runs": "^1.0.0" + "read-pkg": "^5.2.0", + "run-node": "^1.0.0", + "slash": "^3.0.0" }, "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, "chalk": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", - "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" } }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "cosmiconfig": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-5.2.1.tgz", + "integrity": "sha512-H65gsXo1SKjf8zmrJ67eJk8aIRKV5ff2D4uKZIBZShbhGSpEmsQOPW/SKMKYhSTrqR7ufy6RP69rPogdaPh/kA==", + "dev": true, + "requires": { + "import-fresh": "^2.0.0", + "is-directory": "^0.3.1", + "js-yaml": "^3.13.1", + "parse-json": "^4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, "find-up": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", @@ -3532,6 +3638,22 @@ "path-exists": "^4.0.0" } }, + "get-stdin": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-7.0.0.tgz", + "integrity": "sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ==", + "dev": true + }, + "import-fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-2.0.0.tgz", + "integrity": "sha1-2BNVwVYS04bGH53dOSLUMEgipUY=", + "dev": true, + "requires": { + "caller-path": "^2.0.0", + "resolve-from": "^3.0.0" + } + }, "locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -3559,6 +3681,16 @@ "p-limit": "^2.2.0" } }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, "pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -3567,6 +3699,53 @@ "requires": { "find-up": "^4.0.0" } + }, + "read-pkg": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", + "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", + "dev": true, + "requires": { + "@types/normalize-package-data": "^2.4.0", + "normalize-package-data": "^2.5.0", + "parse-json": "^5.0.0", + "type-fest": "^0.6.0" + }, + "dependencies": { + "parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + } + } + }, + "resolve-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", + "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "type-fest": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", + "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", + "dev": true } } }, @@ -3778,6 +3957,12 @@ } } }, + "is-directory": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/is-directory/-/is-directory-0.3.1.tgz", + "integrity": "sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE=", + "dev": true + }, "is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", @@ -3901,6 +4086,12 @@ "is-unc-path": "^1.0.0" } }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, "is-string": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz", @@ -4158,6 +4349,12 @@ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.0.tgz", "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=" }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, "json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -5070,6 +5267,12 @@ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, "nise": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/nise/-/nise-4.0.4.tgz", @@ -5176,6 +5379,23 @@ "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.0.tgz", "integrity": "sha512-2s47yzUxdexf1OhyRi4Em83iQk0aPvwTddtFz4hnSSw9dCEsLEGf6SwIO8ss/19S9iBb5sJaOuTvTGDeZI00BQ==" }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, + "requires": { + "path-key": "^2.0.0" + }, + "dependencies": { + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + } + } + }, "object-copy": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", @@ -5447,6 +5667,12 @@ "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==" }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, "p-limit": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.0.2.tgz", @@ -6186,6 +6412,12 @@ "glob": "^7.1.3" } }, + "run-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/run-node/-/run-node-1.0.0.tgz", + "integrity": "sha512-kc120TBlQ3mih1LSzdAJXo4xn/GWS2ec0l3S+syHDXP9uRr0JAT8Qd3mdMuyjqCzeZktgP3try92cEgf9Nks8A==", + "dev": true + }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -6231,12 +6463,6 @@ } } }, - "semver-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/semver-regex/-/semver-regex-2.0.0.tgz", - "integrity": "sha512-mUdIBBvdn0PLOeP3TEkMH7HHeUP3GjsXCwKarjv/kGmUFOYg1VqEemKhoQpWMu6X2I8kHeuVdGibLGkVK+/5Qw==", - "dev": true - }, "send": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", @@ -6777,6 +7003,12 @@ "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", "dev": true }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, "strip-indent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", @@ -7343,12 +7575,6 @@ "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, - "which-pm-runs": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.0.0.tgz", - "integrity": "sha1-Zws6+8VS4LVd9rd4DKdGFfI60cs=", - "dev": true - }, "wide-align": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", diff --git a/package.json b/package.json index a7ac8b9e..6b8ba471 100644 --- a/package.json +++ b/package.json @@ -69,7 +69,7 @@ "eslint-plugin-prettier": "^3.2.0", "expect-runtime": "^0.7.0", "generate-password": "^1.6.0", - "husky": "^4.3.5", + "husky": "^3.1.0", "mock-knex": "^0.4.9", "prettier": "^2.1.2", "sinon": "^9.0.3", From ff895cb7f560d16383688196543725250f076601 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 16 Apr 2021 02:08:41 +0000 Subject: [PATCH 42/42] chore(release): 1.12.5 [skip ci] --- CHANGELOG.md | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b5e83c5..c74a6e38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [1.12.5](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.4...v1.12.5) (2021-04-16) + + +### Bug Fixes + +* downgraded husky version to support node-run env required by IDEs ([e3656f5](https://github.com/Greenstand/treetracker-wallet-api/commit/e3656f55f3bbc2b9f98d44af29e8ac258cffda2f)) + ## [1.12.4](https://github.com/Greenstand/treetracker-wallet-api/compare/v1.12.3...v1.12.4) (2021-04-03) diff --git a/package.json b/package.json index 6b8ba471..fd4741e9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "treetracker", - "version": "1.12.4", + "version": "1.12.5", "description": "https://documenter.getpostman.com/view/10112806/SWTD8H5x?version=latest", "private": true, "main": "server/server.js",