refactor: implement `GetByHashIDs` to make sure only query database once

pull/3356/head
scholar7r 4 days ago
parent 309a1cbf4d
commit a2552bbf90

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

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

Loading…
Cancel
Save