From eab200ded14d483dc5c75ff500fc39449c0c8a2b Mon Sep 17 00:00:00 2001 From: Daniel Gonzalez Date: Thu, 10 Feb 2022 20:21:05 +0100 Subject: [PATCH] feat: Add interface methods to User object --- examples/me/main.go | 16 ++++++++-------- models.go | 1 + user.go | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 8 deletions(-) create mode 100644 user.go diff --git a/examples/me/main.go b/examples/me/main.go index faefdb2..116cd25 100644 --- a/examples/me/main.go +++ b/examples/me/main.go @@ -38,12 +38,12 @@ func main() { fmt.Printf("Email: %s\nUsername: %s\nName: %s\n", user.Email, user.Username, user.Name) // for each home: get home info and print name and address - // for _, userHome := range user.Homes { - // home, err := gotado.GetHome(client, &userHome) - // if err != nil { - // fmt.Fprintf(os.Stderr, "Failed to get user home info: %v\n", err) - // os.Exit(1) - // } - // fmt.Printf("Home: %s\nAddress:\n%s\n%s %s\n", home.Name, *home.Address.AddressLine1, *home.Address.ZipCode, *home.Address.City) - // } + for _, userHome := range user.Homes { + home, err := user.GetHome(ctx, userHome.Name) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to get user home info: %v\n", err) + os.Exit(1) + } + fmt.Printf("Home: %s\nAddress:\n%s\n%s %s\n", home.Name, *home.Address.AddressLine1, *home.Address.ZipCode, *home.Address.City) + } } diff --git a/models.go b/models.go index bb07d2d..268049e 100644 --- a/models.go +++ b/models.go @@ -30,6 +30,7 @@ const ( // Home represents a home equipped with tado° type Home struct { + client *client ID int32 `json:"id"` Name string `json:"name"` DateTimeZone string `json:"dateTimeZone"` diff --git a/user.go b/user.go new file mode 100644 index 0000000..ef5da29 --- /dev/null +++ b/user.go @@ -0,0 +1,24 @@ +package gotado + +import ( + "context" + "fmt" +) + +func (u *User) GetHome(ctx context.Context, name string) (*Home, error) { + var homeID int32 + for _, h := range u.Homes { + if h.Name == name { + homeID = h.ID + } + } + if homeID == 0 { + return nil, fmt.Errorf("unknown home name '%s'", name) + } + + home := &Home{client: u.client} + if err := u.client.get(ctx, apiURL("homes/%d", homeID), home); err != nil { + return nil, err + } + return home, nil +}