Skip to content

Instantly share code, notes, and snippets.

@koblas
Last active August 3, 2018 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koblas/b27b32310c22379baae39963f05a9b58 to your computer and use it in GitHub Desktop.
Save koblas/b27b32310c22379baae39963f05a9b58 to your computer and use it in GitHub Desktop.
graphql-go/graphql wrapper for unmarshaling
package nresolver
import (
"reflect"
"strings"
"github.com/asaskevich/govalidator"
"github.com/graphql-go/graphql"
"github.com/mitchellh/mapstructure"
)
func wrapGraphQL(wrap interface{}) func(p graphql.ResolveParams) (interface{}, error) {
return func(p graphql.ResolveParams) (interface{}, error) {
// Get the Value of the argument, so we can Call(...) it later
fValue := reflect.ValueOf(wrap)
// The type of the argument
fType := reflect.TypeOf(wrap)
// Basic checking that we're matching the expected arguments
if fType.Kind() != reflect.Func {
panic("Not a function")
}
// Expect a function that is (context.Context, struct{}, []*validationErrors) == 3 arguments
if fType.NumIn() != 3 {
panic("Wrong number of arguments")
}
// Construct the struct{} argument
arg := reflect.New(fType.In(1))
if err := mapstructure.Decode(p.Args, arg.Interface()); err != nil {
return nil, err
}
// Handle validation
var validationErrors []*ValidationError
if _, err := govalidator.ValidateStruct(arg.Interface()); err != nil {
gerrs, _ := err.(govalidator.Errors)
for _, e := range gerrs {
ge, _ := e.(govalidator.Error)
validationErrors = append(validationErrors, &ValidationError{
strings.ToLower(ge.Name),
ge.Err.Error(),
})
}
}
// Call the wrapped function
result := fValue.Call([]reflect.Value{
reflect.ValueOf(p.Context),
reflect.Indirect(arg),
reflect.ValueOf(validationErrors)},
)
// See if we've got errors otherwise return nil
eResult := result[1].Interface()
if eResult != nil {
return result[0].Interface(), eResult.(error)
}
return result[0].Interface(), nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment