Monorepo for Tangled tangled.org

appview/pagination: context based pagination

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>

authored by boltless.me and committed by Tangled f37868d4 3f65e302

Changed files
+27 -15
appview
issues
middleware
notifications
pagination
state
+1 -5
appview/issues/issues.go
··· 770 770 isOpen = true 771 771 } 772 772 773 - page, ok := r.Context().Value("page").(pagination.Page) 774 - if !ok { 775 - l.Error("failed to get page") 776 - page = pagination.FirstPage() 777 - } 773 + page := pagination.FromContext(r.Context()) 778 774 779 775 user := rp.oauth.GetUser(r) 780 776 f, err := rp.repoResolver.Resolve(r)
+1 -1
appview/middleware/middleware.go
··· 105 105 } 106 106 } 107 107 108 - ctx := context.WithValue(r.Context(), "page", page) 108 + ctx := pagination.IntoContext(r.Context(), page) 109 109 next.ServeHTTP(w, r.WithContext(ctx)) 110 110 }) 111 111 }
+1 -5
appview/notifications/notifications.go
··· 49 49 l := n.logger.With("handler", "notificationsPage") 50 50 user := n.oauth.GetUser(r) 51 51 52 - page, ok := r.Context().Value("page").(pagination.Page) 53 - if !ok { 54 - l.Error("failed to get page") 55 - page = pagination.FirstPage() 56 - } 52 + page := pagination.FromContext(r.Context()) 57 53 58 54 total, err := db.CountNotifications( 59 55 n.db,
+23
appview/pagination/page.go
··· 1 1 package pagination 2 2 3 + import "context" 4 + 3 5 type Page struct { 4 6 Offset int // where to start from 5 7 Limit int // number of items in a page ··· 10 12 Offset: 0, 11 13 Limit: 30, 12 14 } 15 + } 16 + 17 + type ctxKey struct{} 18 + 19 + func IntoContext(ctx context.Context, page Page) context.Context { 20 + return context.WithValue(ctx, ctxKey{}, page) 21 + } 22 + 23 + func FromContext(ctx context.Context) Page { 24 + if ctx == nil { 25 + return FirstPage() 26 + } 27 + v := ctx.Value(ctxKey{}) 28 + if v == nil { 29 + return FirstPage() 30 + } 31 + page, ok := v.(Page) 32 + if !ok { 33 + return FirstPage() 34 + } 35 + return page 13 36 } 14 37 15 38 func (p Page) Previous() Page {
+1 -4
appview/state/gfi.go
··· 18 18 func (s *State) GoodFirstIssues(w http.ResponseWriter, r *http.Request) { 19 19 user := s.oauth.GetUser(r) 20 20 21 - page, ok := r.Context().Value("page").(pagination.Page) 22 - if !ok { 23 - page = pagination.FirstPage() 24 - } 21 + page := pagination.FromContext(r.Context()) 25 22 26 23 goodFirstIssueLabel := fmt.Sprintf("at://%s/%s/%s", consts.TangledDid, tangled.LabelDefinitionNSID, "good-first-issue") 27 24