improved list performance (1000 posts -> 118ms). #5

pull/9/head
Niko Abeler 6 months ago
parent e4c0550205
commit 54d319e8d7
  1. 31
      user.go
  2. 23
      user_test.go

@ -65,24 +65,31 @@ func (user User) Posts() ([]Post, error) {
}
}
// sort posts by date
sort.Slice(posts, func(i, j int) bool {
_, markdownData_i := posts[i].MarkdownData()
_, markdownData_j := posts[j].MarkdownData()
type PostWithDate struct {
post Post
date time.Time
}
date_i, err := time.Parse(time.RFC1123Z, markdownData_i.Date)
if err != nil {
// invalid date -> use 1970-01-01
date_i = time.Time{}
}
date_j, err := time.Parse(time.RFC1123Z, markdownData_j.Date)
postDates := make([]PostWithDate, len(posts))
for i, post := range posts {
_, meta := post.MarkdownData()
date, err := time.Parse(time.RFC1123Z, meta.Date)
if err != nil {
// invalid date -> use 1970-01-01
date_j = time.Time{}
date = time.Time{}
}
return date_i.After(date_j)
postDates[i] = PostWithDate{post: post, date: date}
}
// sort posts by date
sort.Slice(postDates, func(i, j int) bool {
return postDates[i].date.After(postDates[j].date)
})
for i, post := range postDates {
posts[i] = post.post
}
return posts, nil
}

@ -202,6 +202,29 @@ func TestPostsSortedByPublishingDateLatestFirst(t *testing.T) {
}
}
func TestPostsSortedByPublishingDateLatestFirst2(t *testing.T) {
user := getTestUser()
// Create a new post
posts := []*owl.Post{}
for i := 59; i >= 0; i-- {
post, _ := user.CreateNewPost("testpost")
content := "---\n"
content += "title: Test Post\n"
content += fmt.Sprintf("date: Wed, 17 Aug 2022 10:%02d:02 +0000\n", i)
content += "---\n"
content += "This is a test"
os.WriteFile(post.ContentFile(), []byte(content), 0644)
posts = append(posts, &post)
}
retPosts, _ := user.Posts()
for i, p := range retPosts {
if p.Id() != posts[i].Id() {
t.Error("Wrong Id, Got: " + p.Id())
}
}
}
func TestPostsSortedByPublishingDateBrokenAtBottom(t *testing.T) {
user := getTestUser()
// Create a new post

Loading…
Cancel
Save