nws: refactored the NWS source files to relocate normalization logic to internal/normalizers.
This commit is contained in:
54
internal/normalizers/common/payload.go
Normal file
54
internal/normalizers/common/payload.go
Normal file
@@ -0,0 +1,54 @@
|
||||
// FILE: ./internal/normalizers/common/payload.go
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/ejr/feedkit/event"
|
||||
)
|
||||
|
||||
// PayloadBytes extracts a JSON-ish payload into bytes suitable for json.Unmarshal.
|
||||
//
|
||||
// Supported payload shapes (weatherfeeder convention):
|
||||
// - json.RawMessage (recommended for raw events)
|
||||
// - []byte
|
||||
// - string (assumed to contain JSON)
|
||||
// - map[string]any (re-marshaled to JSON)
|
||||
//
|
||||
// If you add other raw representations later, extend this function.
|
||||
func PayloadBytes(e event.Event) ([]byte, error) {
|
||||
if e.Payload == nil {
|
||||
return nil, fmt.Errorf("payload is nil")
|
||||
}
|
||||
|
||||
switch v := e.Payload.(type) {
|
||||
case json.RawMessage:
|
||||
if len(v) == 0 {
|
||||
return nil, fmt.Errorf("payload is empty json.RawMessage")
|
||||
}
|
||||
return []byte(v), nil
|
||||
|
||||
case []byte:
|
||||
if len(v) == 0 {
|
||||
return nil, fmt.Errorf("payload is empty []byte")
|
||||
}
|
||||
return v, nil
|
||||
|
||||
case string:
|
||||
if v == "" {
|
||||
return nil, fmt.Errorf("payload is empty string")
|
||||
}
|
||||
return []byte(v), nil
|
||||
|
||||
case map[string]any:
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal map payload: %w", err)
|
||||
}
|
||||
return b, nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported payload type %T", e.Payload)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user