PSA: simplify api (#2022)
This commit is contained in:
parent
cbc272d90c
commit
a0e07e83a9
1 changed files with 24 additions and 33 deletions
|
|
@ -2,11 +2,11 @@ package psa
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/evcc-io/evcc/util"
|
||||
"github.com/evcc-io/evcc/util/request"
|
||||
"github.com/evcc-io/evcc/util/transport"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
|
|
@ -30,56 +30,47 @@ func NewAPI(log *util.Logger, identity oauth2.TokenSource, realm, id string) *AP
|
|||
id: id,
|
||||
}
|
||||
|
||||
// replace client transport with authenticated transport
|
||||
v.Client.Transport = &oauth2.Transport{
|
||||
Source: identity,
|
||||
Base: v.Client.Transport,
|
||||
// replace client transport with authenticated transport plus headers
|
||||
v.Client.Transport = &transport.Decorator{
|
||||
Base: &oauth2.Transport{
|
||||
Source: identity,
|
||||
Base: v.Client.Transport,
|
||||
},
|
||||
Decorator: transport.DecorateHeaders(map[string]string{
|
||||
"Accept": "application/hal+json",
|
||||
"X-Introspect-Realm": v.realm,
|
||||
}),
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
func (v *API) clientID() string {
|
||||
return url.Values{
|
||||
"client_id": []string{v.id},
|
||||
}.Encode()
|
||||
}
|
||||
|
||||
// Vehicles implements the /vehicles response
|
||||
func (v *API) Vehicles() ([]Vehicle, error) {
|
||||
data := url.Values{
|
||||
"client_id": []string{v.id},
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s/user/vehicles?%s", BaseURL, data.Encode())
|
||||
req, err := request.New(http.MethodGet, uri, nil, map[string]string{
|
||||
"Accept": "application/hal+json",
|
||||
"X-Introspect-Realm": v.realm,
|
||||
})
|
||||
|
||||
var res struct {
|
||||
Embedded struct {
|
||||
Vehicles []Vehicle
|
||||
} `json:"_embedded"`
|
||||
}
|
||||
if err == nil {
|
||||
err = v.DoJSON(req, &res)
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s/user/vehicles?%s", BaseURL, v.clientID())
|
||||
err := v.GetJSON(uri, &res)
|
||||
|
||||
return res.Embedded.Vehicles, err
|
||||
}
|
||||
|
||||
// Status implements the /vehicles/<vid>/status response
|
||||
func (v *API) Status(vid string) (Status, error) {
|
||||
data := url.Values{
|
||||
"client_id": []string{v.id},
|
||||
}
|
||||
var res Status
|
||||
|
||||
// BaseURL is the API base url
|
||||
uri := fmt.Sprintf("%s/user/vehicles/%s/status?%s", BaseURL, vid, data.Encode())
|
||||
req, err := request.New(http.MethodGet, uri, nil, map[string]string{
|
||||
"Accept": "application/hal+json",
|
||||
"X-Introspect-Realm": v.realm,
|
||||
})
|
||||
uri := fmt.Sprintf("%s/user/vehicles/%s/status?%s", BaseURL, vid, v.clientID())
|
||||
err := v.GetJSON(uri, &res)
|
||||
|
||||
var status Status
|
||||
if err == nil {
|
||||
err = v.DoJSON(req, &status)
|
||||
}
|
||||
|
||||
return status, err
|
||||
return res, err
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue