|
| 1 | +package com.baeldung.ddd.order.config; |
| 2 | + |
| 3 | +import org.bson.Document; |
| 4 | +import org.joda.money.CurrencyUnit; |
| 5 | +import org.joda.money.Money; |
| 6 | +import org.springframework.context.annotation.Bean; |
| 7 | +import org.springframework.context.annotation.Configuration; |
| 8 | +import org.springframework.core.convert.converter.Converter; |
| 9 | +import org.springframework.data.convert.ReadingConverter; |
| 10 | +import org.springframework.data.mongodb.core.convert.MongoCustomConversions; |
| 11 | + |
| 12 | +import java.math.BigDecimal; |
| 13 | +import java.util.Collections; |
| 14 | + |
| 15 | +@Configuration |
| 16 | +public class CustomMongoConfiguration { |
| 17 | + |
| 18 | + @Bean |
| 19 | + public MongoCustomConversions customConversions() { |
| 20 | + return new MongoCustomConversions(Collections.singletonList(DocumentToMoneyConverter.INSTANCE)); |
| 21 | + } |
| 22 | + |
| 23 | + @ReadingConverter |
| 24 | + enum DocumentToMoneyConverter implements Converter<Document, Money> { |
| 25 | + |
| 26 | + INSTANCE; |
| 27 | + |
| 28 | + @Override |
| 29 | + public Money convert(Document source) { |
| 30 | + Document money = source.get("money", Document.class); |
| 31 | + |
| 32 | + return Money.of(getCurrency(money), getAmount(money)); |
| 33 | + } |
| 34 | + |
| 35 | + private CurrencyUnit getCurrency(Document money) { |
| 36 | + Document currency = money.get("currency", Document.class); |
| 37 | + String currencyCode = currency.getString("code"); |
| 38 | + return CurrencyUnit.of(currencyCode); |
| 39 | + } |
| 40 | + |
| 41 | + private BigDecimal getAmount(Document money) { |
| 42 | + String amount = money.getString("amount"); |
| 43 | + return BigDecimal.valueOf(Double.parseDouble(amount)); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments