forked from mattevans/dinero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrates.go
76 lines (62 loc) · 1.97 KB
/
rates.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
70
71
72
73
74
75
76
package dinero
import (
"errors"
"github.com/shopspring/decimal"
"time"
)
// RatesService handles retrieving forex rates for a given currency, either from
// in-memory cache or by fetching fresh results.
type RatesService service
// RatesStore holds our forex rates for a given base currency
type RatesStore struct {
Rates map[string]decimal.Decimal `json:"rates"`
UpdatedAt *time.Time `json:"updated_at"`
Base string `json:"base"`
}
var baseCurrency string
// GetBaseCurrency will return the baseCurrency.
func (s *RatesService) GetBaseCurrency() string {
return baseCurrency
}
// SetBaseCurrency will set the base currency to be used for requests.
func (s *RatesService) SetBaseCurrency(base string) {
baseCurrency = base
}
// All will build and execute request to fetch the latest rates for given base
// currency either from the in-memory cache or OXR API.
func (s *RatesService) All() (*RatesStore, error) {
// No base currency provided, let them know!
if baseCurrency == "" {
return nil, errors.New("please set a base currency.")
}
// If we have cached results, use them.
results := s.client.Cache.Get(baseCurrency)
if results != nil {
return results, nil
}
// No cached results, go and fetch them.
err := s.client.Update.LatestRates(baseCurrency)
if err != nil {
return nil, err
}
return s.All()
}
// Single will return forex rate for given base/code.
func (s *RatesService) Single(code string) (*decimal.Decimal, error) {
// No base currency provided, let them know!
if baseCurrency == "" || code == "" {
return nil, errors.New("both the base currency and requested currency values must be set")
}
// If we have cached results, use them.
results := s.client.Cache.Get(baseCurrency)
if results != nil {
single := results.Rates[code]
return &single, nil
}
// No cached results, go and fetch them.
err := s.client.Update.LatestRates(baseCurrency)
if err != nil {
return nil, err
}
return s.Single(code)
}