teslainventory_sdk/inventory.go
Matthieu 'JP' DERASSE 5277672f1e
All checks were successful
continuous-integration/drone/push Build is passing
feat(inventory): Be able to handle both type of tesla response
2023-08-13 12:16:34 +00:00

72 lines
1.7 KiB
Go

package teslainventory_sdk
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
// UnmarshalJSON come overide default unmarshal on availabilitiesReponse to handle both type of response sent by Tesla Inventory API.
func (a *AvailabilitiesResponse) UnmarshalJSON(data []byte) error {
if !strings.Contains(string(data), "\"total_matches_found\":\"") {
type TmpJson AvailabilitiesResponse
var tmpJson TmpJson
err := json.Unmarshal(data, &tmpJson)
if err != nil {
return err
}
*a = AvailabilitiesResponse(tmpJson)
return nil
}
var exactAvailabilities AvailabilitiesExactResponse
err := json.Unmarshal(data, &exactAvailabilities)
if err != nil {
return err
}
amount, err := strconv.Atoi(exactAvailabilities.TotalMatchesFound)
if err != nil {
return err
}
a.TotalMatchesFound = amount
a.Results.Exact = exactAvailabilities.Results
return nil
}
// GetAvailabilities return the car availabilities matching with the provided characteristics.
func (c *Client) GetAvailabilities(ctx context.Context, params AvailabilityParams, headers map[string]string) (*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("/v1/inventory-results?%s", queryParams.Encode()),
headers,
)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }() // explicitly discard error
availabilities := AvailabilitiesResponse{}
if err := json.NewDecoder(resp.Body).Decode(&availabilities); err != nil {
return nil, fmt.Errorf("fail to unmarshal response. Error: %w", err)
}
return &availabilities, nil
}