-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.go
61 lines (48 loc) 路 1.39 KB
/
api.go
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
// Copyright 2021 Saferwall. All rights reserved.
// Use of this source code is governed by Apache v2 license
// license that can be found in the LICENSE file.
package activity
import (
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/saferwall/saferwall-api/pkg/log"
"github.com/saferwall/saferwall-api/pkg/pagination"
)
func RegisterHandlers(g *echo.Group, service Service,
requireLogin echo.MiddlewareFunc, logger log.Logger) {
res := resource{service, logger}
g.GET("/activities/:id/", res.get)
g.GET("/activities/", res.query)
}
type resource struct {
service Service
logger log.Logger
}
func (r resource) get(c echo.Context) error {
// the `fields` query parameter is used to limit the fields
// to include in the response.
var fields []string
if fieldsParam := c.QueryParam("fields"); fieldsParam != "" {
fields = strings.Split(fieldsParam, ",")
}
activity, err := r.service.Get(c.Request().Context(), c.Param("id"), fields)
if err != nil {
return err
}
return c.JSON(http.StatusOK, activity)
}
func (r resource) query(c echo.Context) error {
ctx := c.Request().Context()
count, err := r.service.Count(ctx)
if err != nil {
return err
}
pages := pagination.NewFromRequest(c.Request(), count)
activities, err := r.service.Query(ctx, pages.Offset(), pages.Limit())
if err != nil {
return err
}
pages.Items = activities
return c.JSON(http.StatusOK, pages)
}