/
types.go
99 lines (80 loc) · 2.58 KB
/
types.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
87
88
89
90
91
92
93
94
95
96
97
98
99
package gql
import (
"fmt"
"io"
"net"
"strings"
"time"
"github.com/99designs/gqlgen/graphql"
"github.com/cybozu-go/sabakan/v3"
"github.com/vektah/gqlparser/v2/gqlerror"
)
const (
// ErrInvalidStateName is an error code when state name is invalid.
ErrInvalidStateName = "INVALID_STATE_NAME"
// ErrInvalidStateTransition is an error code when state transition is invalid.
ErrInvalidStateTransition = "INVALID_STATE_TRANSITION"
// ErrEncryptionKeyExists is an error code when a retiring machine to retired that still has disk encryption keys.
ErrEncryptionKeyExists = "ENCRYPTION_KEY_EXISTS"
// ErrMachineNotFound is an error code when no specified machine found.
ErrMachineNotFound = "MACHINE_NOT_FOUND"
// ErrInternalServerError is an error code when internal server error has occurred.
ErrInternalServerError = "INTERNAL_SERVER_ERROR"
)
// IPAddress represents "IPAddress" GraphQL custom scalar.
type IPAddress struct {
net.IP
}
// UnmarshalGQL implements graphql.Marshaler interface.
func (a *IPAddress) UnmarshalGQL(v interface{}) error {
str, err := graphql.UnmarshalString(v)
if err != nil {
return fmt.Errorf("invalid IPAddress: %v, %v", v, err)
}
ip := net.ParseIP(str)
if ip == nil {
return fmt.Errorf("invalid IPAddress: %s", str)
}
a.IP = ip
return nil
}
// MarshalGQL implements graphql.Marshaler interface.
func (a IPAddress) MarshalGQL(w io.Writer) {
graphql.MarshalString(a.IP.String()).MarshalGQL(w)
}
// DateTime represents "DateTime" GraphQL custom scalar.
type DateTime time.Time
// UnmarshalGQL implements graphql.Marshaler interface.
func (dt *DateTime) UnmarshalGQL(v interface{}) error {
t, err := graphql.UnmarshalTime(v)
if err != nil {
return fmt.Errorf("invalid DateTime: %v, %v", v, err)
}
*dt = DateTime(t)
return nil
}
// MarshalGQL implements graphql.Marshaler interface.
func (dt DateTime) MarshalGQL(w io.Writer) {
graphql.MarshalTime(time.Time(dt)).MarshalGQL(w)
}
// MarshalMachineState helps mapping sabakan.MachineState with GraphQL enum.
func MarshalMachineState(state sabakan.MachineState) graphql.Marshaler {
return graphql.MarshalString(strings.ToUpper(state.String()))
}
// UnmarshalMachineState helps mapping sabakan.MachineState with GraphQL enum.
func UnmarshalMachineState(v interface{}) (sabakan.MachineState, error) {
str, err := graphql.UnmarshalString(v)
if err != nil {
return "", err
}
st := sabakan.MachineState(strings.ToLower(str))
if !st.IsValid() {
return "", &gqlerror.Error{
Message: "invalid state: " + str,
Extensions: map[string]interface{}{
"type": ErrInvalidStateName,
},
}
}
return st, nil
}