forked from mattevans/dinero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.go
58 lines (47 loc) · 1.28 KB
/
update.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
package dinero
import (
"errors"
"fmt"
"github.com/shopspring/decimal"
"time"
)
const (
latestAPIPath = "latest.json"
historyAPIPath = "history.json"
)
// UpdateService handles communication with /latest.json methods of the
// https://docs.openexchangerates.org/docs/latest-json
type UpdateService service
// UpdateResponse is the set of parameters that is used in response to a send
// request
type UpdateResponse struct {
Timestamp int64
UpdatedAt time.Time
Base string
Rates map[string]decimal.Decimal
}
// LatestRates will build and execute request to /latest.json using the base
// currency provided.
func (s *UpdateService) LatestRates(base string) error {
if base == "" {
return errors.New("The base currency provided cannot be empty")
}
// Append our base currency to request URL.
rateAPIPath := fmt.Sprintf("%s?base=%s", latestAPIPath, base)
// Build request.
request, err := s.client.NewRequest("GET", rateAPIPath, nil)
if err != nil {
return err
}
// Make request
latest := &UpdateResponse{}
_, err = s.client.Do(request, latest)
if err != nil {
return err
}
// Switch our unix timestamp to time.Time.
latest.UpdatedAt = time.Unix(latest.Timestamp, 0).UTC()
// Cache our latest results.
s.client.Cache.Store(base, latest.Rates)
return nil
}