mirror of
https://github.com/crawlab-team/crawlab.git
synced 2026-01-25 17:42:25 +01:00
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:
@@ -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{
|
||||
{
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user