From f690cd852401b038e1b2b1f61f10741c92a9911e Mon Sep 17 00:00:00 2001 From: Igor Kamyshev Date: Sat, 2 Mar 2019 21:43:39 +0200 Subject: [PATCH] feat(converter): add more solidity to cinversation --- .../money/application/CurrencyConverter.ts | 41 +++++++++++-------- .../money/domain/ExchangeRateRepository.ts | 11 +++++ 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/back/src/money/application/CurrencyConverter.ts b/back/src/money/application/CurrencyConverter.ts index fd848f35..01746ec5 100644 --- a/back/src/money/application/CurrencyConverter.ts +++ b/back/src/money/application/CurrencyConverter.ts @@ -7,6 +7,7 @@ import { Currency } from '@shared/enum/Currency' import { ExchangeRate } from '../domain/ExchangeRate.entity' import { ExchangeRateRepository } from '../domain/ExchangeRateRepository' import { ExchangeRateApi } from '../insfrastructure/ExchangeRateApi' +import { Option } from 'tsoption' @Injectable() export class CurrencyConverter { @@ -16,6 +17,14 @@ export class CurrencyConverter { private readonly entitySaver: EntitySaver, ) {} + public async convertApproximately( + from: Currency, + to: Currency, + amount: number, + ): Promise { + return 0 + } + public async convert( from: Currency, to: Currency, @@ -28,22 +37,22 @@ export class CurrencyConverter { const normalizedDate = startOfHour(when) - const rate = await this.getExchangeRate(from, to, normalizedDate).catch( - async e => { - // if correct rate getting failed, we can return the closest available rate - const closestRate = await this.exchangeRateRepo.findClosest( - from, - to, - normalizedDate, - ) - - if (closestRate.nonEmpty()) { - return closestRate.get().rate - } - - throw e - }, - ) + const tryTo = (promiseRate: Promise>) => async ( + e: Error, + ) => { + const optionalRate = await promiseRate + + if (optionalRate.nonEmpty()) { + return optionalRate.get().rate + } + + throw e + } + + const rate = await this.getExchangeRate(from, to, normalizedDate) + .catch(tryTo(this.exchangeRateRepo.findClosest(from, to, normalizedDate))) + .catch(() => this.fetchExchangeRate(from, to, new Date())) + .catch(tryTo(this.exchangeRateRepo.findLast(from, to))) return Math.round(amount * rate) } diff --git a/back/src/money/domain/ExchangeRateRepository.ts b/back/src/money/domain/ExchangeRateRepository.ts index fb45ed74..2f6826f8 100644 --- a/back/src/money/domain/ExchangeRateRepository.ts +++ b/back/src/money/domain/ExchangeRateRepository.ts @@ -31,6 +31,17 @@ class ExchangeRateRepo { .then(this.toOption) } + public async findLast( + from: Currency, + to: Currency, + ): Promise> { + return this.createFromToQueryBuilder('rate') + .orderBy('rate.collectAt', 'DESC') + .setParameters({ from, to }) + .getOne() + .then(this.toOption) + } + public async findClosest( from: Currency, to: Currency,