Created
May 7, 2018 02:40
-
-
Save sanae10001/9ad4c2ebfe640751f7e3278f5c6eb02a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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