From a0e07e83a91ced76b8bf6fdcf33ff709b0fc1013 Mon Sep 17 00:00:00 2001 From: andig Date: Sat, 11 Dec 2021 12:46:56 +0100 Subject: [PATCH] PSA: simplify api (#2022) --- vehicle/psa/api.go | 57 +++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/vehicle/psa/api.go b/vehicle/psa/api.go index 625ee662c..0b1857cbb 100644 --- a/vehicle/psa/api.go +++ b/vehicle/psa/api.go @@ -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//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 }