From a1f870715fb08865329d947060eb3304f35890a5 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Thu, 27 Feb 2025 16:39:51 +0800 Subject: [PATCH] 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 --- core/controllers/router.go | 5 ++++ core/controllers/token.go | 47 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/core/controllers/router.go b/core/controllers/router.go index 78da20d4..42510dc1 100644 --- a/core/controllers/router.go +++ b/core/controllers/router.go @@ -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{ { diff --git a/core/controllers/token.go b/core/controllers/token.go index 6100e178..bfa079a3 100644 --- a/core/controllers/token.go +++ b/core/controllers/token.go @@ -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) +}