-
Notifications
You must be signed in to change notification settings - Fork 689
/
rates.go
81 lines (71 loc) · 2.4 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
77
78
79
80
81
package currency
import (
"encoding/json"
"errors"
"time"
"golang.org/x/text/currency"
)
// Rates holds data as represented on https://cdn.jsdelivr.net/gh/prebid/currency-file@1/latest.json
// note that `DataAsOfRaw` field is needed when parsing remote JSON as the date format if not standard and requires
// custom parsing to be properly set as Golang time.Time
type Rates struct {
DataAsOf time.Time `json:"dataAsOf"`
Conversions map[string]map[string]float64 `json:"conversions"`
}
// NewRates creates a new Rates object holding currencies rates
func NewRates(dataAsOf time.Time, conversions map[string]map[string]float64) *Rates {
return &Rates{
DataAsOf: dataAsOf,
Conversions: conversions,
}
}
// UnmarshalJSON unmarshal raw JSON bytes to Rates object
func (r *Rates) UnmarshalJSON(b []byte) error {
c := &struct {
DataAsOf string `json:"dataAsOf"`
Conversions map[string]map[string]float64 `json:"conversions"`
}{}
if err := json.Unmarshal(b, &c); err != nil {
return err
}
r.Conversions = c.Conversions
layout := "2006-01-02"
if date, err := time.Parse(layout, c.DataAsOf); err == nil {
r.DataAsOf = date
}
return nil
}
// GetRate returns the conversion rate between two currencies or:
// - An error if one of the currency strings is not well-formed
// - An error if any of the currency strings is not a recognized currency code.
// - A ConversionNotFoundError in case the conversion rate between the two
// given currencies is not in the currencies rates map
func (r *Rates) GetRate(from, to string) (float64, error) {
var err error
fromUnit, err := currency.ParseISO(from)
if err != nil {
return 0, err
}
toUnit, err := currency.ParseISO(to)
if err != nil {
return 0, err
}
if fromUnit.String() == toUnit.String() {
return 1, nil
}
if r.Conversions != nil {
if conversion, present := r.Conversions[fromUnit.String()][toUnit.String()]; present {
// In case we have an entry FROM -> TO
return conversion, nil
} else if conversion, present := r.Conversions[toUnit.String()][fromUnit.String()]; present {
// In case we have an entry TO -> FROM
return 1 / conversion, nil
}
return 0, ConversionNotFoundError{FromCur: fromUnit.String(), ToCur: toUnit.String()}
}
return 0, errors.New("rates are nil")
}
// GetRates returns current rates
func (r *Rates) GetRates() *map[string]map[string]float64 {
return &r.Conversions
}