feat: add GET endpoint for retrieving user's token list

Implemented a new GetTokenList handler in the token controller to:
- Fetch tokens created by the current user
- Support pagination and filtering
- Return tokens with total count
- Handle cases with no documents gracefully
This commit is contained in:
Marvin Zhang
2025-02-27 16:39:51 +08:00
parent 6048d4eeb8
commit a1f870715f
2 changed files with 52 additions and 0 deletions

View File

@@ -247,6 +247,11 @@ func InitRoutes(app *gin.Engine) (err error) {
Path: "",
HandlerFunc: PostToken,
},
{
Method: http.MethodGet,
Path: "",
HandlerFunc: GetTokenList,
},
}...))
RegisterController(groups.AuthGroup, "/users", NewController[models.User]([]Action{
{

View File

@@ -1,10 +1,14 @@
package controllers
import (
"errors"
"github.com/crawlab-team/crawlab/core/models/models"
"github.com/crawlab-team/crawlab/core/models/service"
"github.com/crawlab-team/crawlab/core/mongo"
"github.com/crawlab-team/crawlab/core/user"
"github.com/gin-gonic/gin"
mongo2 "go.mongodb.org/mongo-driver/mongo"
)
func PostToken(c *gin.Context) {
@@ -33,3 +37,46 @@ func PostToken(c *gin.Context) {
}
HandleSuccess(c)
}
func GetTokenList(c *gin.Context) {
// Get current user from context
u := GetUserFromContext(c)
// Get pagination, filter query, and sort options
pagination := MustGetPagination(c)
query := MustGetFilterQuery(c)
sort := MustGetSortOption(c)
// If query is nil, initialize it
if query == nil {
query = make(map[string]interface{})
}
// Add filter for tokens created by the current user
query["created_by"] = u.Id
// Get tokens with pagination
tokens, err := service.NewModelService[models.Token]().GetMany(query, &mongo.FindOptions{
Sort: sort,
Skip: pagination.Size * (pagination.Page - 1),
Limit: pagination.Size,
})
if err != nil {
if errors.Is(err, mongo2.ErrNoDocuments) {
HandleSuccessWithListData(c, nil, 0)
} else {
HandleErrorInternalServerError(c, err)
}
return
}
// Count total tokens for pagination
total, err := service.NewModelService[models.Token]().Count(query)
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
// Return tokens with total count
HandleSuccessWithListData(c, tokens, total)
}