-
Notifications
You must be signed in to change notification settings - Fork 12
/
currency_rates_repository.go
69 lines (58 loc) · 1.78 KB
/
currency_rates_repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package repository
import (
"errors"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/utils"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-postgres-repository/entity"
"gorm.io/gorm"
"time"
)
type currencyRateRepo struct {
db *gorm.DB
}
type CurrencyRateRepository interface {
GetLatestCurrencyRate(currency string) (*entity.CurrencyRate, error)
SaveCurrencyRate(currency string, rate float64, date time.Time, source string) error
}
func NewCurrencyRateRepository(db *gorm.DB) CurrencyRateRepository {
return ¤cyRateRepo{db: db}
}
func (r *currencyRateRepo) GetLatestCurrencyRate(currency string) (*entity.CurrencyRate, error) {
var rate entity.CurrencyRate
err := r.db.
Where("currency = ?", currency).
Order("date desc").
First(&rate).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &rate, nil
}
func (r *currencyRateRepo) SaveCurrencyRate(currency string, rate float64, date time.Time, source string) error {
// Check if the currency rate already exists for the given currency and date
var existingRate entity.CurrencyRate
err := r.db.
Where("currency = ?", currency).
Where("date = ?", date).
Where("source = ?", source).
First(&existingRate).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
// If the currency rate doesn't exist, create a new record
if errors.Is(err, gorm.ErrRecordNotFound) {
newRate := entity.CurrencyRate{
Currency: currency,
Rate: rate,
Date: date,
Source: source,
}
return r.db.Create(&newRate).Error
}
// If the currency rate exists, update the rate
existingRate.Rate = rate
existingRate.UpdatedAt = utils.Now()
return r.db.Save(&existingRate).Error
}