summaryrefslogtreecommitdiff
path: root/system/api/handlers.go
diff options
context:
space:
mode:
Diffstat (limited to 'system/api/handlers.go')
-rw-r--r--system/api/handlers.go66
1 files changed, 58 insertions, 8 deletions
diff --git a/system/api/handlers.go b/system/api/handlers.go
index 0c9139f..aa3b936 100644
--- a/system/api/handlers.go
+++ b/system/api/handlers.go
@@ -5,6 +5,8 @@ import (
"encoding/json"
"log"
"net/http"
+ "strconv"
+ "strings"
"github.com/bosssauce/ponzu/content"
"github.com/bosssauce/ponzu/system/db"
@@ -28,24 +30,72 @@ func typesHandler(res http.ResponseWriter, req *http.Request) {
func postsHandler(res http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
t := q.Get("type")
- // TODO: implement pagination
- // num := q.Get("num")
- // page := q.Get("page")
-
- // TODO: inplement time-based ?after=time.Time, ?before=time.Time between=time.Time|time.Time
-
if t == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
- posts := db.ContentAll(t)
+ count, err := strconv.Atoi(q.Get("count")) // int: determines number of posts to return (10 default, -1 is all)
+ if err != nil {
+ if q.Get("count") == "" {
+ count = 10
+ } else {
+ res.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ }
+
+ offset, err := strconv.Atoi(q.Get("offset")) // int: multiplier of count for pagination (0 default)
+ if err != nil {
+ if q.Get("offset") == "" {
+ count = 0
+ } else {
+ res.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ }
+
+ order := strings.ToUpper(q.Get("order")) // string: sort order of posts by timestamp ASC / DESC (DESC default)
+ if order != "ASC" || order == "" {
+ order = "DESC"
+ }
+
+ // TODO: time-based ?after=time.Time, ?before=time.Time between=time.Time|time.Time
+
+ posts := db.ContentAll(t + "_sorted")
var all = []json.RawMessage{}
for _, post := range posts {
all = append(all, post)
}
- j, err := fmtJSON(all...)
+ var start, end int
+ switch count {
+ case -1:
+ start = 0
+ end = len(posts)
+
+ default:
+ start = count * offset
+ end = start + count
+ }
+
+ // bounds check on posts given the start & end count
+ if start > len(posts) {
+ start = len(posts) - count
+ }
+ if end > len(posts) {
+ end = len(posts)
+ }
+
+ // reverse the sorted order if ASC
+ if order == "ASC" {
+ all = []json.RawMessage{}
+ for i := len(posts) - 1; i >= 0; i-- {
+ all = append(all, posts[i])
+ }
+ }
+
+ j, err := fmtJSON(all[start:end]...)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return