forked from zemirco/couchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
67 lines (61 loc) · 1.83 KB
/
view.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 couchdb
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/google/go-querystring/query"
)
// ViewService is an interface for dealing with a view inside a CouchDB database.
type ViewService interface {
Get(name string, params QueryParameters) (*ViewResponse, error)
Post(name string, keys []string, params QueryParameters) (*ViewResponse, error)
}
// View performs actions and certain view documents
type View struct {
URL string
Client *Client
}
// Get executes specified view function from specified design document.
func (v *View) Get(name string, params QueryParameters) (*ViewResponse, error) {
q, err := query.Values(params)
if err != nil {
return nil, err
}
uri := fmt.Sprintf("%s_view/%s?%s", v.URL, name, q.Encode())
res, err := v.Client.Request(http.MethodGet, uri, nil, "")
if err != nil {
return nil, err
}
defer res.Body.Close()
var response ViewResponse
return &response, json.NewDecoder(res.Body).Decode(&response)
}
// Post executes specified view function from specified design document.
// Unlike View.Get for accessing views, View.Post supports
// the specification of explicit keys to be retrieved from the view results.
func (v *View) Post(name string, keys []string, params QueryParameters) (*ViewResponse, error) {
content := struct {
Keys []string `json:"keys"`
}{
Keys: keys,
}
// create POST body
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(content); err != nil {
return nil, err
}
// create query string
q, err := query.Values(params)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s_view/%s?%s", v.URL, name, q.Encode())
res, err := v.Client.Request(http.MethodPost, url, &b, "application/json")
if err != nil {
return nil, err
}
defer res.Body.Close()
var response ViewResponse
return &response, json.NewDecoder(res.Body).Decode(&response)
}