feat: added role for bap and bpp

This commit is contained in:
mayur.popli
2025-03-21 04:44:58 +05:30
parent 5e3422fb24
commit 02fb7c0897
2 changed files with 38 additions and 43 deletions

View File

@@ -14,11 +14,12 @@ import (
type Config struct { type Config struct {
checkKeys []string checkKeys []string
Role string
} }
type contextKeyType string type contextKeyType string
const contextKey = "context" const contextKey = "context"
const subscriberIDKey contextKeyType = "subscriber_id"
func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) { func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) {
if err := validateConfig(cfg); err != nil { if err := validateConfig(cfg); err != nil {
@@ -47,7 +48,14 @@ func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) {
http.Error(w, fmt.Sprintf("%s field is not a map.", contextKey), http.StatusBadRequest) http.Error(w, fmt.Sprintf("%s field is not a map.", contextKey), http.StatusBadRequest)
return return
} }
ctx := r.Context() var subID any
switch cfg.Role {
case "bap":
subID = contextData["bap_id"]
case "bpp":
subID = contextData["bpp_id"]
}
ctx := context.WithValue(r.Context(), subscriberIDKey, subID)
for _, key := range cfg.checkKeys { for _, key := range cfg.checkKeys {
value := uuid.NewString() value := uuid.NewString()
updatedValue := update(contextData, key, value) updatedValue := update(contextData, key, value)
@@ -90,9 +98,6 @@ func validateConfig(cfg *Config) error {
if cfg == nil { if cfg == nil {
return errors.New("config cannot be nil") return errors.New("config cannot be nil")
} }
if len(cfg.checkKeys) == 0 {
return errors.New("checkKeys cannot be empty")
}
for _, key := range cfg.checkKeys { for _, key := range cfg.checkKeys {
if key == "" { if key == "" {
return errors.New("checkKeys cannot contain empty strings") return errors.New("checkKeys cannot contain empty strings")

View File

@@ -3,7 +3,6 @@ package reqpreprocessor
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@@ -16,34 +15,41 @@ func TestNewUUIDSetter(t *testing.T) {
requestBody map[string]any requestBody map[string]any
expectedCode int expectedCode int
expectedKeys []string expectedKeys []string
role string
}{ }{
{ {
name: "Valid keys, update missing keys", name: "Valid keys, update missing keys with bap role",
config: &Config{ config: &Config{
checkKeys: []string{"transaction_id", "message_id"}, checkKeys: []string{"transaction_id", "message_id"},
Role: "bap",
}, },
requestBody: map[string]any{ requestBody: map[string]any{
"context": map[string]any{ "context": map[string]any{
"transaction_id": "", "transaction_id": "",
"message_id": nil, "message_id": nil,
"bap_id": "bap-123",
}, },
}, },
expectedCode: http.StatusOK, expectedCode: http.StatusOK,
expectedKeys: []string{"transaction_id", "message_id"}, expectedKeys: []string{"transaction_id", "message_id", "bap_id"},
role: "bap",
}, },
{ {
name: "Valid keys, do not update existing keys", name: "Valid keys, do not update existing keys with bpp role",
config: &Config{ config: &Config{
checkKeys: []string{"transaction_id", "message_id"}, checkKeys: []string{"transaction_id", "message_id"},
Role: "bpp",
}, },
requestBody: map[string]any{ requestBody: map[string]any{
"context": map[string]any{ "context": map[string]any{
"transaction_id": "existing-transaction", "transaction_id": "existing-transaction",
"message_id": "existing-message", "message_id": "existing-message",
"bpp_id": "bpp-456",
}, },
}, },
expectedCode: http.StatusOK, expectedCode: http.StatusOK,
expectedKeys: []string{"transaction_id", "message_id"}, expectedKeys: []string{"transaction_id", "message_id", "bpp_id"},
role: "bpp",
}, },
{ {
name: "Missing context key", name: "Missing context key",
@@ -65,18 +71,6 @@ func TestNewUUIDSetter(t *testing.T) {
}, },
expectedCode: http.StatusBadRequest, expectedCode: http.StatusBadRequest,
}, },
{
name: "Empty checkKeys in config",
config: &Config{
checkKeys: []string{},
},
requestBody: map[string]any{
"context": map[string]any{
"transaction_id": "",
},
},
expectedCode: http.StatusInternalServerError,
},
{ {
name: "Nil config", name: "Nil config",
config: nil, config: nil,
@@ -97,48 +91,44 @@ func TestNewUUIDSetter(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Unexpected error while creating middleware: %v", err) t.Fatalf("Unexpected error while creating middleware: %v", err)
} }
// Prepare request
bodyBytes, _ := json.Marshal(tt.requestBody) bodyBytes, _ := json.Marshal(tt.requestBody)
req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(bodyBytes)) req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
// Define a dummy handler
dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, r.Body); err != nil { if subID, ok := ctx.Value(subscriberIDKey).(string); ok {
http.Error(w, "Failed to copy request body", http.StatusInternalServerError) response := map[string]any{
"subscriber_id": subID,
}
json.NewEncoder(w).Encode(response)
} else {
http.Error(w, "Subscriber ID not found", http.StatusInternalServerError)
return return
} }
}) })
// Apply middleware
middleware(dummyHandler).ServeHTTP(rec, req) middleware(dummyHandler).ServeHTTP(rec, req)
// Check status code
if rec.Code != tt.expectedCode { if rec.Code != tt.expectedCode {
t.Errorf("Expected status code %d, but got %d", tt.expectedCode, rec.Code) t.Errorf("Expected status code %d, but got %d", tt.expectedCode, rec.Code)
} }
// If success, check updated keys
if rec.Code == http.StatusOK { if rec.Code == http.StatusOK {
var responseBody map[string]any var responseBody map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &responseBody); err != nil { if err := json.Unmarshal(rec.Body.Bytes(), &responseBody); err != nil {
t.Fatal("Failed to unmarshal response body:", err) t.Fatal("Failed to unmarshal response body:", err)
} }
expectedSubIDKey := "bap_id"
// Validate updated keys if tt.role == "bpp" {
contextData, ok := responseBody[contextKey].(map[string]any) expectedSubIDKey = "bpp_id"
if !ok {
t.Fatalf("Expected context to be a map, got %T", responseBody[contextKey])
} }
for _, key := range tt.expectedKeys { if subID, ok := responseBody["subscriber_id"].(string); ok {
value, exists := contextData[key] expectedSubID := tt.requestBody["context"].(map[string]any)[expectedSubIDKey]
if !exists || isEmpty(value) { if subID != expectedSubID {
t.Errorf("Expected key %s to be set, but it's missing or empty", key) t.Errorf("Expected subscriber_id %v, but got %v", expectedSubID, subID)
} }
} else {
t.Error("subscriber_id not found in response")
} }
} }
}) })