Optimize list attachment api

This commit is contained in:
LittleSheep 2024-08-07 01:02:03 +08:00
parent 13893e87f7
commit 3e000b6f9e
2 changed files with 25 additions and 11 deletions

View File

@ -20,6 +20,8 @@ func listAttachment(c *fiber.Ctx) error {
tx := database.C
needQuery := true
var result = make([]models.Attachment, take)
var idxList []uint
@ -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
@ -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,

View File

@ -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