Add "generic" option to the "optional" configuration for handling nullable types (#252)

This is an implementation for #251, it adds a new `"generic"` option for
the `"optional"` configuration, and a companion type
`"optional_generic_type"` which is a fully qualified type with a
placeholder `%` for the generic parameter.

Co-authored-by: Dylan R. Johnston <[email protected]>
Co-authored-by: Ben Kraft <[email protected]>
This commit is contained in:
Dylan R. Johnston
2023-05-06 10:40:03 -07:00
committed by GitHub
co-authored by Dylan R. Johnston Ben Kraft
parent 94b6a71403
commit c61d7acaa5
8 changed files with 279 additions and 12 deletions
+58
View File
@@ -2,6 +2,7 @@ package testutil
import (
"context"
"encoding/json"
"time"
"github.com/Khan/genqlient/graphql"
@@ -49,3 +50,60 @@ func UnmarshalDate(b []byte, t *time.Time) error {
*t, err = time.Parse(`"`+dateFormat+`"`, string(b))
return err
}
type Option[V any] struct {
value V
ok bool
}
func Some[V any](value V) Option[V] {
return Option[V]{value: value, ok: true}
}
func None[V any]() Option[V] {
return Option[V]{ok: false}
}
func (v Option[V]) Unpack() (V, bool) {
return v.value, v.ok
}
func (v Option[V]) Get(fallback V) V {
if v.ok {
return v.value
}
return fallback
}
func FromPtr[V any](ptr *V) Option[V] {
if ptr == nil {
return None[V]()
}
return Some(*ptr)
}
func (value Option[V]) MarshalJSON() ([]byte, error) {
if value.ok {
return json.Marshal(value.value)
} else {
return json.Marshal((*V)(nil))
}
}
func (value *Option[V]) UnmarshalJSON(data []byte) error {
v := (*V)(nil)
err := json.Unmarshal(data, &v)
if err != nil {
return err
}
if v != nil {
value.value = *v
value.ok = true
}
return nil
}