-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmtoy.go
78 lines (61 loc) · 1.35 KB
/
mtoy.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
// Copyright 2012 The Toys Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mtoy
import (
"errors"
"github.com/kidstuff/toys/model"
"labix.org/v2/mgo/bson"
)
var (
ErrRequireStr = errors.New("mtoy: Decode require a string")
ErrInvalidStr = errors.New("mtoy: Invalid input string format")
)
func init() {
model.Register("mtoy", &Driver{})
}
type Driver struct{}
func (d *Driver) DecodeId(i interface{}) (model.Identifier, error) {
idStr, ok := i.(string)
if !ok {
return nil, ErrRequireStr
}
if !bson.IsObjectIdHex(idStr) {
return nil, ErrInvalidStr
}
return ID{bson.ObjectIdHex(idStr)}, nil
}
func (d *Driver) ValidIdRep(i interface{}) bool {
idStr, ok := i.(string)
if !ok {
return false
}
if !bson.IsObjectIdHex(idStr) {
return false
}
return true
}
func (d *Driver) NewId() model.Identifier {
return NewID()
}
// ID a wraper for bson.ObjectId implements github.com/kidstuff/toys/model#Identifier
type ID struct {
bson.ObjectId
}
func NewID() ID {
return ID{bson.NewObjectId()}
}
func (id ID) Decode(i interface{}) error {
idStr, ok := i.(string)
if !ok {
return ErrRequireStr
}
if !bson.IsObjectIdHex(idStr) {
return ErrInvalidStr
}
id.ObjectId = bson.ObjectIdHex(idStr)
return nil
}
func (id ID) Encode() string {
return id.Hex()
}