diff --git a/internal/processor/json-decode.go b/internal/processor/json-decode.go new file mode 100644 index 0000000..7b9520f --- /dev/null +++ b/internal/processor/json-decode.go @@ -0,0 +1,44 @@ +package processor + +import ( + "context" + "encoding/json" + "errors" + + "github.com/jwetzell/showbridge-go/internal/config" +) + +type JsonDecode struct { + config config.ProcessorConfig +} + +func (jd *JsonDecode) Process(ctx context.Context, payload any) (any, error) { + payloadString, ok := payload.(string) + + if !ok { + return nil, errors.New("json.decode processor only accepts a string") + } + + payloadJson := make(map[string]any) + + err := json.Unmarshal([]byte(payloadString), &payloadJson) + if err != nil { + return nil, err + } + + return payloadJson, nil + +} + +func (jd *JsonDecode) Type() string { + return jd.config.Type +} + +func init() { + RegisterProcessor(ProcessorRegistration{ + Type: "json.decode", + New: func(config config.ProcessorConfig) (Processor, error) { + return &JsonDecode{config: config}, nil + }, + }) +} diff --git a/internal/processor/json-decode_test.go b/internal/processor/json-decode_test.go new file mode 100644 index 0000000..baa7ba5 --- /dev/null +++ b/internal/processor/json-decode_test.go @@ -0,0 +1,51 @@ +package processor_test + +import ( + "reflect" + "testing" + + "github.com/jwetzell/showbridge-go/internal/processor" +) + +func TestGoodJsonDecode(t *testing.T) { + jsonDecoder := processor.JsonDecode{} + tests := []struct { + name string + payload string + expected map[string]any + }{ + { + name: "basic json", + payload: "{\"address\":\"/hello\",\"args\":null}", + expected: map[string]any{ + "address": "/hello", + "args": nil, + }, + }, + { + name: "array", + payload: "{\"address\":\"/hello\",\"args\":[1,2,3]}", + expected: map[string]any{ + "address": "/hello", + "args": []any{1.0, 2.0, 3.0}, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got, err := jsonDecoder.Process(t.Context(), test.payload) + + gotMap, ok := got.(map[string]any) + if !ok { + t.Fatalf("json.decode returned a %T payload: %s", got, got) + } + if err != nil { + t.Fatalf("json.decode failed: %s", err) + } + if !reflect.DeepEqual(gotMap, test.expected) { + t.Fatalf("json.decode got %x, expected %s", got, test.expected) + } + }) + } +} diff --git a/schema/processors.schema.json b/schema/processors.schema.json index 62c4fa5..6cbd71e 100644 --- a/schema/processors.schema.json +++ b/schema/processors.schema.json @@ -277,6 +277,17 @@ } } }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "json.decode" + } + }, + "required": ["type"], + "additionalProperties": false + }, { "type": "object", "properties": {