~sircmpwn/core-go

583d0b1bcb08fa0962f0b539f6c0dffcedf8c521 — Simon Ser 5 months ago a88277c
client/graphql: handle GraphQL errors

Instead of leaving it up to the caller to check for GraphQL errors,
centralize in core-go.
1 files changed, 17 insertions(+), 3 deletions(-)

M client/graphql.go
M client/graphql.go => client/graphql.go +17 -3
@@ 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