feat(favorites): implement user favorites and recents functionality
Introduced a new API client for managing user favorites, allowing users to list, add, and remove starred resources. Enhanced the sidebar to display favorites and recents, improving user navigation. Updated internationalization files to include relevant labels and tooltips for the new features across multiple languages. Refs: #1303
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type userResourceFavoriteRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewUserResourceFavoriteRepository constructs the GORM-backed implementation.
|
||||
func NewUserResourceFavoriteRepository(db *gorm.DB) interfaces.UserResourceFavoriteRepository {
|
||||
return &userResourceFavoriteRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *userResourceFavoriteRepository) List(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType string,
|
||||
) ([]*types.UserResourceFavorite, error) {
|
||||
var list []*types.UserResourceFavorite
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND tenant_id = ? AND resource_type = ?", userID, tenantID, resourceType).
|
||||
Order("created_at DESC").
|
||||
Find(&list).Error
|
||||
return list, err
|
||||
}
|
||||
|
||||
// Add upserts the favorite. We rely on the composite primary key + GORM's
|
||||
// FirstOrCreate to make the insertion idempotent — concurrent double-clicks
|
||||
// from the same user collapse into one row with no error path needed.
|
||||
// `created` reflects whether the row was newly inserted vs already present.
|
||||
func (r *userResourceFavoriteRepository) Add(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
|
||||
) (bool, error) {
|
||||
rec := &types.UserResourceFavorite{
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
ResourceType: resourceType,
|
||||
ResourceID: resourceID,
|
||||
}
|
||||
res := r.db.WithContext(ctx).Where(rec).FirstOrCreate(rec)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *userResourceFavoriteRepository) Remove(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
|
||||
) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND tenant_id = ? AND resource_type = ? AND resource_id = ?",
|
||||
userID, tenantID, resourceType, resourceID).
|
||||
Delete(&types.UserResourceFavorite{})
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *userResourceFavoriteRepository) IsFavorite(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
|
||||
) (bool, error) {
|
||||
var rec types.UserResourceFavorite
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND tenant_id = ? AND resource_type = ? AND resource_id = ?",
|
||||
userID, tenantID, resourceType, resourceID).
|
||||
First(&rec).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Sentinel errors so the handler can map cleanly to HTTP status codes
|
||||
// without leaking GORM internals.
|
||||
var (
|
||||
ErrFavoriteInvalidType = errors.New("invalid favorite resource type")
|
||||
ErrFavoriteEmptyID = errors.New("favorite resource id is required")
|
||||
)
|
||||
|
||||
type userResourceFavoriteService struct {
|
||||
repo interfaces.UserResourceFavoriteRepository
|
||||
}
|
||||
|
||||
// NewUserResourceFavoriteService wraps the repository with input
|
||||
// validation (allowlist of resource types, non-empty resource id).
|
||||
// We keep service thin on purpose — favoriting is a non-business action
|
||||
// that doesn't need audit logging or cross-aggregate side effects.
|
||||
func NewUserResourceFavoriteService(repo interfaces.UserResourceFavoriteRepository) interfaces.UserResourceFavoriteService {
|
||||
return &userResourceFavoriteService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *userResourceFavoriteService) List(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType string,
|
||||
) ([]*types.UserResourceFavorite, error) {
|
||||
if !types.IsValidFavoriteResourceType(resourceType) {
|
||||
return nil, ErrFavoriteInvalidType
|
||||
}
|
||||
return s.repo.List(ctx, userID, tenantID, resourceType)
|
||||
}
|
||||
|
||||
func (s *userResourceFavoriteService) Add(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
|
||||
) error {
|
||||
if !types.IsValidFavoriteResourceType(resourceType) {
|
||||
return ErrFavoriteInvalidType
|
||||
}
|
||||
if strings.TrimSpace(resourceID) == "" {
|
||||
return ErrFavoriteEmptyID
|
||||
}
|
||||
_, err := s.repo.Add(ctx, userID, tenantID, resourceType, resourceID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *userResourceFavoriteService) Remove(
|
||||
ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
|
||||
) error {
|
||||
if !types.IsValidFavoriteResourceType(resourceType) {
|
||||
return ErrFavoriteInvalidType
|
||||
}
|
||||
if strings.TrimSpace(resourceID) == "" {
|
||||
return ErrFavoriteEmptyID
|
||||
}
|
||||
_, err := s.repo.Remove(ctx, userID, tenantID, resourceType, resourceID)
|
||||
return err
|
||||
}
|
||||
@@ -155,6 +155,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewKBShareRepository))
|
||||
must(container.Provide(repository.NewAgentShareRepository))
|
||||
must(container.Provide(repository.NewTenantDisabledSharedAgentRepository))
|
||||
must(container.Provide(repository.NewUserResourceFavoriteRepository))
|
||||
must(container.Provide(service.NewWebSearchStateService))
|
||||
must(container.Provide(repository.NewDataSourceRepository))
|
||||
must(container.Provide(repository.NewSyncLogRepository))
|
||||
@@ -197,6 +198,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewMCPServiceService))
|
||||
must(container.Provide(service.NewMCPToolApprovalService))
|
||||
must(container.Provide(service.NewCustomAgentService))
|
||||
must(container.Provide(service.NewUserResourceFavoriteService))
|
||||
must(container.Provide(memoryService.NewMemoryService))
|
||||
must(container.Provide(service.NewWikiPageService))
|
||||
must(container.Provide(service.NewWikiLogEntryService))
|
||||
@@ -310,6 +312,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewWebSearchProviderHandler))
|
||||
must(container.Provide(handler.NewVectorStoreHandler))
|
||||
must(container.Provide(handler.NewCustomAgentHandler))
|
||||
must(container.Provide(handler.NewUserResourceFavoriteHandler))
|
||||
must(container.Provide(service.NewSkillService))
|
||||
must(container.Provide(handler.NewSkillHandler))
|
||||
must(container.Provide(handler.NewOrganizationHandler))
|
||||
|
||||
@@ -165,6 +165,34 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Optional creator filter — see the matching block in
|
||||
// KnowledgeBaseHandler.ListKnowledgeBases for rationale. Built-in
|
||||
// agents (IsBuiltin=true, CreatedBy="") are tenant-level fixtures
|
||||
// rather than user creations; we always keep them regardless of the
|
||||
// filter so the conversation dropdown never silently loses
|
||||
// quick-answer / smart-reasoning when a user picks "Created by me".
|
||||
creatorFilter := strings.ToLower(strings.TrimSpace(c.Query("creator")))
|
||||
if creatorFilter == "mine" || creatorFilter == "others" {
|
||||
callerUserID, _ := c.Get(types.UserIDContextKey.String())
|
||||
callerUserIDStr, _ := callerUserID.(string)
|
||||
filtered := make([]*types.CustomAgent, 0, len(agents))
|
||||
for _, ag := range agents {
|
||||
if ag.IsBuiltin {
|
||||
filtered = append(filtered, ag)
|
||||
continue
|
||||
}
|
||||
if ag.CreatedBy == "" {
|
||||
continue
|
||||
}
|
||||
if creatorFilter == "mine" && ag.CreatedBy == callerUserIDStr {
|
||||
filtered = append(filtered, ag)
|
||||
} else if creatorFilter == "others" && ag.CreatedBy != callerUserIDStr {
|
||||
filtered = append(filtered, ag)
|
||||
}
|
||||
}
|
||||
agents = filtered
|
||||
}
|
||||
|
||||
// Per-tenant "disabled by me" for own agents (only affects this tenant's conversation dropdown)
|
||||
tenantIDVal, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
|
||||
@@ -503,6 +503,32 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Optional creator filter — drives the [All | Mine | Others] segmented
|
||||
// control on the list page. We filter in-process rather than pushing
|
||||
// down into SQL because the tenant-bounded KB list is small (typically
|
||||
// <100 rows) and adding a creator predicate to ListKnowledgeBases would
|
||||
// ripple through every other caller (chat pipeline, agent editor, …).
|
||||
// Rows with empty CreatorID predate the RBAC migration (PR 5); we treat
|
||||
// them as "not anyone in particular" so they never appear under "mine"
|
||||
// or "others" — they fall out of both filters cleanly.
|
||||
creatorFilter := strings.ToLower(strings.TrimSpace(c.Query("creator")))
|
||||
if creatorFilter == "mine" || creatorFilter == "others" {
|
||||
callerUserID, _ := c.Get(types.UserIDContextKey.String())
|
||||
callerUserIDStr, _ := callerUserID.(string)
|
||||
filtered := make([]*types.KnowledgeBase, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
if kb.CreatorID == "" {
|
||||
continue
|
||||
}
|
||||
if creatorFilter == "mine" && kb.CreatorID == callerUserIDStr {
|
||||
filtered = append(filtered, kb)
|
||||
} else if creatorFilter == "others" && kb.CreatorID != callerUserIDStr {
|
||||
filtered = append(filtered, kb)
|
||||
}
|
||||
}
|
||||
kbs = filtered
|
||||
}
|
||||
|
||||
// Get share counts for all knowledge bases
|
||||
if len(kbs) > 0 && h.kbShareService != nil {
|
||||
kbIDs := make([]string, len(kbs))
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UserResourceFavoriteHandler exposes the per-user starred-resource API.
|
||||
//
|
||||
// Authorization model: a user can only manipulate *their own* favorites in
|
||||
// the tenant they're currently scoped into (TenantIDContextKey from the
|
||||
// auth middleware). Cross-user or cross-tenant access is not allowed —
|
||||
// callers cannot pass a user_id or tenant_id query param. This matches
|
||||
// the data-model rationale: favorites are personal navigation aids, not
|
||||
// shareable resources, so there's no value in admin-style listing.
|
||||
type UserResourceFavoriteHandler struct {
|
||||
service interfaces.UserResourceFavoriteService
|
||||
}
|
||||
|
||||
func NewUserResourceFavoriteHandler(svc interfaces.UserResourceFavoriteService) *UserResourceFavoriteHandler {
|
||||
return &UserResourceFavoriteHandler{service: svc}
|
||||
}
|
||||
|
||||
// favoriteContext resolves the (userID, tenantID) pair the handler will
|
||||
// scope all queries to. Centralised so the three endpoints stay short
|
||||
// and consistent in their error shape.
|
||||
func favoriteContext(c *gin.Context) (string, uint64, bool) {
|
||||
uidVal, ok := c.Get(types.UserIDContextKey.String())
|
||||
if !ok {
|
||||
c.Error(apperrors.NewUnauthorizedError("user ID not found"))
|
||||
return "", 0, false
|
||||
}
|
||||
userID, _ := uidVal.(string)
|
||||
if userID == "" {
|
||||
c.Error(apperrors.NewUnauthorizedError("user ID not found"))
|
||||
return "", 0, false
|
||||
}
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
|
||||
return "", 0, false
|
||||
}
|
||||
return userID, tenantID, true
|
||||
}
|
||||
|
||||
// ListFavorites godoc
|
||||
// @Summary List my favorites
|
||||
// @Description Lists this user's starred resources in the current tenant for a given type
|
||||
// @Tags User
|
||||
// @Param type query string true "Resource type (kb | agent)"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /user/favorites [get]
|
||||
func (h *UserResourceFavoriteHandler) ListFavorites(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, tenantID, ok := favoriteContext(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
resourceType := c.Query("type")
|
||||
|
||||
list, err := h.service.List(ctx, userID, tenantID, resourceType)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, service.ErrFavoriteInvalidType) {
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(apperrors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": list})
|
||||
}
|
||||
|
||||
// AddFavoriteRequest is the body for POST /user/favorites — kept symmetric
|
||||
// with the DELETE path parameters so the frontend can build a single API
|
||||
// helper that switches verb on toggle.
|
||||
type AddFavoriteRequest struct {
|
||||
ResourceType string `json:"type"`
|
||||
ResourceID string `json:"id"`
|
||||
}
|
||||
|
||||
// AddFavorite godoc
|
||||
// @Summary Star a resource
|
||||
// @Tags User
|
||||
// @Param body body AddFavoriteRequest true "Type + id"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /user/favorites [post]
|
||||
func (h *UserResourceFavoriteHandler) AddFavorite(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, tenantID, ok := favoriteContext(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req AddFavoriteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewBadRequestError("invalid request body").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := h.service.Add(ctx, userID, tenantID, req.ResourceType, req.ResourceID); err != nil {
|
||||
if stderrors.Is(err, service.ErrFavoriteInvalidType) || stderrors.Is(err, service.ErrFavoriteEmptyID) {
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(apperrors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// RemoveFavorite godoc
|
||||
// @Summary Unstar a resource
|
||||
// @Tags User
|
||||
// @Param type path string true "Resource type"
|
||||
// @Param id path string true "Resource id"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /user/favorites/{type}/{id} [delete]
|
||||
func (h *UserResourceFavoriteHandler) RemoveFavorite(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, tenantID, ok := favoriteContext(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
resourceType := c.Param("type")
|
||||
resourceID := c.Param("id")
|
||||
|
||||
if err := h.service.Remove(ctx, userID, tenantID, resourceType, resourceID); err != nil {
|
||||
if stderrors.Is(err, service.ErrFavoriteInvalidType) || stderrors.Is(err, service.ErrFavoriteEmptyID) {
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(apperrors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
@@ -72,6 +72,7 @@ type RouterParams struct {
|
||||
FAQHandler *handler.FAQHandler
|
||||
TagHandler *handler.TagHandler
|
||||
CustomAgentHandler *handler.CustomAgentHandler
|
||||
UserFavoriteHandler *handler.UserResourceFavoriteHandler
|
||||
SkillHandler *handler.SkillHandler
|
||||
OrganizationHandler *handler.OrganizationHandler
|
||||
IMHandler *handler.IMHandler
|
||||
@@ -191,6 +192,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterWebSearchProviderRoutes(v1, params.WebSearchProviderHandler, params.WebSearchCredentialsHandler, rbacGuards)
|
||||
RegisterVectorStoreRoutes(v1, params.VectorStoreHandler, rbacGuards)
|
||||
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler, rbacGuards)
|
||||
RegisterUserFavoriteRoutes(v1, params.UserFavoriteHandler, rbacGuards)
|
||||
RegisterSkillRoutes(v1, params.SkillHandler, rbacGuards)
|
||||
RegisterOrganizationRoutes(v1, params.OrganizationHandler, rbacGuards)
|
||||
RegisterIMChannelRoutes(v1, params.IMHandler, rbacGuards)
|
||||
@@ -804,6 +806,22 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
|
||||
r.GET("/agents/:id/suggested-questions", g.Viewer(), agentHandler.GetSuggestedQuestions)
|
||||
}
|
||||
|
||||
// RegisterUserFavoriteRoutes wires the per-user starred-resource endpoints.
|
||||
//
|
||||
// Authorization: the handler always derives (user_id, tenant_id) from the
|
||||
// auth context — there is no admin-style "see another user's favorites"
|
||||
// path — so a Viewer floor is the right gate. The endpoints intentionally
|
||||
// don't follow the OwnedXOrAdmin pattern: favorites aren't owned by the
|
||||
// resource's creator, they're owned by the user *doing* the starring.
|
||||
func RegisterUserFavoriteRoutes(r *gin.RouterGroup, h *handler.UserResourceFavoriteHandler, g *rbacGuards) {
|
||||
favs := r.Group("/user/favorites")
|
||||
{
|
||||
favs.GET("", g.Viewer(), h.ListFavorites)
|
||||
favs.POST("", g.Viewer(), h.AddFavorite)
|
||||
favs.DELETE("/:type/:id", g.Viewer(), h.RemoveFavorite)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterSkillRoutes registers skill routes.
|
||||
//
|
||||
// PR 2 currently only exposes a read-only `ListSkills`; gated to
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// UserResourceFavoriteRepository is the storage contract for per-user
|
||||
// favorited resources. Implementations are expected to be tenant-aware
|
||||
// (queries always include tenant_id) so a user switching tenants sees
|
||||
// only that tenant's favorites — matches the PK shape in migration 000047.
|
||||
type UserResourceFavoriteRepository interface {
|
||||
// List returns favorites for (userID, tenantID, resourceType), newest first.
|
||||
List(ctx context.Context, userID string, tenantID uint64, resourceType string) ([]*types.UserResourceFavorite, error)
|
||||
// Add upserts a favorite (no-op if already present). Returns whether
|
||||
// a new row was actually inserted so the service layer can decide
|
||||
// whether to emit an audit event.
|
||||
Add(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) (created bool, err error)
|
||||
// Remove deletes a favorite; returns whether anything was deleted.
|
||||
Remove(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) (removed bool, err error)
|
||||
// IsFavorite exists for the rare RPC where the caller wants a single
|
||||
// boolean rather than the full list (e.g. a future GET-by-id endpoint).
|
||||
IsFavorite(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) (bool, error)
|
||||
}
|
||||
|
||||
// UserResourceFavoriteService wraps the repository with input validation
|
||||
// (resource type allowlist, non-empty id) so the handler stays thin.
|
||||
type UserResourceFavoriteService interface {
|
||||
List(ctx context.Context, userID string, tenantID uint64, resourceType string) ([]*types.UserResourceFavorite, error)
|
||||
Add(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) error
|
||||
Remove(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) error
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package types
|
||||
|
||||
import "time"
|
||||
|
||||
// Resource type constants for UserResourceFavorite. Extensible — adding a
|
||||
// new favoritable resource is just a new constant string + a frontend hook,
|
||||
// no schema change required.
|
||||
const (
|
||||
ResourceTypeKB = "kb"
|
||||
ResourceTypeAgent = "agent"
|
||||
)
|
||||
|
||||
// UserResourceFavorite is a per-(user, tenant) star on a single resource.
|
||||
// See migration 000047 for the schema rationale (composite key, no FK,
|
||||
// tenant-scoped on purpose).
|
||||
type UserResourceFavorite struct {
|
||||
UserID string `json:"user_id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"primaryKey"`
|
||||
ResourceType string `json:"resource_type" gorm:"type:varchar(16);primaryKey"`
|
||||
ResourceID string `json:"resource_id" gorm:"type:varchar(64);primaryKey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName pins the table to the migration's exact name so GORM's
|
||||
// pluraliser doesn't drift if we ever rename the struct.
|
||||
func (UserResourceFavorite) TableName() string {
|
||||
return "user_resource_favorites"
|
||||
}
|
||||
|
||||
// IsValidFavoriteResourceType returns true for resource types this product
|
||||
// currently supports favoriting. The handler validates against this list
|
||||
// to keep clients from inserting arbitrary strings (which would balloon
|
||||
// the table and break the frontend's segmented view).
|
||||
func IsValidFavoriteResourceType(t string) bool {
|
||||
switch t {
|
||||
case ResourceTypeKB, ResourceTypeAgent:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user