Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(blog): store posts in slices & include chronological sorting #1367

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 39 additions & 76 deletions examples/gno.land/p/demo/blog/blog.gno
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,21 @@ package blog
import (
"errors"
"std"
"strconv"
"strings"
"time"

"gno.land/p/demo/avl"
"gno.land/p/demo/mux"
"gno.land/p/demo/ufmt"
)

type Blog struct {
Title string
Prefix string // i.e. r/gnoland/blog:
Posts avl.Tree // slug -> Post
NoBreadcrumb bool
}

func (b Blog) RenderLastPostsWidget(limit int) string {
output := ""
i := 0
b.Posts.Iterate("", "", func(key string, value interface{}) bool {
p := value.(*Post)
for i, p := range b.Posts {
if i >= limit {
break
}
output += ufmt.Sprintf("- [%s](%s)\n", p.Title, p.URL())
i++
return i >= limit
})
}
return output
}

Expand All @@ -36,17 +26,17 @@ func (b Blog) RenderHome(res *mux.ResponseWriter, req *mux.Request) {
res.Write(breadcrumb([]string{b.Title}))
}

if b.Posts.Size() == 0 {
if len(b.Posts) == 0 {
res.Write("No posts.")
return
}

res.Write("<div class='columns-3'>")
b.Posts.Iterate("", "", func(key string, value interface{}) bool {
post := value.(*Post)

for _, post := range b.Posts {
res.Write(post.RenderListItem())
return false
})
}

res.Write("</div>")

// FIXME: tag list/cloud.
Expand All @@ -55,33 +45,31 @@ func (b Blog) RenderHome(res *mux.ResponseWriter, req *mux.Request) {
func (b Blog) RenderPost(res *mux.ResponseWriter, req *mux.Request) {
slug := req.GetVar("slug")

post, found := b.Posts.Get(slug)
if !found {
post := b.Posts.GetPostBySlug(slug)

if post == nil {
res.Write("404")
return
}
p := post.(*Post)

if !b.NoBreadcrumb {
breadStr := breadcrumb([]string{
ufmt.Sprintf("[%s](%s)", b.Title, b.Prefix),
"p",
p.Title,
post.Title,
})
res.Write(breadStr)
}

// output += ufmt.Sprintf("## [%s](%s)\n", p.Title, p.URL())
res.Write(p.Body + "\n\n")
res.Write(p.RenderTagList() + "\n\n")
res.Write(formatAuthorAndDate(p.Author, p.CreatedAt) + "\n\n")
res.Write(post.Body + "\n\n")
res.Write(post.RenderTagList() + "\n\n")
res.Write(formatAuthorAndDate(post.Author, post.CreatedAt) + "\n\n")

// comments
p.Comments.ReverseIterate("", "", func(key string, value interface{}) bool {
comment := value.(*Comment)
for _, comment := range post.Comments {
res.Write(comment.RenderListItem())
return false
})
}
}

func (b Blog) RenderTag(res *mux.ResponseWriter, req *mux.Request) {
Expand All @@ -102,15 +90,13 @@ func (b Blog) RenderTag(res *mux.ResponseWriter, req *mux.Request) {
}

nb := 0
b.Posts.Iterate("", "", func(key string, value interface{}) bool {
post := value.(*Post)
if !post.HasTag(slug) {
return false
for _, post := range b.Posts {
if post.HasTag(slug) {
res.Write(post.RenderListItem())
nb++
}
res.Write(post.RenderListItem())
nb++
return false
})
}

if nb == 0 {
res.Write("No posts.")
}
Expand All @@ -125,8 +111,8 @@ func (b Blog) Render(path string) string {
}

func (b *Blog) NewPost(author std.Address, slug, title, body string, tags []string) error {
_, found := b.Posts.Get(slug)
if found {
p := b.Posts.GetPostBySlug(slug)
if p != nil {
return errors.New("slug already exists.")
}

Expand Down Expand Up @@ -159,31 +145,10 @@ func (b *Blog) prepareAndSetPost(post *Post) error {
post.Blog = b
post.UpdatedAt = time.Now()

b.Posts.Set(post.Slug, post)
b.Posts = append(b.Posts, post)
return nil
}

func (b *Blog) GetPost(slug string) *Post {
post, found := b.Posts.Get(slug)
if !found {
return nil
}
return post.(*Post)
}

type Post struct {
Blog *Blog
Slug string // FIXME: save space?
Title string
Body string
CreatedAt time.Time
UpdatedAt time.Time
Comments avl.Tree
Author std.Address
Tags []string
CommentIndex int
}

func (p *Post) Update(title, body string, tags []string) error {
p.Title = title
p.Body = body
Expand All @@ -195,10 +160,10 @@ func (p *Post) AddComment(author std.Address, comment string) error {
if p == nil {
return ErrNoSuchPost
}
p.CommentIndex++
commentKey := strconv.Itoa(p.CommentIndex)
comment = strings.TrimSpace(comment)
p.Comments.Set(commentKey, &Comment{

p.Comments = append(p.Comments, &Comment{
ID: p.commentID.Next(),
Post: p,
CreatedAt: time.Now(),
Author: author,
Expand All @@ -208,12 +173,17 @@ func (p *Post) AddComment(author std.Address, comment string) error {
return nil
}

func (p *Post) DeleteComment(index int) error {
func (p *Post) DeleteComment(id int) error {
if p == nil {
return ErrNoSuchPost
}
commentKey := strconv.Itoa(index)
p.Comments.Remove(commentKey)

updatedSlice, err := p.Comments.RemoveByID(id)
if err != nil {
return err
}

p.Comments = updatedSlice
return nil
}

Expand Down Expand Up @@ -279,13 +249,6 @@ func (p *Post) Summary() string {
return strings.Join(lines[0:3], "\n") + "..."
}

type Comment struct {
Post *Post
CreatedAt time.Time
Author std.Address
Comment string
}

func (c Comment) RenderListItem() string {
output := ""
output += ufmt.Sprintf("#### %s\n", formatAuthorAndDate(c.Author, c.CreatedAt))
Expand Down
1 change: 1 addition & 0 deletions examples/gno.land/p/demo/blog/errors.gno
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ package blog
import "errors"

var ErrNoSuchPost = errors.New("no such post")
var ErrNoSuchComment = errors.New("no such comment")
2 changes: 1 addition & 1 deletion examples/gno.land/p/demo/blog/gno.mod
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module gno.land/p/demo/blog

require (
gno.land/p/demo/avl v0.0.0-latest
gno.land/p/demo/mux v0.0.0-latest
gno.land/p/demo/seqid v0.0.0-latest
gno.land/p/demo/ufmt v0.0.0-latest
)
38 changes: 38 additions & 0 deletions examples/gno.land/p/demo/blog/types.gno
leohhhn marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package blog

import (
"gno.land/p/demo/seqid"
"std"
"time"
Comment on lines +4 to +6
Copy link
Member

@moul moul Dec 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we configure our linter to flag import style issues?

cc @gnolang/tech-staff

)

type Blog struct {
Title string
Prefix string // i.e. r/gnoland/blog:
Posts postSlice
NoBreadcrumb bool
}

type Post struct {
Blog *Blog
Slug string
Title string
Body string
CreatedAt time.Time
UpdatedAt time.Time
Comments commentSlice
Author std.Address
Tags []string
commentID seqid.ID
}

type Comment struct {
ID seqid.ID
Post *Post
CreatedAt time.Time
Author std.Address
Comment string
}

type postSlice []*Post
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we use seqid with an avl.Tree instead of a slice? I believe it allows for an always growing key string, which would help keep the avl.Tree ordered. cc @thehowl

type commentSlice []*Comment
52 changes: 51 additions & 1 deletion examples/gno.land/p/demo/blog/util.gno
Original file line number Diff line number Diff line change
@@ -1,7 +1,57 @@
package blog

import "strings"
import (
"sort"
"strings"
)

func breadcrumb(parts []string) string {
return "# " + strings.Join(parts, " / ") + "\n\n"
}

func (p postSlice) GetPostBySlug(slug string) *Post {
for _, post := range p {
if post.Slug == slug {
Comment on lines +13 to +14
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The goal of an AVL tree is to optimize the lazy loading of necessary data and skip unnecessary posts. Unlike this implementation, an AVL tree is scalable and will efficiently handle larger data sets.

return post
}
}
return nil
}

func (c commentSlice) RemoveByID(id int) (commentSlice, error) {
for i, comment := range c {
if comment.ID == id {
return append(c[:i], c[i+1:]...), nil
}
}
return nil, ErrNoSuchComment
}

// Sort interface implementations for postSlice & commentSlice

func (p postSlice) Len() int {
return len(p)
}

func (p postSlice) Less(i, j int) bool {
return p[i].CreatedAt.Before(p[j].CreatedAt)
}

func (p postSlice) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
leohhhn marked this conversation as resolved.
Show resolved Hide resolved

func (c commentSlice) Len() int {
return len(c)
}

func (c commentSlice) Less(i, j int) bool {
return c[i].CreatedAt.Before(c[j].CreatedAt)
}

func (c commentSlice) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}

var _ sort.Interface = postSlice(nil)
var _ sort.Interface = commentSlice(nil)
4 changes: 2 additions & 2 deletions examples/gno.land/r/gnoland/blog/admin.gno
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func ModEditPost(slug, title, body, tags string) {
assertIsModerator()

tagList := strings.Split(tags, ",")
err := b.GetPost(slug).Update(title, body, tagList)
err := b.Posts.GetPostBySlug(slug).Update(title, body, tagList)
checkErr(err)
}

Expand All @@ -69,7 +69,7 @@ func ModDelCommenter(addr std.Address) {
func ModDelComment(slug string, index int) {
assertIsModerator()

err := b.GetPost(slug).DeleteComment(index)
err := b.Posts.GetPostBySlug(slug).DeleteComment(index)
checkErr(err)
}

Expand Down
2 changes: 1 addition & 1 deletion examples/gno.land/r/gnoland/blog/gnoblog.gno
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func AddComment(postSlug, comment string) {
assertNotInPause()

caller := std.GetOrigCaller()
err := b.GetPost(postSlug).AddComment(caller, comment)
err := b.Posts.GetPostBySlug(postSlug).AddComment(caller, comment)
checkErr(err)
}

Expand Down
2 changes: 1 addition & 1 deletion examples/gno.land/r/gnoland/pages/admin.gno
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func ModEditPost(slug, title, body, tags string) {
assertIsModerator()

tagList := strings.Split(tags, ",")
err := b.GetPost(slug).Update(title, body, tagList)
err := b.Posts.GetPostBySlug(slug).Update(title, body, tagList)
checkErr(err)
}

Expand Down
2 changes: 1 addition & 1 deletion examples/gno.land/r/manfred/present/admin.gno
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func ModEditPost(slug, title, body, tags string) {
assertIsModerator()

tagList := strings.Split(tags, ",")
err := b.GetPost(slug).Update(title, body, tagList)
err := b.Posts.GetPostBySlug(slug).Update(title, body, tagList)
checkErr(err)
}

Expand Down
Loading