gqlgenmarshal
Use Go Generate to autogen MarshalGQL and UnmarshalGQL functions for your enums/iotas.
Installation
Go >= 1.16
go install github.com/xplorfin/gqlgenmarshal@latest
Go < 1.16
go get -u github.com/xplorfin/gqlgenmarshal
Usage
Using the example type Carl
:
package carl
//go:generate github.com/xplorfin/gqlgenmarshal -type=Carl
type Carl uint8
const (
Herp Carl = iota
Derp
Merp
)
Run go generate ./...
from the root of your project, and you'll get the following:
// Code generated by "gqlgenmarshal -type=Carl"; DO NOT EDIT.
package carl
import (
"encoding/json"
"fmt"
"io"
)
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Herp-0]
_ = x[Derp-1]
_ = x[Merp-2]
}
func (i Carl) MarshalGQL(w io.Writer) {
if err := json.NewEncoder(w).Encode(i); err != nil {
panic(fmt.Errorf("error marshaling Carl"))
}
}
func (i *Carl) UnmarshalGQL(v interface{}) error {
check, ok := v.(int)
if !ok {
return fmt.Errorf("Carl must be a valid int value")
}
switch Carl(check) {
case Herp:
*i = Herp
case Derp:
*i = Derp
case Merp:
*i = Merp
default:
return fmt.Errorf("unknown Carl value %[1]v", check)
}
return nil
}
If your type implements fmt.Stringer
(ie. has a String()
method), then the generated code will encode/decode the string value
of the sent/received data instead of the int value.
You can pass the -checkstringlowercase
flag to make UnmarshalGQL check against the lowercase value of a string instead of
whatever the raw result of <type>.String()
returns.