Skip to content

Commit

Permalink
feat: add delete method for storage module (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
beihai0xff committed Jul 9, 2024
1 parent a8dc64e commit e3661d3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ type Storage interface {
GetByLongURL(ctx context.Context, long []byte) (*TinyURL, error)
// GetByShortID retrieves a TinyURL record by its short ID.
GetByShortID(ctx context.Context, short uint64) (*TinyURL, error)
// Delete a short link by short id
Delete(ctx context.Context, short uint64) error
// Close closes the storage.
Close() error
}
Expand Down Expand Up @@ -92,6 +94,21 @@ func (s *storage) GetByLongURL(ctx context.Context, long []byte) (*TinyURL, erro
return &t, nil
}

// Delete a short link by short id
func (s *storage) Delete(ctx context.Context, short uint64) error {
res := s.db.WithContext(ctx).Where("short = ?", short).Delete(&TinyURL{})

if res.Error != nil {
return res.Error
}

if res.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}

return nil
}

// Close closes the storage.
func (s *storage) Close() error {
return nil
Expand Down
25 changes: 25 additions & 0 deletions pkg/storage/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,28 @@ func Test_storage_GetByLongURL(t *testing.T) {
require.Nil(t, got)
})
}

func Test_storage_Delete(t *testing.T) {
db, _ := mysql.New(tests.GlobalConfig.MySQL)

long := []byte("www.storage_Delete.com")
s, ctx := newStorage(db), context.Background()
t.Cleanup(func() { s.Close() })

t.Run("Delete", func(t *testing.T) {
_, err := s.Insert(ctx, uint64(60000), long)
require.NoError(t, err)

err = s.Delete(ctx, uint64(60000))
require.NoError(t, err)

got, err := s.GetByShortID(ctx, uint64(60000))
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
require.Nil(t, got)
})

t.Run("DeleteNotFound", func(t *testing.T) {
err := s.Delete(ctx, uint64(60000))
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
})
}

0 comments on commit e3661d3

Please sign in to comment.