id.go

 1package entity
 2
 3import (
 4	"fmt"
 5	"io"
 6	"strings"
 7
 8	"github.com/pkg/errors"
 9)
10
11const IdLengthSHA1 = 40
12const IdLengthSHA256 = 64
13const humanIdLength = 7
14
15const UnsetId = Id("unset")
16
17// Id is an identifier for an entity or part of an entity
18type Id string
19
20func (i Id) String() string {
21	return string(i)
22}
23
24func (i Id) Human() string {
25	format := fmt.Sprintf("%%.%ds", humanIdLength)
26	return fmt.Sprintf(format, i)
27}
28
29func (i Id) HasPrefix(prefix string) bool {
30	return strings.HasPrefix(string(i), prefix)
31}
32
33// UnmarshalGQL implement the Unmarshaler interface for gqlgen
34func (i *Id) UnmarshalGQL(v interface{}) error {
35	_, ok := v.(string)
36	if !ok {
37		return fmt.Errorf("IDs must be strings")
38	}
39
40	*i = v.(Id)
41
42	if err := i.Validate(); err != nil {
43		return errors.Wrap(err, "invalid ID")
44	}
45
46	return nil
47}
48
49// MarshalGQL implement the Marshaler interface for gqlgen
50func (i Id) MarshalGQL(w io.Writer) {
51	_, _ = w.Write([]byte(`"` + i.String() + `"`))
52}
53
54// IsValid tell if the Id is valid
55func (i Id) Validate() error {
56	if len(i) != IdLengthSHA1 && len(i) != IdLengthSHA256 {
57		return fmt.Errorf("invalid length")
58	}
59	for _, r := range i {
60		if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
61			return fmt.Errorf("invalid character")
62		}
63	}
64	return nil
65}