Skip to content

Instantly share code, notes, and snippets.

@jeroenr
Last active July 8, 2021 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenr/e1cf7881eebe276140af5908b59fcc90 to your computer and use it in GitHub Desktop.
Save jeroenr/e1cf7881eebe276140af5908b59fcc90 to your computer and use it in GitHub Desktop.
Example of service with many dependencies
@Service
class DepositService(
val userRepo: UserRepository,
val userAccountRepo: UserAccountRepository,
val exchangeApiClient: ExchangeApiClient,
val eventBus: EventBus
) {
@Transactional
fun deposit(userId: String, amount: BigDecimal, currency: String){
require(amount > BigDecimal.ZERO) { “Amount must be larger than 0” }
require(Currencies.isSupported(currency)) { “$currency is not supported”}
userRepo.findById(userId)?.let { user ->
userAccountRepo.findByAccountId(user.accountId)?.let { account ->
val rateToUsd = if (currency != “USD”) {
exchangeApiClient.getRate(RateRequest(currency, “USD”)).rate
} else { 1.0 }
val rateToPref = if (account.currency != “USD”) {
exchangeApiClient.getRate(RateRequest(“USD”, account.currency)).rate
} else { 1.0 }
val oldBalance = account.balance
account.balance += amount * rateToUsd.toBigDecimal() * rateToPref.toBigDecimal()
userAccountRepo.save(account)
val update = BalanceUpdate(
userId, oldBalance, account.balance
)
eventBus.publish(ProducerRecord(“balance-updates”, update))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment