From a2552bbf906d3753c32391ce564ff3bda2d565e9 Mon Sep 17 00:00:00 2001 From: scholar7r Date: Fri, 13 Mar 2026 09:37:27 +0800 Subject: [PATCH] refactor: implement `GetByHashIDs` to make sure only query database once --- inventory/share.go | 17 +++++++++++++++++ service/share/manage.go | 17 ++++++++--------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/inventory/share.go b/inventory/share.go index 642ce21c..52f3b9f2 100644 --- a/inventory/share.go +++ b/inventory/share.go @@ -41,6 +41,8 @@ type ( GetByIDUser(ctx context.Context, id, uid int) (*ent.Share, error) // GetByHashID returns the share with given hash id. GetByHashID(ctx context.Context, idRaw string) (*ent.Share, error) + // GetByHashIDs returns the shares with given hash ids + GetByHashIDs(ctx context.Context, idsRaw []string) ([]*ent.Share, error) // Upsert creates or update a new share record. Upsert(ctx context.Context, params *CreateShareParams) (*ent.Share, error) // Viewed increase the view count of the share. @@ -161,6 +163,21 @@ func (c *shareClient) GetByHashID(ctx context.Context, idRaw string) (*ent.Share return c.GetByID(ctx, id) } +func (c *shareClient) GetByHashIDs(ctx context.Context, idsRaw []string) ([]*ent.Share, error) { + var ids []int + + for _, v := range idsRaw { + id, err := c.hasher.Decode(v, hashid.ShareID) + if err != nil { + return nil, fmt.Errorf("failed to decode hash id %q: %w", v, err) + } + + ids = append(ids, id) + } + + return c.GetByIDs(ctx, ids) +} + func (c *shareClient) GetByID(ctx context.Context, id int) (*ent.Share, error) { s, err := withShareEagerLoading(ctx, c.client.Share.Query().Where(share.ID(id))).First(ctx) if err != nil { diff --git a/service/share/manage.go b/service/share/manage.go index e9049f1b..687e3445 100644 --- a/service/share/manage.go +++ b/service/share/manage.go @@ -38,18 +38,17 @@ func (s *BatchDeleteShareService) Delete(c *gin.Context) error { dep := dependency.FromContext(c) shareClient := dep.ShareClient() - var shareIDs []int - - for _, v := range s.ShareIDs { - share, err := shareClient.GetByHashID(c, v) - if err != nil { - return err - } + shares, err := shareClient.GetByHashIDs(c, s.ShareIDs) + if err != nil { + return err + } - shareIDs = append(shareIDs, share.ID) + var ids []int + for _, v := range shares { + ids = append(ids, v.ID) } - if err := shareClient.DeleteBatch(c, shareIDs); err != nil { + if err := shareClient.DeleteBatch(c, ids); err != nil { return serializer.NewError(serializer.CodeDBError, "Failed to delete shares", err) }