diff --git a/CHANGELOG.md b/CHANGELOG.md index ec320b7..1aa9652 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `Payload.String() string` method is added +- `Payload.MarshalJSON() ([]byte, error)` method is added + ## [0.12.0] - 2020-09-12 **IMPORTANT**: If you are upgrading from a previous version, please install the latest version of the CLI `go get -u github.com/hibiken/asynq/tools/asynq` and run `asynq migrate` command. No process should be writing to Redis while you run the migration command. diff --git a/payload.go b/payload.go index 85d63f1..b447ef9 100644 --- a/payload.go +++ b/payload.go @@ -44,6 +44,16 @@ func toInt(v interface{}) (int, error) { } } +// String returns a string representation of payload data. +func (p Payload) String() string { + return fmt.Sprint(p.data) +} + +// MarshalJSON returns the JSON encoding of payload data. +func (p Payload) MarshalJSON() ([]byte, error) { + return json.Marshal(p.data) +} + // GetString returns a string value if a string type is associated with // the key, otherwise reports an error. func (p Payload) GetString(key string) (string, error) { diff --git a/payload_test.go b/payload_test.go index 9808374..379a4ac 100644 --- a/payload_test.go +++ b/payload_test.go @@ -6,6 +6,7 @@ package asynq import ( "encoding/json" + "fmt" "testing" "time" @@ -645,3 +646,30 @@ func TestPayloadHas(t *testing.T) { t.Errorf("Payload.Has(%q) = true, want false", "name") } } + +func TestPayloadDebuggingStrings(t *testing.T) { + data := map[string]interface{}{ + "foo": 123, + "bar": "hello", + "baz": false, + } + payload := Payload{data: data} + + if payload.String() != fmt.Sprint(data) { + t.Errorf("Payload.String() = %q, want %q", + payload.String(), fmt.Sprint(data)) + } + + got, err := payload.MarshalJSON() + if err != nil { + t.Fatal(err) + } + want, err := json.Marshal(data) + if err != nil { + t.Fatal(err) + } + if diff := cmp.Diff(got, want); diff != "" { + t.Errorf("Payload.MarhsalJSON() = %s, want %s; (-want,+got)\n%s", + got, want, diff) + } +}