/
priority.go
90 lines (73 loc) · 2.05 KB
/
priority.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
package rest
import (
"encoding/json"
"github.com/ryanpfalz/go-openapi/internal"
)
// Priority indicates how important a Task is.
type Priority string
const (
priorityNone Priority = "none"
priorityLow Priority = "low"
priorityMedium Priority = "medium"
priorityHigh Priority = "high"
)
// NewPriority converts the received domain type to a rest type, when the argument is unknown "none" is used.
func NewPriority(p internal.Priority) Priority {
switch p {
case internal.PriorityNone:
return priorityNone
case internal.PriorityLow:
return priorityLow
case internal.PriorityMedium:
return priorityMedium
case internal.PriorityHigh:
return priorityHigh
}
return priorityNone
}
// Convert returns the domain type defining the internal representation, when priority is unknown "none" is
// used.
func (p Priority) Convert() internal.Priority {
switch p {
case priorityNone:
return internal.PriorityNone
case priorityLow:
return internal.PriorityLow
case priorityMedium:
return internal.PriorityMedium
case priorityHigh:
return internal.PriorityHigh
}
return internal.PriorityNone
}
// Validate ...
func (p Priority) Validate() error {
switch p {
case priorityNone, priorityLow, priorityMedium, priorityHigh:
return nil
}
return internal.NewErrorf(internal.ErrorCodeInvalidArgument, "unknown value")
}
// MarshalJSON ...
func (p Priority) MarshalJSON() ([]byte, error) {
if err := p.Validate(); err != nil {
return nil, internal.WrapErrorf(err, internal.ErrorCodeUnknown, "Validate")
}
b, err := json.Marshal(string(p))
if err != nil {
return nil, internal.WrapErrorf(err, internal.ErrorCodeUnknown, "json.Marshal")
}
return b, nil
}
// UnmarshalJSON ...
func (p *Priority) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return internal.WrapErrorf(err, internal.ErrorCodeInvalidArgument, "json.Unmarshal")
}
if err := Priority(str).Validate(); err != nil {
return internal.WrapErrorf(err, internal.ErrorCodeInvalidArgument, "Validate")
}
*p = Priority(str)
return nil
}