From 583d0b1bcb08fa0962f0b539f6c0dffcedf8c521 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Tue, 9 Jan 2024 09:57:48 +0000 Subject: [PATCH] client/graphql: handle GraphQL errors Instead of leaving it up to the caller to check for GraphQL errors, centralize in core-go. --- client/graphql.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/client/graphql.go b/client/graphql.go index 1b93e8b675e48979d896b62eb032c8c33019aa13..0b986057ce1dd434808677fd52b78f633b86eeed 100644 --- a/client/graphql.go +++ b/client/graphql.go @@ -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