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 @@ "net/http" "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 @@ } 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 @@ resp, err := http.DefaultClient.Do(req) if err != nil { return err } - defer resp.Body.Close() + respBody, err := ioutil.ReadAll(resp.Body) if err != nil { return err @@ -74,8 +77,19 @@ return fmt.Errorf("%s returned status %d: %s", 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