Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package routes
import (
"net/http"
"strconv"
"owo.codes/whats-this/api/lib/apierrors"
"owo.codes/whats-this/api/lib/db"
"owo.codes/whats-this/api/lib/middleware"
"github.com/go-chi/render"
"github.com/rs/zerolog/log"
)
// Objects per page
const perPage = 50
// Maximum objects per page
const maxPerPage = 100
// listObjectsResponse is the response format for ListObjects.
type listObjectsResponse struct {
Success bool `json:"success"`
Data []db.Object `json:"data"`
}
// ListObjects returns a paginated list of all objects owned by a user.
func ListObjects(w http.ResponseWriter, r *http.Request) {
// Only authorized users can use this route
user := middleware.GetAuthorizedUser(r)
if user.ID == "" || user.IsBlocked {
panic(apierrors.Unauthorized)
}
// Determine offset and limit information
query := r.URL.Query()
l := query.Get("limit")
limit, err := strconv.Atoi(l)
if err != nil {
panic(apierrors.InvalidOffsetOrLimit)
}
o := query.Get("offset")
offset, err := strconv.Atoi(o)
if err != nil {
panic(apierrors.InvalidOffsetOrLimit)
}
if limit > maxPerPage {
panic(apierrors.OffsetTooLarge)
}
asc := false
if query.Get("order") == "asc" {
asc = true
}
// Get the data
objects, err := db.ListObjectsByAssociatedUser(user.ID, asc, offset, limit)
if err != nil {
log.Error().Err(err).Msg("failed to list objects for user")
panic(apierrors.InternalServerError)
}
associatedWithCurrentUser := true
for i := 0; i < len(objects); i++ {
objects[i].AssociatedWithCurrentUser = &associatedWithCurrentUser
}
// Return response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
render.JSON(w, r, listObjectsResponse{true, objects})
}