From ddf24163b409d58110b76533b354d8ca3c126d4f Mon Sep 17 00:00:00 2001 From: Valentin Zickner Date: Thu, 8 Jul 2021 19:28:44 +0200 Subject: [PATCH] optimize database query execution for portfolio chart --- apps/api/src/app/core/portfolio-calculator.ts | 67 ++++++++++--------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/apps/api/src/app/core/portfolio-calculator.ts b/apps/api/src/app/core/portfolio-calculator.ts index 2804388a..c37a91f3 100644 --- a/apps/api/src/app/core/portfolio-calculator.ts +++ b/apps/api/src/app/core/portfolio-calculator.ts @@ -142,7 +142,7 @@ export class PortfolioCalculator { const start = dparse(startDate); const end = dparse(endDate); - const timelinePeriod: TimelinePeriod[] = []; + const timelinePeriodPromises: Promise[] = []; let i = 0; let j = -1; for ( @@ -162,40 +162,47 @@ export class PortfolioCalculator { ) { j++; } - - let investment: Big = new Big(0); - const promises = []; - if (j >= 0) { - for (const item of this.transactionPoints[j].items) { - investment = investment.add(item.investment); - promises.push( - this.currentRateService - .getValue({ - date: currentDate, - symbol: item.symbol, - currency: item.currency, - userCurrency: this.currency - }) - .then((v) => new Big(v).mul(item.quantity)) - ); - } - } - - const value = (await Promise.all(promises)).reduce( - (a, b) => a.add(b), - new Big(0) - ); - timelinePeriod.push({ - date: format(currentDate, DATE_FORMAT), - grossPerformance: value.minus(investment), - investment, - value - }); + timelinePeriodPromises.push(this.getTimePeriodForDate(j, currentDate)); } + const timelinePeriod: TimelinePeriod[] = await Promise.all( + timelinePeriodPromises + ); + return timelinePeriod; } + private async getTimePeriodForDate(j: number, currentDate: Date) { + let investment: Big = new Big(0); + const promises = []; + if (j >= 0) { + for (const item of this.transactionPoints[j].items) { + investment = investment.add(item.investment); + promises.push( + this.currentRateService + .getValue({ + date: currentDate, + symbol: item.symbol, + currency: item.currency, + userCurrency: this.currency + }) + .then((v) => new Big(v).mul(item.quantity)) + ); + } + } + + const value = (await Promise.all(promises)).reduce( + (a, b) => a.add(b), + new Big(0) + ); + return { + date: format(currentDate, DATE_FORMAT), + grossPerformance: value.minus(investment), + investment, + value + }; + } + private getFactor(type: OrderType) { let factor: number; switch (type) {