Skip to content

Instantly share code, notes, and snippets.

@huantt
Created May 17, 2023 14:37
Show Gist options
  • Save huantt/649fe4478d30164df845001eae45d956 to your computer and use it in GitHub Desktop.
Save huantt/649fe4478d30164df845001eae45d956 to your computer and use it in GitHub Desktop.
Json scalar implementation for github.com/graph-gophers/graphql-go
package graphql
import (
"encoding/json"
)
type Json map[string]interface{}
func (Json) ImplementsGraphQLType(name string) bool {
return name == "Json"
}
func (m *Json) UnmarshalGraphQL(input interface{}) error {
var bytes []byte
switch input.(type) {
case []byte:
bytes = input.([]byte)
default:
var err error
bytes, err = json.Marshal(input)
if err != nil {
return err
}
}
return json.Unmarshal(bytes, m)
}
@huantt
Copy link
Author

huantt commented May 17, 2023

How to use it:

func (r *CollectionResolver) Data() (*graphql.Json, error) {
	result := &graphql.Json{}
	err := result.UnmarshalGraphQL(map[string]interface{}{
		"a": map[string]interface{}{
			"b": map[string]interface{}{
				"c": "d",
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment