mirror of https://git.sr.ht/~sircmpwn/core-go
client/graphql: handle GraphQL errors
Instead of leaving it up to the caller to check for GraphQL errors, centralize in core-go.
This commit is contained in:
parent
a88277c1bc
commit
583d0b1bcb
|
@ -10,6 +10,8 @@ import (
|
|||
|
||||
"git.sr.ht/~sircmpwn/core-go/config"
|
||||
"git.sr.ht/~sircmpwn/core-go/crypto"
|
||||
|
||||
"github.com/vektah/gqlparser/v2/gqlerror"
|
||||
)
|
||||
|
||||
type GraphQLQuery struct {
|
||||
|
@ -25,6 +27,7 @@ type InternalAuth struct {
|
|||
|
||||
func Execute(ctx context.Context, username string, svc string,
|
||||
query GraphQLQuery, result interface{}) error {
|
||||
|
||||
body, err := json.Marshal(query)
|
||||
if err != nil {
|
||||
panic(err) // Programmer error
|
||||
|
@ -62,8 +65,8 @@ func Execute(ctx context.Context, username string, svc string,
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -74,8 +77,19 @@ func Execute(ctx context.Context, username string, svc string,
|
|||
svc, resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(respBody, result); err != nil {
|
||||
return err
|
||||
var respData struct {
|
||||
Data interface{} `json:"data"`
|
||||
Errors gqlerror.List `json:"errors"`
|
||||
}
|
||||
respData.Data = result
|
||||
if err := json.Unmarshal(respBody, &respData); err != nil {
|
||||
return fmt.Errorf("failed to parse GraphQL response: %v", err)
|
||||
}
|
||||
|
||||
if len(respData.Errors) == 1 {
|
||||
return respData.Errors[0]
|
||||
} else if len(respData.Errors) > 1 {
|
||||
return respData.Errors
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
Loading…
Reference in New Issue