refactor: improve search user collections logic to handle optional keyword

This commit is contained in:
2025-07-31 11:01:49 +08:00
parent 470324221d
commit 40fb3a93b6
3 changed files with 9 additions and 5 deletions

View File

@@ -195,9 +195,9 @@ func handleRemoveResourceFromCollection(c fiber.Ctx) error {
func handleSearchUserCollections(c fiber.Ctx) error { func handleSearchUserCollections(c fiber.Ctx) error {
keyword := c.Query("keyword", "") keyword := c.Query("keyword", "")
if keyword == "" { // if keyword == "" {
return model.NewRequestError("keyword is required") // return model.NewRequestError("keyword is required")
} // }
username := c.Query("username", "") username := c.Query("username", "")
if username == "" { if username == "" {
return model.NewRequestError("username is required") return model.NewRequestError("username is required")

View File

@@ -181,7 +181,11 @@ func SearchUserCollections(uid uint, keyword string, excludedRID uint) ([]*model
var collections []*model.Collection var collections []*model.Collection
query := db.Model(&model.Collection{}). query := db.Model(&model.Collection{}).
Where("user_id = ? AND title LIKE ?", uid, "%"+keyword+"%") Where("user_id = ?", uid)
if keyword != "" {
query = query.Where("title LIKE ?", "%"+keyword+"%")
}
if excludedRID > 0 { if excludedRID > 0 {
// Use LEFT JOIN with IS NULL for better performance // Use LEFT JOIN with IS NULL for better performance

View File

@@ -136,7 +136,7 @@ func ListCollectionResources(collectionID uint, page int) ([]*model.ResourceView
// Search user collections by keyword, limited to 10 results. // Search user collections by keyword, limited to 10 results.
// excludedRID: if >0, only return collections not containing this resource. // excludedRID: if >0, only return collections not containing this resource.
func SearchUserCollections(username string, keyword string, excludedRID uint) ([]*model.CollectionView, error) { func SearchUserCollections(username string, keyword string, excludedRID uint) ([]*model.CollectionView, error) {
if username == "" || keyword == "" { if username == "" {
return nil, errors.New("invalid parameters") return nil, errors.New("invalid parameters")
} }
user, err := dao.GetUserByUsername(username) user, err := dao.GetUserByUsername(username)