-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesign.go
More file actions
81 lines (78 loc) · 2.08 KB
/
design.go
File metadata and controls
81 lines (78 loc) · 2.08 KB
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
package couchdb
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
const (
fileNameMap = "map.js"
fileNameReduce = "reduce.js"
)
// Parse takes a location and parses all design documents with corresponding views.
// The folder structure must look like this.
//
// design
// |-- player
// | |-- byAge
// | | |-- map.js
// | | `-- reduce.js
// | `-- byName
// | `-- map.js
// `-- user
// |-- byEmail
// | |-- map.js
// | `-- reduce.js
// `-- byUsername
// `-- map.js
func (c *CouchDBClient) Parse(dirname string) ([]DesignDocument, error) {
docs := []DesignDocument{}
// get all directories inside location which will become separate design documents
dirs, err := ioutil.ReadDir(dirname)
if err != nil {
return nil, err
}
for _, dir := range dirs {
designDocumentName := dir.Name()
ff, err := ioutil.ReadDir(filepath.Join(dirname, designDocumentName))
if err != nil {
return nil, err
}
d := DesignDocument{
Document: Document{
ID: fmt.Sprintf("_design/%s", designDocumentName),
},
Language: langJavaScript,
Views: map[string]DesignDocumentView{},
}
for _, j := range ff {
viewName := j.Name()
// create new view inside design document
view := DesignDocumentView{}
// get map function
pathMap := filepath.Join(dirname, designDocumentName, viewName, fileNameMap)
bMap, err := ioutil.ReadFile(pathMap)
if err != nil {
return nil, err
}
view.Map = string(bMap)
// get reduce function only if it exists
pathReduce := filepath.Join(dirname, designDocumentName, viewName, fileNameReduce)
if _, err := os.Stat(pathReduce); err != nil {
// ignore error that file does not exist but return other errors
if !os.IsNotExist(err) {
return nil, err
}
} else {
bReduce, err := ioutil.ReadFile(pathReduce)
if err != nil {
return nil, err
}
view.Reduce = string(bReduce)
}
d.Views[viewName] = view
}
docs = append(docs, d)
}
return docs, nil
}