-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocument_list.go
84 lines (68 loc) · 2.4 KB
/
document_list.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
package sofa
import (
"encoding/json"
)
// DocumentList is the CouchDB reprentation of a list of Documents where each document
// is contained within a Row along with some metadata. Depending on the view & the request
// paramaters used the documents may or may not be included in the row.
type DocumentList struct {
TotalRows float64 `json:"total_rows"`
Offset float64 `json:"offset"`
Rows []Row `json:"rows"`
}
// Size returns the number of documents currently stored in this DocumentList.
func (dl *DocumentList) Size() int {
// TODO: Possibly should just return `int(dl.TotalRows)`
return len(dl.Rows)
}
// RawDocuments returns the Document from each Row of this DocumentList as a json.RawMessage
// which can then be Unmarshalled into the correct type.
func (dl *DocumentList) RawDocuments() []json.RawMessage {
var docs []json.RawMessage
for _, row := range dl.Rows {
if row.HasDocument() {
docs = append(docs, row.Document)
} else {
docs = append(docs, nil)
}
}
return docs
}
// MapDocuments returns a list containing the document from each row in this DocumentList
// Unmarshalled into a map[string]interface{}.
func (dl *DocumentList) MapDocuments() ([]map[string]interface{}, error) {
var docs []map[string]interface{}
for _, row := range dl.Rows {
if row.HasDocument() {
var rowDoc map[string]interface{}
err := json.Unmarshal(row.Document, &rowDoc)
if err != nil {
return nil, err
}
docs = append(docs, rowDoc)
}
}
return docs, nil
}
// UnmarshalDocuments is a convenience function which unmarshalls just the list of Documents from
// this. Due to a Marshal/Unmarhal cycle this method may be slow. Sometimes slow is fine though.
func (dl *DocumentList) UnmarshalDocuments(docs interface{}) error {
rawDocs := dl.RawDocuments()
jsonAllDocs, err := json.Marshal(rawDocs)
if err != nil {
return err
}
return json.Unmarshal(jsonAllDocs, docs)
}
// Row represents a row in a CouchDB DocumentList. These are mainly returned by views but
// may also be sent to the server as part of the bulk documents API.
type Row struct {
ID string `json:"id,omitempty"`
Key interface{} `json:"key,omitempty"`
Value interface{} `json:"value,omitempty"`
Document json.RawMessage `json:"doc,omitempty"`
}
// HasDocument checks the current Row for the presence of the Document attached to it.
func (r Row) HasDocument() bool {
return r.Document != nil
}