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