/
api.go
103 lines (89 loc) · 2.03 KB
/
api.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
94
95
96
97
98
99
100
101
102
103
package main
import (
"encoding/json"
"log/syslog"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type TodoItem struct {
Id string
Text string
}
func apiGet(s *mgo.Session, label string, todo string, mlog *syslog.Writer) string {
if len(label) == 0 {
return ""
}
list, err := dbQuery(s, label)
if err != nil {
mlog.Err("Error: db query went bad: " + err.Error())
return "Error"
}
todos := make([]TodoItem, len(list))
count := 0
for i, todo := range list {
todos[i].Text = todo.Text
todos[i].Id = todo.Id.Hex()
count += 1
}
jsonOut := struct {
Label string
Count int
Todos []TodoItem
}{label, count, todos}
out, err := json.MarshalIndent(jsonOut, "", " ")
if err != nil {
mlog.Err("Error: could not properly construct json")
return "Error"
}
return string(out)
}
func apiRemove(s *mgo.Session, label string, id string, mlog *syslog.Writer) string {
if len(label) == 0 {
return ""
}
err := dbRemove(s, label, MongoTodo{Id: bson.ObjectIdHex(id), Text: ""})
if err != nil {
mlog.Err("Error: db remove went bad: " + err.Error())
return "Error"
}
return "Removing: " + id + " from: " + label
}
func apiAdd(s *mgo.Session, label string, todo string, mlog *syslog.Writer) string {
if len(label) == 0 {
return ""
}
newTodo := MongoTodo{Id: bson.NewObjectId(), Text: todo}
err := dbInsert(s, label, newTodo)
if err != nil {
mlog.Err("Error: db insert went bad: " + err.Error())
return "Error"
}
return newTodo.Id.Hex()
}
func apiCount(s *mgo.Session, mlog *syslog.Writer) string {
itemCount, listCount, err := dbCountLists(s)
var countOut struct {
ItemCount int
List []struct {
Label string
Count int
}
}
countOut.ItemCount = listCount
countOut.List = make([]struct {
Label string
Count int
}, len(itemCount))
i := 0
for k, v := range itemCount {
countOut.List[i].Label = k
countOut.List[i].Count = v
i += 1
}
out, err := json.MarshalIndent(countOut, "", " ")
if err != nil {
mlog.Err("Error: could not properly construct json")
return "Error"
}
return string(out)
}