-
Notifications
You must be signed in to change notification settings - Fork 44
/
report.go
76 lines (63 loc) · 1.96 KB
/
report.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
package types
import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/codec"
)
// NewReport returns a Report
func NewReport(postID string, reportType string, message string, user string) Report {
return Report{
PostID: postID,
Type: reportType,
Message: message,
User: user,
}
}
// Validate implements validator
func (r Report) Validate() error {
if !IsValidPostID(r.PostID) {
return fmt.Errorf("invalid post id: %s", r.PostID)
}
if len(strings.TrimSpace(r.Type)) == 0 {
return fmt.Errorf("report type cannot be empty")
}
if len(strings.TrimSpace(r.Message)) == 0 {
return fmt.Errorf("report message cannot be empty")
}
if len(r.User) == 0 {
return fmt.Errorf("invalid user address: %s", r.User)
}
return nil
}
// ___________________________________________________________________________________________________________________
// AppendIfMissing appends the given report to the provided reports slice if not already present.
// If appended, returns the new slice and true.
// If not appended, returns the original slice and false.
func AppendIfMissing(reports []Report, report Report) (newSlice []Report, appended bool) {
for _, existing := range reports {
if existing.Equal(report) {
return reports, false
}
}
return append(reports, report), true
}
// ___________________________________________________________________________________________________________________
// MustMarshalReports marshals the given reports into an array of bytes.
// Panics on error.
func MustMarshalReports(reports []Report, cdc codec.BinaryMarshaler) []byte {
bz, err := cdc.MarshalBinaryBare(&Reports{Reports: reports})
if err != nil {
panic(err)
}
return bz
}
// MustUnmarshalReports tries unmarshalling the given bz to a list of reports.
// Panics on error.
func MustUnmarshalReports(bz []byte, cdc codec.BinaryMarshaler) []Report {
var wrapped Reports
err := cdc.UnmarshalBinaryBare(bz, &wrapped)
if err != nil {
panic(err)
}
return wrapped.Reports
}