Tesla/api/sdk.go

52 lines
1.1 KiB
Go
Raw Permalink Normal View History

2023-06-05 13:41:48 +00:00
package api
import (
"context"
"encoding/json"
"fmt"
"io"
"net/url"
)
// GetAvailabilities return car availabilities for the given filters.
func (c *Client) GetAvailabilities(ctx context.Context, params *AvailabilityParams) (*AvailabilitiesResponse, error) {
b, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("fail to marshal availability params. Error: %w", err)
}
queryParams := url.Values{
"query": {string(b)},
}
resp, err := c.get(
ctx,
fmt.Sprintf("/inventory/api/v1/inventory-results?%s", queryParams.Encode()),
)
if err != nil {
return nil, err
}
if resp.Body != nil {
defer func() {
if err := resp.Body.Close(); err != nil {
fmt.Printf("Error closing body: %s", err)
}
}()
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("fail to read body. Error: %w", err)
}
availabilities := AvailabilitiesResponse{}
err = json.Unmarshal(body, &availabilities)
if err != nil {
return nil, fmt.Errorf("fail to unmarshal response. Error: %w", err)
}
return &availabilities, nil
}