-
Notifications
You must be signed in to change notification settings - Fork 0
/
id.go
67 lines (59 loc) · 1.59 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
package mongo
import (
"context"
"errors"
"github.com/rs/rest-layer/schema"
"go.mongodb.org/mongo-driver/bson/primitive"
)
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 = primitive.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.(primitive.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")
}
return primitive.ObjectIDFromHex(s)
}
// Serialize implements FieldSerializer interface
func (v ObjectID) Serialize(value interface{}) (interface{}, error) {
id, ok := value.(primitive.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
}