Skip to content

Commit

Permalink
⚡ Optimize list attachment api
Browse files Browse the repository at this point in the history
  • Loading branch information
LittleSheep2Code committed Aug 6, 2024
1 parent 13893e8 commit 3e000b6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
32 changes: 21 additions & 11 deletions pkg/internal/server/api/attachment_dir_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ func listAttachment(c *fiber.Ctx) error {

tx := database.C

needQuery := true

var result = make([]models.Attachment, take)
var idxList []uint

Expand All @@ -40,6 +42,7 @@ func listAttachment(c *fiber.Ctx) error {
}
}
tx = tx.Where("id IN ?", pendingQueryId)
needQuery = len(pendingQueryId) > 0
} else {
// Do sort this when doesn't filter by the id
// Because the sort will mess up the result
Expand All @@ -64,23 +67,30 @@ func listAttachment(c *fiber.Ctx) error {
if err := countTx.Model(&models.Attachment{}).Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
var out []models.Attachment
if err := tx.Offset(offset).Limit(take).Preload("Account").Find(&out).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}

if len(idxList) == 0 {
result = out
} else {
for _, item := range out {
for p, id := range idxList {
if item.ID == id {
result[p] = item
if needQuery {
var out []models.Attachment
if err := tx.Offset(offset).Limit(take).Preload("Account").Find(&out).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}

if len(idxList) == 0 {
result = out
} else {
for _, item := range out {
for p, id := range idxList {
if item.ID == id {
result[p] = item
}
}
}
}
}

for _, item := range result {
services.CacheAttachment(item.ID, item)
}

return c.JSON(fiber.Map{
"count": count,
"data": result,
Expand Down
4 changes: 4 additions & 0 deletions pkg/internal/services/attachments.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ func GetAttachmentCache(id uint) (models.Attachment, bool) {
return models.Attachment{}, false
}

func CacheAttachment(id uint, item models.Attachment) {
metadataCache.Store(id, item)
}

func NewAttachmentMetadata(tx *gorm.DB, user models.Account, file *multipart.FileHeader, attachment models.Attachment) (models.Attachment, error) {
attachment.Uuid = uuid.NewString()
attachment.Size = file.Size
Expand Down

0 comments on commit 3e000b6

Please sign in to comment.