Skip to content

Commit

Permalink
09-Pagination add paginate
Browse files Browse the repository at this point in the history
  • Loading branch information
bonfy committed Oct 8, 2018
1 parent f106252 commit fd3c825
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 10 deletions.
2 changes: 2 additions & 0 deletions controller/g.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ var (
sessionName string
flashName string
store *sessions.CookieStore
pageLimit int
)

func init() {
templates = PopulateTemplates()
store = sessions.NewCookieStore([]byte("something-very-secret"))
sessionName = "go-mega"
flashName = "go-flash"
pageLimit = 5
}

// Startup func
Expand Down
6 changes: 4 additions & 2 deletions controller/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ func (h home) registerRoutes() {
func indexHandler(w http.ResponseWriter, r *http.Request) {
tpName := "index.html"
vop := vm.IndexViewModelOp{}
page := getPage(r)
username, _ := getSessionUser(r)
if r.Method == http.MethodGet {
flash := getFlash(w, r)
v := vop.GetVM(username, flash)
v := vop.GetVM(username, flash, page, pageLimit)
templates[tpName].Execute(w, &v)
}
if r.Method == http.MethodPost {
Expand Down Expand Up @@ -119,8 +120,9 @@ func profileHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
pUser := vars["username"]
sUser, _ := getSessionUser(r)
page := getPage(r)
vop := vm.ProfileViewModelOp{}
v, err := vop.GetVM(sUser, pUser)
v, err := vop.GetVM(sUser, pUser, page, pageLimit)
if err != nil {
msg := fmt.Sprintf("user ( %s ) does not exist", pUser)
w.Write([]byte(msg))
Expand Down
17 changes: 17 additions & 0 deletions controller/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"os"
"regexp"
"strconv"

"github.com/bonfy/go-mega-code/vm"
)
Expand Down Expand Up @@ -192,3 +193,19 @@ func getFlash(w http.ResponseWriter, r *http.Request) string {
session.Save(r, w)
return fmt.Sprintf("%v", fm[0])
}

func getPage(r *http.Request) int {
url := r.URL // net/url.URL
query := url.Query() // Values (map[string][]string)

q := query.Get("page")
if q == "" {
return 1
}

page, err := strconv.Atoi(q)
if err != nil {
return 1
}
return page
}
12 changes: 12 additions & 0 deletions model/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,15 @@ func GetPostsByUserID(id int) (*[]Post, error) {
}
return &posts, nil
}

// GetPostsByUserIDPageAndLimit func
func GetPostsByUserIDPageAndLimit(id, page, limit int) (*[]Post, int, error) {
var total int
var posts []Post
offset := (page - 1) * limit
if err := db.Preload("User").Order("timestamp desc").Where("user_id=?", id).Offset(offset).Limit(limit).Find(&posts).Error; err != nil {
return nil, total, err
}
db.Model(&Post{}).Where("user_id=?", id).Count(&total)
return &posts, total, nil
}
13 changes: 13 additions & 0 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ func (u *User) FollowingPosts() (*[]Post, error) {
return &posts, nil
}

// FollowingPostsByPageAndLimit func
func (u *User) FollowingPostsByPageAndLimit(page, limit int) (*[]Post, int, error) {
var total int
var posts []Post
offset := (page - 1) * limit
ids := u.FollowingIDs()
if err := db.Preload("User").Order("timestamp desc").Where("user_id in (?)", ids).Offset(offset).Limit(limit).Find(&posts).Error; err != nil {
return nil, total, err
}
db.Model(&Post{}).Where("user_id in (?)", ids).Count(&total)
return &posts, total, nil
}

// IsFollowedByUser func
func (u *User) IsFollowedByUser(username string) bool {
user, _ := GetUserByUsername(username)
Expand Down
10 changes: 9 additions & 1 deletion templates/content/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ <h1>Hello, {{.CurrentUser}}!</h1>
<table>
<tr valign="top">
<td><img src="{{.User.Avatar}}&s=36"></td>
<td>{{ .User.Username }} says:<br>{{ .Body }}</td>
<td><a href="/user/{{.User.Username}}">{{ .User.Username }}</a> says:<br>{{ .Body }}</td>
</tr>
</table>
{{end}}

{{ if gt .PrevPage 0 }}
<a href="/?page={{.PrevPage}}">Newer posts</a>
{{ end }}
{{ if gt .NextPage 0 }}
<a href="/?page={{.NextPage}}">Older posts</a>
{{ end }}

{{end}}
9 changes: 8 additions & 1 deletion templates/content/profile.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,16 @@ <h1>User: {{.ProfileUser.Username}}</h1>
<table>
<tr valign="top">
<td><img src="{{.User.Avatar}}&s=36"></td>
<td>{{ .User.Username }} says:<br>{{ .Body }}</td>
<td><a href="/user/{{.User.Username}}">{{ .User.Username }}</a> says:<br>{{ .Body }}</td>
</tr>
</table>
{{end}}

{{ if gt .PrevPage 0 }}
<a href="/user/{{.ProfileUser.Username}}?page={{.PrevPage}}">Newer posts</a>
{{ end }}
{{ if gt .NextPage 0 }}
<a href="/user/{{.ProfileUser.Username}}?page={{.NextPage}}">Older posts</a>
{{ end }}

{{end}}
28 changes: 28 additions & 0 deletions vm/g.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,31 @@ func (v *BaseViewModel) SetTitle(title string) {
func (v *BaseViewModel) SetCurrentUser(username string) {
v.CurrentUser = username
}

// BasePageViewModel struct
type BasePageViewModel struct {
PrevPage int
NextPage int
Total int
CurrentPage int
Limit int
}

// SetPrevAndNextPage func
func (v *BasePageViewModel) SetPrevAndNextPage() {
if v.CurrentPage > 1 {
v.PrevPage = v.CurrentPage - 1
}

if (v.Total-1)/v.Limit >= v.CurrentPage {
v.NextPage = v.CurrentPage + 1
}
}

// SetBasePageViewModel func
func (v *BasePageViewModel) SetBasePageViewModel(total, page, limit int) {
v.Total = total
v.CurrentPage = page
v.Limit = limit
v.SetPrevAndNextPage()
}
12 changes: 9 additions & 3 deletions vm/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,22 @@ type IndexViewModel struct {
BaseViewModel
Posts []model.Post
Flash string

BasePageViewModel
}

// IndexViewModelOp struct
type IndexViewModelOp struct{}

// GetVM func
func (IndexViewModelOp) GetVM(username string, flash string) IndexViewModel {
func (IndexViewModelOp) GetVM(username, flash string, page, limit int) IndexViewModel {
u, _ := model.GetUserByUsername(username)
posts, _ := u.FollowingPosts()
v := IndexViewModel{BaseViewModel{Title: "Homepage"}, *posts, flash}
posts, total, _ := u.FollowingPostsByPageAndLimit(page, limit)
v := IndexViewModel{}
v.SetTitle("Homepage")
v.Posts = *posts
v.Flash = flash
v.SetBasePageViewModel(total, page, limit)
v.SetCurrentUser(username)
return v
}
Expand Down
7 changes: 4 additions & 3 deletions vm/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,24 @@ type ProfileViewModel struct {
FollowersCount int
FollowingCount int
ProfileUser model.User
BasePageViewModel
}

// ProfileViewModelOp struct
type ProfileViewModelOp struct{}

// GetVM func
func (ProfileViewModelOp) GetVM(sUser, pUser string) (ProfileViewModel, error) {
func (ProfileViewModelOp) GetVM(sUser, pUser string, page, limit int) (ProfileViewModel, error) {
v := ProfileViewModel{}
v.SetTitle("Profile")
u, err := model.GetUserByUsername(pUser)
if err != nil {
return v, err
}
posts, _ := model.GetPostsByUserID(u.ID)
posts, total, _ := model.GetPostsByUserIDPageAndLimit(u.ID, page, limit)
v.ProfileUser = *u
v.Editable = (sUser == pUser)

v.SetBasePageViewModel(total, page, limit)
if !v.Editable {
v.IsFollow = u.IsFollowedByUser(sUser)
}
Expand Down

0 comments on commit fd3c825

Please sign in to comment.