-
Notifications
You must be signed in to change notification settings - Fork 31
/
document.go
105 lines (91 loc) · 2.11 KB
/
document.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package aranGO
import (
"errors"
"strings"
)
type Document struct {
Id string `json:"_id,omitempty" `
Rev string `json:"_rev,omitempty" `
Key string `json:"_key,omitempty" `
Error bool `json:"error,omitempty"`
Message string `json:"errorMessage,omitempty"`
}
// Creates base document structure
func NewDocument(id string) (*Document, error) {
// some basic validation
sid := strings.Split(id, "/")
if len(sid) != 2 {
return nil, errors.New("Invalid id")
}
if id == "" {
return nil, errors.New("Invalid empty id")
}
var d Document
d.Id = id
d.Key = sid[1]
return &d, nil
}
// Map returns map[string]string of document instead of struct
func (d *Document) Map(db *Database) (map[string]string, error) {
var m map[string]string
sid := strings.Split(d.Id, "/")
m = make(map[string]string)
err := db.Col(sid[0]).Get(sid[1], &m)
if err != nil {
return m, err
}
return m, nil
}
func (d *Document) SetKey(key string) error {
//valitated key
d.Key = key
return nil
}
func (d *Document) SetRev(rev string) error {
d.Rev = rev
return nil
}
// Updated checks if a document was updated
func (d *Document) Updated(db *Database) (bool, error) {
if db == nil {
return false, errors.New("Invalid db")
}
// check document id and rev
if d.Id == "" || d.Rev == "" {
return false, errors.New("Document must exist or have valid _rev and _id")
}
// add revision id
res, err := db.get("document", d.Id+"?rev="+d.Rev, "GET", nil, nil, nil)
if err != nil {
return false, err
}
switch res.Status() {
case 404:
return true, nil
case 412:
return true, nil
default:
return false, nil
}
}
// Exist checks if document exist
func (d *Document) Exist(db *Database) (bool, error) {
if db == nil {
return false, errors.New("Invalid db")
}
// check document id and rev
if d.Id == "" {
return false, errors.New("Document must exist or have valid _rev and _id")
}
// add revision id
res, err := db.get("document", d.Id, "GET", nil, nil, nil)
if err != nil {
return false, err
}
switch res.Status() {
case 404:
return false, nil
default:
return true, nil
}
}