-
Notifications
You must be signed in to change notification settings - Fork 11
/
id.go
71 lines (63 loc) · 1.64 KB
/
id.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
package mongo
import (
"context"
"errors"
"fmt"
"github.com/rs/rest-layer/schema"
"gopkg.in/mgo.v2/bson"
)
var (
// NewObjectID is a field hook handler that generates a new Mongo ObjectID hex if
// value is nil to be used in schema with OnInit.
NewObjectID = func(ctx context.Context, value interface{}) interface{} {
if value == nil {
value = bson.NewObjectId().Hex()
}
return value
}
// ObjectIDField is a common schema field configuration that generate an Object ID
// for new item id.
ObjectIDField = schema.Field{
Required: true,
ReadOnly: true,
OnInit: NewObjectID,
Filterable: true,
Sortable: true,
Validator: &ObjectID{},
}
)
// ObjectID validates and serialize unique id
type ObjectID struct{}
// Validate implements FieldValidator interface
func (v ObjectID) Validate(value interface{}) (interface{}, error) {
_, ok := value.(bson.ObjectId)
if ok {
return value, nil
}
s, ok := value.(string)
if !ok {
return nil, errors.New("invalid object id")
}
if len(s) != 24 {
return nil, errors.New("invalid object id length")
}
if !bson.IsObjectIdHex(s) {
return nil, fmt.Errorf("invalid object id")
}
return bson.ObjectIdHex(s), nil
}
// Serialize implements FieldSerializer interface
func (v ObjectID) Serialize(value interface{}) (interface{}, error) {
id, ok := value.(bson.ObjectId)
if !ok {
return nil, errors.New("not an ObjectId")
}
return id.Hex(), nil
}
// BuildJSONSchema implements the jsonschema.Builder interface.
func (v ObjectID) BuildJSONSchema() (map[string]interface{}, error) {
return map[string]interface{}{
"type": "string",
"pattern": "^[0-9a-fA-F]{24}$",
}, nil
}