Skip to content

Instantly share code, notes, and snippets.

@sanae10001
Created May 7, 2018 02:40
Show Gist options
  • Save sanae10001/9ad4c2ebfe640751f7e3278f5c6eb02a to your computer and use it in GitHub Desktop.
Save sanae10001/9ad4c2ebfe640751f7e3278f5c6eb02a to your computer and use it in GitHub Desktop.
import (
"encoding/json"
"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/errors"
)
type ErrorType string
type Error struct {
Type ErrorType
Message string
}
type GraphqlError struct {
Message string `json:"message"`
Locations []errors.Location `json:"locations,omitempty"`
Path []interface{} `json:"path,omitempty"`
Type ErrorType `json:"type,omitempty"`
}
type GraphqlResponse struct {
Data json.RawMessage `json:"data,omitempty"`
Errors []*GraphqlError `json:"errors,omitempty"`
}
func BuildGraphqlResponse(resp *graphql.Response) interface{} {
gr := &GraphqlResponse{
Data: resp.Data,
Errors: batchBuildError(resp.Errors),
}
return gr
}
func batchBuildError(qErrors []*errors.QueryError) []*GraphqlError {
gErrors := make([]*GraphqlError, 0, len(qErrors))
for _, qError := range qErrors {
gErrors = append(gErrors, buildError(qError))
}
return gErrors
}
func buildError(qError *errors.QueryError) *GraphqlError {
ge := &GraphqlError{
Message: qError.Message,
Locations: qError.Locations,
Path: qError.Path,
}
if err, ok := qError.ResolverError.(*Error); ok {
ge.Type = err.Type
ge.Message = err.Message
} else {
if qError.ResolverError != nil {
ge.Message = qError.ResolverError.Error()
}
ge.Type = ErrorTypeBadRequest
}
return ge
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment