Skip to content
This repository has been archived by the owner on May 11, 2021. It is now read-only.

Commit

Permalink
feat(converter): add more solidity to cinversation
Browse files Browse the repository at this point in the history
  • Loading branch information
igorkamyshev committed Mar 2, 2019
1 parent 291f91e commit f690cd8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
41 changes: 25 additions & 16 deletions back/src/money/application/CurrencyConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -16,6 +17,14 @@ export class CurrencyConverter {
private readonly entitySaver: EntitySaver,
) {}

public async convertApproximately(
from: Currency,
to: Currency,
amount: number,
): Promise<number> {
return 0
}

public async convert(
from: Currency,
to: Currency,
Expand All @@ -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<Option<ExchangeRate>>) => 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)
}
Expand Down
11 changes: 11 additions & 0 deletions back/src/money/domain/ExchangeRateRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ class ExchangeRateRepo {
.then(this.toOption)
}

public async findLast(
from: Currency,
to: Currency,
): Promise<Option<ExchangeRate>> {
return this.createFromToQueryBuilder('rate')
.orderBy('rate.collectAt', 'DESC')
.setParameters({ from, to })
.getOne()
.then(this.toOption)
}

public async findClosest(
from: Currency,
to: Currency,
Expand Down

0 comments on commit f690cd8

Please sign in to comment.