-
Notifications
You must be signed in to change notification settings - Fork 0
/
duration.go
62 lines (53 loc) · 1.45 KB
/
duration.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
package types
import (
"fmt"
"io"
"strconv"
"time"
"github.com/99designs/gqlgen/graphql"
)
// TimeDuration implements IO custom type of time with custom format
type TimeDuration time.Duration
// Duration object from TimeDuration
func (t TimeDuration) Duration() time.Duration {
return (time.Duration)(t)
}
// SetDuration from time object
func (t *TimeDuration) SetDuration(d time.Duration) {
*t = (TimeDuration)(d)
}
// MarshalGQL implements method of interface graphql.Marshaler
func (t TimeDuration) MarshalGQL(w io.Writer) {
_, _ = w.Write([]byte(
strconv.Quote(t.Duration().String()),
))
}
// UnmarshalGQL implements method of interface graphql.Unmarshaler
func (t *TimeDuration) UnmarshalGQL(v any) error {
switch v := v.(type) {
case string:
d, err := time.ParseDuration(v)
if err != nil {
return err
}
t.SetDuration(d)
return nil
default:
return fmt.Errorf("%T is not a supported as a duration", v)
}
}
// MarshalDuration redecalre the marshalel of standart scalar type Duration
func MarshalDuration(d time.Duration) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = io.WriteString(w, strconv.Quote(d.String()))
})
}
// UnmarshalDuration redecalre the unmarshalel of standart scalar type Duration
func UnmarshalDuration(v any) (time.Duration, error) {
switch v := v.(type) {
case string:
return time.ParseDuration(v)
default:
return time.Duration(0), fmt.Errorf("%T is not a supported as a duration", v)
}
}