forked from harvesthq/notable
/
notes.go
101 lines (74 loc) · 1.78 KB
/
notes.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
package notable
import (
"encoding/json"
"fmt"
redis "github.com/harvesthq/notable/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
redisurl "github.com/harvesthq/notable/Godeps/_workspace/src/github.com/soveran/redisurl"
"os"
)
func Notes() []Note {
db := redisConnection()
defer db.Close()
var notes []Note
for _, id := range noteIDs(db) {
notes = append(notes, fetchNote(db, id))
}
return notes
}
func AddNote(note Note) {
db := redisConnection()
defer db.Close()
id, err := redis.Int64(db.Do("INCR", "notable:note"))
check(err)
_, err = db.Do("RPUSH", "notable:notes", id)
check(err)
_, err = db.Do("SET", noteKey(id), serialize(note))
check(err)
}
func Reset() {
db := redisConnection()
defer db.Close()
for _, id := range noteIDs(db) {
_, err := db.Do("DEL", noteKey(id))
check(err)
}
_, err := db.Do("DEL", "notable:notes")
check(err)
}
func noteIDs(db redis.Conn) []int64 {
var ids []int64
rawIDs, err := redis.Values(db.Do("LRANGE", "notable:notes", 0, -1))
check(err)
redis.ScanSlice(rawIDs, &ids)
return ids
}
func fetchNote(db redis.Conn, id int64) Note {
noteAsJSON, err := redis.String(db.Do("GET", noteKey(id)))
check(err)
return deserialize(noteAsJSON)
}
func noteKey(id int64) string {
return fmt.Sprintf("notable:note:%d", id)
}
func deserialize(noteAsJSON string) Note {
var note Note
err := json.Unmarshal([]byte(noteAsJSON), ¬e)
check(err)
return note
}
func serialize(note Note) string {
noteAsJSON, err := json.Marshal(note)
check(err)
return string(noteAsJSON)
}
func redisConnection() redis.Conn {
var connection redis.Conn
var err error
if len(os.Getenv("REDIS_URL")) > 0 {
connection, err = redisurl.Connect()
} else {
connection, err = redis.Dial("tcp", ":6379")
}
check(err)
return connection
}