This commit is contained in:
Erik Winter 2024-10-07 09:34:17 +02:00
parent 71204f8686
commit bdd794a1e7
3 changed files with 118 additions and 0 deletions

50
plan/command/delete.go Normal file
View File

@ -0,0 +1,50 @@
package command
import (
"fmt"
"github.com/urfave/cli/v2"
"go-mod.ewintr.nl/planner/plan/storage"
)
var DeleteCmd = &cli.Command{
Name: "delete",
Usage: "Delete an event",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "localID",
Aliases: []string{"l"},
Usage: "The local id of the event",
Required: true,
},
},
}
func NewDeleteCmd(localRepo storage.LocalID, eventRepo storage.Event) *cli.Command {
DeleteCmd.Action = func(cCtx *cli.Context) error {
return Delete(localRepo, eventRepo, cCtx.Int("localID"))
}
return DeleteCmd
}
func Delete(localRepo storage.LocalID, eventRepo storage.Event, localID int) error {
var id string
idMap, err := localRepo.FindAll()
if err != nil {
return fmt.Errorf("could not get local ids: %v", err)
}
for eid, lid := range idMap {
if localID == lid {
id = eid
}
}
if id == "" {
return fmt.Errorf("could not find local id")
}
if err := eventRepo.Delete(id); err != nil {
return fmt.Errorf("could not delete event: %v", err)
}
return nil
}

View File

@ -0,0 +1,67 @@
package command_test
import (
"errors"
"testing"
"time"
"go-mod.ewintr.nl/planner/item"
"go-mod.ewintr.nl/planner/plan/command"
"go-mod.ewintr.nl/planner/plan/storage"
"go-mod.ewintr.nl/planner/plan/storage/memory"
)
func TestDelete(t *testing.T) {
t.Parallel()
e := item.Event{
ID: "id",
EventBody: item.EventBody{
Title: "name",
Start: time.Date(2024, 10, 7, 9, 30, 0, 0, time.UTC),
},
}
for _, tc := range []struct {
name string
localID int
expErr bool
}{
{
name: "not found",
localID: 5,
expErr: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
eventRepo := memory.NewEvent()
if err := eventRepo.Store(e); err != nil {
t.Errorf("exp nil, got %v", err)
}
localRepo := memory.NewLocalID()
if err := localRepo.Store(e.ID, 1); err != nil {
t.Errorf("exp nil, got %v", err)
}
actErr := command.Delete(localRepo, eventRepo, tc.localID) != nil
if tc.expErr != actErr {
t.Errorf("exp %v, got %v", tc.expErr, actErr)
}
if tc.expErr {
return
}
_, repoErr := eventRepo.Find(e.ID)
if !errors.Is(repoErr, storage.ErrNotFound) {
t.Errorf("exp %v, got %v", storage.ErrNotFound, actErr)
}
idMap, idErr := localRepo.FindAll()
if idErr != nil {
t.Errorf("exp nil, got %v", idErr)
}
if len(idMap) != 0 {
t.Errorf("exp 0, got %v", len(idMap))
}
})
}
}

View File

@ -36,6 +36,7 @@ func main() {
command.NewAddCmd(localIDRepo, eventRepo), command.NewAddCmd(localIDRepo, eventRepo),
command.NewListCmd(localIDRepo, eventRepo), command.NewListCmd(localIDRepo, eventRepo),
command.NewUpdateCmd(localIDRepo, eventRepo), command.NewUpdateCmd(localIDRepo, eventRepo),
command.NewDeleteCmd(localIDRepo, eventRepo),
}, },
} }