-
Notifications
You must be signed in to change notification settings - Fork 1
/
bytes.go
86 lines (70 loc) · 1.58 KB
/
bytes.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package scalar
import (
"encoding/base64"
"encoding/json"
"github.com/hasura/ndc-sdk-go/utils"
)
// Bytes wraps the scalar implementation for bytes with base64 encoding
//
// @scalar Bytes string
type Bytes struct {
data []byte
}
// NewBytes create a Bytes instance
func NewBytes(data []byte) *Bytes {
return &Bytes{data: data}
}
// ParseBytes parses bytes from base64 string
func ParseBytes(value string) (*Bytes, error) {
bs, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return nil, err
}
return &Bytes{data: bs}, nil
}
// Bytes get the inner bytes value.
func (bs Bytes) Bytes() []byte {
return bs.data
}
// Bytes get the inner bytes length.
func (bs Bytes) Len() int {
return len(bs.data)
}
// String implements fmt.Stringer interface.
func (bs Bytes) String() string {
return string(bs.data)
}
// MarshalJSON implements json.Marshaler.
func (bs Bytes) MarshalJSON() ([]byte, error) {
str := base64.StdEncoding.EncodeToString(bs.data)
return json.Marshal(str)
}
// UnmarshalJSON implements json.Unmarshaler.
func (bs *Bytes) UnmarshalJSON(b []byte) error {
var value string
if err := json.Unmarshal(b, &value); err != nil {
return err
}
result, err := ParseBytes(value)
if err != nil {
return err
}
*bs = *result
return nil
}
// FromValue decode any value to d Date.
func (bs *Bytes) FromValue(value any) error {
sValue, err := utils.DecodeNullableString(value)
if err != nil {
return err
}
if sValue == nil {
return nil
}
data, err := base64.StdEncoding.DecodeString(*sValue)
if err != nil {
return err
}
bs.data = data
return nil
}