Skip to content

Commit

Permalink
fix: ensure only one attachment is marked as primary (#287)
Browse files Browse the repository at this point in the history
  • Loading branch information
mwayne authored Oct 17, 2024
1 parent 3a4c78e commit c2546f0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
17 changes: 11 additions & 6 deletions backend/internal/data/repo/repo_item_attachments.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ func (r *AttachmentRepo) Get(ctx context.Context, id uuid.UUID) (*ent.Attachment
Only(ctx)
}

func (r *AttachmentRepo) Update(ctx context.Context, itemID uuid.UUID, data *ItemAttachmentUpdate) (*ent.Attachment, error) {
func (r *AttachmentRepo) Update(ctx context.Context, id uuid.UUID, data *ItemAttachmentUpdate) (*ent.Attachment, error) {
// TODO: execute within Tx
typ := attachment.Type(data.Type)

bldr := r.db.Attachment.UpdateOneID(itemID).
bldr := r.db.Attachment.UpdateOneID(id).
SetType(typ)

// Primary only applies to photos
Expand All @@ -101,24 +101,29 @@ func (r *AttachmentRepo) Update(ctx context.Context, itemID uuid.UUID, data *Ite
bldr = bldr.SetPrimary(false)
}

itm, err := bldr.Save(ctx)
updatedAttachment, err := bldr.Save(ctx)
if err != nil {
return nil, err
}

attachmentItem, err := updatedAttachment.QueryItem().Only(ctx)
if err != nil {
return nil, err
}

// Ensure all other attachments are not primary
err = r.db.Attachment.Update().
Where(
attachment.HasItemWith(item.ID(itemID)),
attachment.IDNEQ(itm.ID),
attachment.HasItemWith(item.ID(attachmentItem.ID)),
attachment.IDNEQ(updatedAttachment.ID),
).
SetPrimary(false).
Exec(ctx)
if err != nil {
return nil, err
}

return r.Get(ctx, itm.ID)
return r.Get(ctx, updatedAttachment.ID)
}

func (r *AttachmentRepo) Delete(ctx context.Context, id uuid.UUID) error {
Expand Down
22 changes: 22 additions & 0 deletions backend/internal/data/repo/repo_item_attachments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,25 @@ func TestAttachmentRepo_Delete(t *testing.T) {
_, err = tRepos.Attachments.Get(context.Background(), entity.ID)
require.Error(t, err)
}

func TestAttachmentRepo_EnsureSinglePrimaryAttachment(t *testing.T) {
ctx := context.Background()
attachments := useAttachments(t, 2)

setAndVerifyPrimary := func(primaryAttachmentID, nonPrimaryAttachmentID uuid.UUID) {
primaryAttachment, err := tRepos.Attachments.Update(ctx, primaryAttachmentID, &ItemAttachmentUpdate{
Type: attachment.TypePhoto.String(),
Primary: true,
})
require.NoError(t, err)

nonPrimaryAttachment, err := tRepos.Attachments.Get(ctx, nonPrimaryAttachmentID)
require.NoError(t, err)

assert.True(t, primaryAttachment.Primary)
assert.False(t, nonPrimaryAttachment.Primary)
}

setAndVerifyPrimary(attachments[0].ID, attachments[1].ID)
setAndVerifyPrimary(attachments[1].ID, attachments[0].ID)
}

0 comments on commit c2546f0

Please sign in to comment.