tavern/web/handler_tags.go

85 lines
2.0 KiB
Go

package web
import (
"fmt"
"math"
"net/http"
"github.com/gin-gonic/gin"
"github.com/ngerakines/tavern/storage"
)
func (h handler) getTaggedObjects(c *gin.Context) {
if !requireAccept(c, "application/ld+json") {
h.writeJSONError(c, http.StatusNotAcceptable, fmt.Errorf("client does not indicate that they accept application/jrd+json responses"))
return
}
ctx := c.Request.Context()
tag := c.Param("tag")
page := intParam(c, "page", 0)
limit := 50
total, err := h.storage.CountObjectPayloadsInTagFeed(ctx, tag)
if err != nil {
h.internalServerErrorJSON(c, err)
return
}
lastPage := 1
if total > limit {
lastPage = int(math.Ceil(float64(total) / float64(limit)))
}
response := storage.EmptyPayload()
if page == 0 {
response["@context"] = "https://www.w3.org/ns/activitystreams"
response["id"] = fmt.Sprintf("https://%s/tags/%s", h.domain, tag)
response["type"] = "OrderedCollection"
response["totalItems"] = total
if total > 0 {
response["first"] = fmt.Sprintf("https://%s/tags/%s?page=1", h.domain, tag)
response["last"] = fmt.Sprintf("https://%s/tags/%s?page=%d", h.domain, tag, lastPage)
}
h.writeJSONLD(c, http.StatusOK, response)
return
}
response["id"] = fmt.Sprintf("https://%s/tags/%s?page=%d", h.domain, tag, page)
response["type"] = "OrderedCollectionPage"
response["totalItems"] = total
response["partOf"] = fmt.Sprintf("https://%s/tags/%s", h.domain, tag)
if total == 0 || page > lastPage {
response["orderedItems"] = []interface{}{}
h.writeJSONLD(c, http.StatusOK, response)
return
}
objects, err := h.storage.ListObjectPayloadsInTagFeed(ctx, tag /*, limit, (page-1)*limit */)
if err != nil {
h.internalServerErrorJSON(c, err)
return
}
if len(objects) > 0 {
response["orderedItems"] = objects
}
if page > 1 {
response["prev"] = fmt.Sprintf("https://%s/tags/%s?page=%d", h.domain, tag, page-1)
}
if page < lastPage {
response["next"] = fmt.Sprintf("https://%s/tags/%s?page=%d", h.domain, tag, page+1)
}
h.writeJSONLD(c, http.StatusOK, response)
}