-
Notifications
You must be signed in to change notification settings - Fork 6
/
water.go
102 lines (85 loc) · 2.42 KB
/
water.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package fitbit
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
)
// WaterUnit is an object that contains one log of water consumption
type WaterUnit struct {
Amount uint64 `json:"amount"`
LogID uint64 `json:"logId"`
}
// WaterSummary is a summary of the requested water logs
type WaterSummary struct {
Water uint64 `json:"water"`
}
// Water object contains all the data of the logged water
type Water struct {
Summary *WaterSummary `json:"summary"`
Water []*WaterUnit `json:"water"`
}
// GetWater gets the amount of water taken on a specific date
// It returns an collection of Water or an error if one occours
func (c *Client) GetWater(date time.Time) (*Water, error) {
//Build and get request-URL
requestURL := fmt.Sprintf("user/-/foods/log/water/date/%s.json", date.Format("2006-01-02"))
responseBody, err := c.getData(requestURL)
if err != nil {
return nil, err
}
//Parse data
waterData := &Water{}
err = json.NewDecoder(responseBody).Decode(waterData)
if err != nil {
return nil, err
}
return waterData, nil
}
type LogWater struct {
WaterLog *WaterUnit `json:"waterLog"`
}
// LogWater adds a certain amount of water taken on a specific date
// It returns an error if one occours
func (c *Client) LogWater(measurementType string, amount float64, date time.Time) (*LogWater, error) {
//Supported unit types
measurementUnitTypes := map[string]string{"ml": "", "fl oz": "", "cup": ""}
//Build arguments map
dataArguments := map[string]string{
"amount": strconv.FormatFloat(amount, 'f', 2, 32),
"date": date.Format("2006-01-02"),
}
//Check parameters
if amount == 0 {
return nil, errors.New("missing paramters")
}
//Check if correct measurement is passed
_, ok := measurementUnitTypes[measurementType]
if ok {
dataArguments["unit"] = measurementType
}
//Build an put request-URL
responseBody, err := c.postData("user/-/foods/log/water.json", dataArguments)
if err != nil {
return nil, err
}
//Parse data
logWater := &LogWater{}
err = json.NewDecoder(responseBody).Decode(logWater)
if err != nil {
return nil, err
}
return logWater, nil
}
// DeleteWater removes a record of water taken based on the waterId
// It returns an error if one occours
func (c *Client) DeleteWater(waterId uint64) error {
//Build requestURL and DELETE data
requestURL := fmt.Sprintf("user/-/foods/log/water/%d.json", waterId)
_, err := c.deleteData(requestURL, nil)
if err != nil {
return err
}
return nil
}