Skip to content

Commit

Permalink
feat: add RawResponseData() to Context (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
DarthPestilane authored Dec 2, 2021
1 parent e2379ba commit 014e153
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
26 changes: 21 additions & 5 deletions router_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ type Context interface {
// Response returns the response message entry.
Response() *message.Entry

// RawResponseData returns the not yet encoded response data.
RawResponseData() interface{}

// SetResponse encodes data with session's codec and sets response message entry.
SetResponse(id, data interface{}) error

Expand Down Expand Up @@ -64,11 +67,12 @@ type Context interface {

// routeContext implements the Context interface.
type routeContext struct {
mu sync.RWMutex
storage map[string]interface{}
session Session
reqEntry *message.Entry
respEntry *message.Entry
mu sync.RWMutex
storage map[string]interface{}
session Session
reqEntry *message.Entry
respEntry *message.Entry
rawRespData interface{}
}

// Deadline implements the context.Context Deadline method.
Expand Down Expand Up @@ -118,6 +122,17 @@ func (c *routeContext) Response() *message.Entry {
return c.respEntry
}

// RawResponseData returns the not yet encoded response data.
func (c *routeContext) RawResponseData() interface{} {
if c.rawRespData != nil {
return c.rawRespData
}
if c.respEntry != nil {
return c.respEntry.Data
}
return nil
}

// SetResponse implements Context.SetResponse method.
func (c *routeContext) SetResponse(id, data interface{}) error {
if c.Session().Codec() == nil {
Expand All @@ -127,6 +142,7 @@ func (c *routeContext) SetResponse(id, data interface{}) error {
if err != nil {
return err
}
c.rawRespData = data
c.respEntry = &message.Entry{
ID: id,
Data: dataRaw,
Expand Down
21 changes: 21 additions & 0 deletions router_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ func TestRouteContext_SetResponse(t *testing.T) {
err := c.SetResponse(1, "test")
assert.NoError(t, err)
assert.Equal(t, c.respEntry, entry)
assert.Equal(t, c.rawRespData, "test")
})
}

Expand Down Expand Up @@ -246,3 +247,23 @@ func Test_routeContext_MustSetResponse(t *testing.T) {
})
})
}

func Test_routeContext_RawResponseData(t *testing.T) {
t.Run("when raw resp data is not nil", func(t *testing.T) {
c := newContext(nil, nil)
c.rawRespData = 123
assert.Equal(t, c.RawResponseData(), 123)
})
t.Run("when resp entry is not nil", func(t *testing.T) {
c := newContext(nil, nil)
c.rawRespData = nil
c.respEntry = &message.Entry{
Data: []byte("123"),
}
assert.Equal(t, c.RawResponseData(), []byte("123"))
})
t.Run("when resp entry is nil", func(t *testing.T) {
c := newContext(nil, nil)
assert.Nil(t, c.RawResponseData())
})
}

0 comments on commit 014e153

Please sign in to comment.