...
1 package graphql
2
3 import "encoding/json"
4
5
6
7 type Omittable[T any] struct {
8 value T
9 set bool
10 }
11
12 var (
13 _ json.Marshaler = Omittable[struct{}]{}
14 _ json.Unmarshaler = (*Omittable[struct{}])(nil)
15 )
16
17 func OmittableOf[T any](value T) Omittable[T] {
18 return Omittable[T]{
19 value: value,
20 set: true,
21 }
22 }
23
24 func (o Omittable[T]) Value() T {
25 if !o.set {
26 var zero T
27 return zero
28 }
29 return o.value
30 }
31
32 func (o Omittable[T]) ValueOK() (T, bool) {
33 if !o.set {
34 var zero T
35 return zero, false
36 }
37 return o.value, true
38 }
39
40 func (o Omittable[T]) IsSet() bool {
41 return o.set
42 }
43
44 func (o Omittable[T]) MarshalJSON() ([]byte, error) {
45 if !o.set {
46 return []byte("null"), nil
47 }
48 return json.Marshal(o.value)
49 }
50
51 func (o *Omittable[T]) UnmarshalJSON(bytes []byte) error {
52 err := json.Unmarshal(bytes, &o.value)
53 if err != nil {
54 return err
55 }
56 o.set = true
57 return nil
58 }
59
View as plain text