forked from fjl/go-couchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
design.go
63 lines (56 loc) · 1.73 KB
/
design.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
package couchdb
import (
"crypto/sha256"
"fmt"
"sort"
"strings"
)
// Design is a structure that can be used for creating design documents
// ready to be synched with the database.
// At the moment we're only support very basic design documents with views,
// please feel free to add new properties.
type Design struct {
ID string `json:"_id" yaml:"_id"`
Rev string `json:"_rev,omitempty" yaml:"_rev"`
Language string `json:"language" yaml:"language"`
Views map[string]*View `json:"views,omitempty" yaml:"views"`
}
// View is a view definition to be used inside a Design document.
type View struct {
Map string `json:"map" yaml:"map"`
Reduce string `json:"reduce,omitempty" yaml:"reduce"`
}
// NewDesign will instantiate a design document instance with the base properties
// set and ready to use.
func NewDesign(name string) *Design {
d := &Design{
ID: "_design/" + name,
Language: "javascript",
Views: make(map[string]*View),
}
return d
}
// AddView is a helper to be able to add a view definition to the design.
func (d *Design) AddView(name string, view *View) {
d.Views[name] = view
}
// ViewChecksum will generate a checksum or hash of the design documents
// views such that two design documents can be compared to see if an update
// is required.
// For the time being we assume that the map will maintain the order of
// views.
func (d *Design) ViewChecksum() string {
var items []string
var keys []string
for key := range d.Views {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
view := d.Views[key]
items = append(items, key, "map", view.Map, "reduce", view.Reduce)
}
text := strings.Join(items, ":")
sum := sha256.Sum256([]byte(text))
return fmt.Sprintf("%x", sum)
}