mirror of
https://github.com/crawlab-team/crawlab.git
synced 2026-01-22 17:31:03 +01:00
- Refactored multiple controller methods to accept structured parameters for improved clarity and maintainability. - Consolidated error handling and response generation across various endpoints. - Updated function signatures to eliminate unnecessary context parameters and enhance type safety. - Improved consistency in response formatting and error handling across controllers. - Enhanced file handling methods to support multipart file uploads and directory operations more effectively.
75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
package controllers
|
|
|
|
import (
|
|
"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"
|
|
"github.com/juju/errors"
|
|
mongo2 "go.mongodb.org/mongo-driver/mongo"
|
|
)
|
|
|
|
type PostTokenParams struct {
|
|
Data models.Token `json:"data"`
|
|
}
|
|
|
|
func PostToken(c *gin.Context, params *PostTokenParams) (response *Response[models.Token], err error) {
|
|
t := params.Data
|
|
svc, err := user.GetUserService()
|
|
if err != nil {
|
|
return GetErrorResponse[models.Token](err)
|
|
}
|
|
|
|
u := GetUserFromContext(c)
|
|
t.SetCreated(u.Id)
|
|
t.SetUpdated(u.Id)
|
|
t.Token, err = svc.MakeToken(u)
|
|
if err != nil {
|
|
return GetErrorResponse[models.Token](err)
|
|
}
|
|
|
|
id, err := service.NewModelService[models.Token]().InsertOne(t)
|
|
if err != nil {
|
|
return GetErrorResponse[models.Token](err)
|
|
}
|
|
t.Id = id
|
|
|
|
return GetDataResponse(t)
|
|
}
|
|
|
|
func GetTokenList(c *gin.Context, params *GetListParams) (response *ListResponse[models.Token], err error) {
|
|
// Get current user from context
|
|
u := GetUserFromContext(c)
|
|
|
|
// Get filter query
|
|
query, err := GetFilterQueryFromListParams(params)
|
|
if err != nil {
|
|
return GetErrorListResponse[models.Token](errors.BadRequestf("invalid request parameters: %v", err))
|
|
}
|
|
|
|
// 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: params.Sort,
|
|
Skip: params.Size * (params.Page - 1),
|
|
Limit: params.Size,
|
|
})
|
|
if err != nil {
|
|
if err == mongo2.ErrNoDocuments {
|
|
return GetListResponse([]models.Token{}, 0)
|
|
}
|
|
return GetErrorListResponse[models.Token](err)
|
|
}
|
|
|
|
// Count total tokens for pagination
|
|
total, err := service.NewModelService[models.Token]().Count(query)
|
|
if err != nil {
|
|
return GetErrorListResponse[models.Token](err)
|
|
}
|
|
|
|
return GetListResponse(tokens, total)
|
|
}
|