/
document.go
93 lines (74 loc) · 2.16 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
package cloudant
import (
"bytes"
"encoding/json"
)
type CloudantDocumentInterfacer interface {
Id() string
SetId(string)
Revision() string
}
type cloudantDocument struct {
DocId string `json:"_id,omitempty"`
DocRevision string `json:"_rev,omitempty"`
}
type CloudantDocument struct {
cloudantDocument
}
type CloudantDocumentResponse struct {
Id string `json:"id"`
Revision string `json:"rev"`
Ok string `json:"ok"`
Result string `json:"result"`
}
func (doc *CloudantDocument) Id() string {
return doc.DocId
}
func (doc *CloudantDocument) SetId(id string) {
doc.DocId = id
}
func (doc *CloudantDocument) Revision() string {
return doc.DocRevision
}
func (db *Database) GetDocument(id string, doc interface{}) error {
resp, err := db.client.doRequest("GET", "/"+db.Name()+"/"+id, nil, nil)
return db.client.handleResponse(resp, err, 200, doc)
}
func (db *Database) CreateDocument(doc interface{}, isBatch bool) (CloudantDocumentResponse, error) {
cdr := CloudantDocumentResponse{}
uri := "/" + db.Name()
successStatusCode := 201
j, err := json.Marshal(doc)
if err != nil {
return cdr, err
}
if isBatch {
uri += "?batch=ok"
successStatusCode = 202
}
resp, err := db.client.doRequest("POST", uri, nil, bytes.NewReader(j))
err = db.client.handleResponse(resp, err, successStatusCode, &cdr)
return cdr, err
}
func (db *Database) UpdateDocument(doc CloudantDocumentInterfacer, isBatch bool) (CloudantDocumentResponse, error) {
cdr := CloudantDocumentResponse{}
uri := "/" + db.Name() + "/" + doc.Id() + "?rev=" + doc.Revision()
successStatusCode := 201
j, err := json.Marshal(doc)
if err != nil {
return cdr, err
}
if isBatch {
uri += "&batch=ok"
successStatusCode = 202
}
resp, err := db.client.doRequest("PUT", uri, nil, bytes.NewReader(j))
err = db.client.handleResponse(resp, err, successStatusCode, &cdr)
return cdr, err
}
func (db *Database) DeleteDocument(id string, revision string) (CloudantDocumentResponse, error) {
cdr := CloudantDocumentResponse{}
resp, err := db.client.doRequest("DELETE", "/"+db.Name()+"/"+id+"?rev="+revision, nil, nil)
err = db.client.handleResponse(resp, err, 200, &cdr)
return cdr, err
}