Moved Unquote to utils package

Signed-off-by: ItalyPaleAle <43508+ItalyPaleAle@users.noreply.github.com>
This commit is contained in:
ItalyPaleAle 2023-01-10 17:52:38 +00:00
parent 02d478785b
commit 32f14568ec
3 changed files with 51 additions and 19 deletions

View File

@ -15,7 +15,6 @@ package sms
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@ -24,9 +23,8 @@ import (
"strings"
"time"
"github.com/spf13/cast"
"github.com/dapr/components-contrib/bindings"
"github.com/dapr/components-contrib/internal/utils"
"github.com/dapr/kit/logger"
)
@ -109,21 +107,7 @@ func (t *SMS) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*binding
toNumberValue = toNumberFromRequest
}
var (
bodyObj any
body string
)
err := json.Unmarshal(req.Data, &bodyObj)
if err != nil {
// If req.Data can't be un-marshalled, keep body as-is
body = string(req.Data)
} else {
// Try casting to string
body, err = cast.ToStringE(bodyObj)
if err != nil {
body = string(req.Data)
}
}
body := utils.Unquote(req.Data)
v := url.Values{}
v.Set("To", toNumberValue)

View File

@ -14,8 +14,11 @@ limitations under the License.
package utils
import (
"encoding/json"
"strconv"
"strings"
"github.com/spf13/cast"
)
// IsTruthy returns true if a string is a truthy value.
@ -54,3 +57,21 @@ func GetIntValOrDefault(val int, defaultValue int) int {
}
return defaultValue
}
// Unquote parses a request data that may be quoted due to JSON encoding, and removes the quotes.
func Unquote(data []byte) (res string) {
var dataObj any
err := json.Unmarshal(data, &dataObj)
if err != nil {
// If data can't be un-marshalled, keep as-is
res = string(data)
} else {
// Try casting to string
res, err = cast.ToStringE(dataObj)
if err != nil {
// If dataObj can't be cast to string, keep as-is
res = string(data)
}
}
return res
}

View File

@ -13,7 +13,9 @@ limitations under the License.
package utils
import "testing"
import (
"testing"
)
func TestGetElemOrDefaultFromMap(t *testing.T) {
t.Run("test int", func(t *testing.T) {
@ -96,3 +98,28 @@ func TestGetElemOrDefaultFromMap(t *testing.T) {
}
})
}
func TestUnquote(t *testing.T) {
type args struct {
data []byte
}
tests := []struct {
name string
args args
wantRes string
}{
{name: "empty data", args: args{data: []byte{}}, wantRes: ""},
{name: "string", args: args{data: []byte("ciao mondo")}, wantRes: "ciao mondo"},
{name: "JSON-encoded string", args: args{data: []byte(`"ciao mondo"`)}, wantRes: "ciao mondo"},
{name: "int", args: args{data: []byte("42")}, wantRes: "42"},
{name: "bool", args: args{data: []byte("true")}, wantRes: "true"},
{name: "JSON-encoded array", args: args{data: []byte(`["ciao","mondo"]`)}, wantRes: `["ciao","mondo"]`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if gotRes := Unquote(tt.args.data); gotRes != tt.wantRes {
t.Errorf("Unquote() = %v, want %v", gotRes, tt.wantRes)
}
})
}
}