Skip to content

Commit b6f2ad4

Browse files
committed
db: use canonical link short name in stats
When loading stats from the database, map IDs back to their canonical short name, which is what we want to show in the frontend. This is only called once on cold start, so performance of loading all links isn't a big concern. Fixes #13 Signed-off-by: Will Norris <[email protected]>
1 parent ef8311b commit b6f2ad4

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

db.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,15 @@ func (s *SQLiteDB) Save(link *Link) error {
124124

125125
// LoadStats returns click stats for links.
126126
func (s *SQLiteDB) LoadStats() (ClickStats, error) {
127+
allLinks, err := s.LoadAll()
128+
if err != nil {
129+
return nil, err
130+
}
131+
linkmap := make(map[string]string, len(allLinks)) // map ID => Short
132+
for _, link := range allLinks {
133+
linkmap[linkID(link.Short)] = link.Short
134+
}
135+
127136
rows, err := s.db.Query("SELECT ID, sum(Clicks) FROM Stats GROUP BY ID")
128137
if err != nil {
129138
return nil, err
@@ -136,7 +145,8 @@ func (s *SQLiteDB) LoadStats() (ClickStats, error) {
136145
if err != nil {
137146
return nil, err
138147
}
139-
stats[id] = clicks
148+
short := linkmap[id]
149+
stats[short] = clicks
140150
}
141151
return stats, rows.Err()
142152
}

db_test.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,23 +60,25 @@ func Test_SQLiteDB_SaveLoadStats(t *testing.T) {
6060
// preload some links
6161
links := []*Link{
6262
{Short: "a"},
63-
{Short: "b"},
63+
{Short: "B-c"},
6464
}
6565
for _, link := range links {
6666
if err := db.Save(link); err != nil {
6767
t.Error(err)
6868
}
6969
}
7070

71-
// stats to record and then retrieve
71+
// Stats to record and then retrieve.
72+
// Stats to store do not need to be their canonical short name,
73+
// but returned stats always should be.
7274
stats := []ClickStats{
7375
{"a": 1},
74-
{"b": 1},
75-
{"a": 1, "b": 2},
76+
{"b-c": 1},
77+
{"a": 1, "bc": 2},
7678
}
7779
want := ClickStats{
78-
"a": 2,
79-
"b": 3,
80+
"a": 2,
81+
"B-c": 3,
8082
}
8183

8284
for _, s := range stats {

0 commit comments

Comments
 (0)