Skip to content

Commit

Permalink
✨ feat: add Delete method to Store struct in session middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
kaptinlin committed Sep 30, 2023
1 parent af73a7c commit ebb30aa
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/api/middleware/session.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ This middleware uses our [Storage](https://github.com/gofiber/storage) package t
func New(config ...Config) *Store
func (s *Store) RegisterType(i interface{})
func (s *Store) Get(c *fiber.Ctx) (*Session, error)
func (s *Store) Delete(id string) error
func (s *Store) Reset() error

func (s *Session) Get(key string) interface{}
Expand Down
8 changes: 8 additions & 0 deletions middleware/session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,11 @@ func (s *Session) delSession() {
fasthttp.ReleaseCookie(fcookie)
}
}

// Delete deletes a session by its id
func (s *Store) Delete(id string) error {
if len(id) == 0 {
return fmt.Errorf("session id cannot be empty")
}
return s.Storage.Delete(id)
}
38 changes: 38 additions & 0 deletions middleware/session/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,41 @@ func TestStore_Get(t *testing.T) {
utils.AssertEqual(t, unexpectedID, acquiredSession.ID())
})
}

// go test -run TestStore_Delete
func TestStore_Delete(t *testing.T) {
t.Parallel()
// fiber instance
app := fiber.New()
// session store
store := New()

// fiber context
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)

// Create a new session
session, err := store.Get(ctx)
if err != nil {
t.Fatal(err)
}

// Save the session ID
sessionID := session.ID()

// Delete the session
if err := store.Delete(sessionID); err != nil {
t.Fatal(err)
}

// Try to get the session again
session, err = store.Get(ctx)
if err != nil {
t.Fatal(err)
}

// The session ID should be different now, because the old session was deleted
if session.ID() == sessionID {
t.Errorf("The session was not deleted, the session ID is still the same")
}
}

0 comments on commit ebb30aa

Please sign in to comment.