appview/pagination: context based pagination #712

merged
opened by boltless.me targeting master from push-ztsunkmpnsry

introduce helper methods: IntoContext and FromContext these will help using pagination obj form context easier and make it less error-prune by using private empty struct as a key instead of raw string

Signed-off-by: Seongmin Lee git@boltless.me

Changed files
+27 -15
appview
issues
middleware
notifications
pagination
state
+1 -5
appview/issues/issues.go
···
isOpen = true
}
-
page, ok := r.Context().Value("page").(pagination.Page)
-
if !ok {
-
l.Error("failed to get page")
-
page = pagination.FirstPage()
-
}
+
page := pagination.FromContext(r.Context())
user := rp.oauth.GetUser(r)
f, err := rp.repoResolver.Resolve(r)
+1 -1
appview/middleware/middleware.go
···
}
}
-
ctx := context.WithValue(r.Context(), "page", page)
+
ctx := pagination.IntoContext(r.Context(), page)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
+1 -5
appview/notifications/notifications.go
···
l := n.logger.With("handler", "notificationsPage")
user := n.oauth.GetUser(r)
-
page, ok := r.Context().Value("page").(pagination.Page)
-
if !ok {
-
l.Error("failed to get page")
-
page = pagination.FirstPage()
-
}
+
page := pagination.FromContext(r.Context())
total, err := db.CountNotifications(
n.db,
+23
appview/pagination/page.go
···
package pagination
+
import "context"
+
type Page struct {
Offset int // where to start from
Limit int // number of items in a page
···
}
}
+
type ctxKey struct{}
+
+
func IntoContext(ctx context.Context, page Page) context.Context {
+
return context.WithValue(ctx, ctxKey{}, page)
+
}
+
+
func FromContext(ctx context.Context) Page {
+
if ctx == nil {
+
return FirstPage()
+
}
+
v := ctx.Value(ctxKey{})
+
if v == nil {
+
return FirstPage()
+
}
+
page, ok := v.(Page)
+
if !ok {
+
return FirstPage()
+
}
+
return page
+
}
+
func (p Page) Previous() Page {
if p.Offset-p.Limit < 0 {
return FirstPage()
+1 -4
appview/state/gfi.go
···
func (s *State) GoodFirstIssues(w http.ResponseWriter, r *http.Request) {
user := s.oauth.GetUser(r)
-
page, ok := r.Context().Value("page").(pagination.Page)
-
if !ok {
-
page = pagination.FirstPage()
-
}
+
page := pagination.FromContext(r.Context())
goodFirstIssueLabel := fmt.Sprintf("at://%s/%s/%s", consts.TangledDid, tangled.LabelDefinitionNSID, "good-first-issue")