|
| 1 | +package dbt_cloud |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/go-playground/validator/v10" |
| 8 | +) |
| 9 | + |
| 10 | +// ResponseValidator is a singleton instance of the validator |
| 11 | +var validate *validator.Validate |
| 12 | + |
| 13 | +func init() { |
| 14 | + validate = validator.New(validator.WithRequiredStructEnabled()) |
| 15 | +} |
| 16 | + |
| 17 | +// ValidationError wraps validator errors with the API response for debugging |
| 18 | +type ValidationError struct { |
| 19 | + Message string |
| 20 | + FieldErrors []FieldError |
| 21 | + Response interface{} |
| 22 | +} |
| 23 | + |
| 24 | +type FieldError struct { |
| 25 | + Field string |
| 26 | + Tag string |
| 27 | + Value interface{} |
| 28 | + Message string |
| 29 | +} |
| 30 | + |
| 31 | +func (e *ValidationError) Error() string { |
| 32 | + responseJSON, _ := json.MarshalIndent(e.Response, "", " ") |
| 33 | + |
| 34 | + msg := fmt.Sprintf("API response validation failed:\n%s\n\nFields with errors:\n", e.Message) |
| 35 | + for _, fe := range e.FieldErrors { |
| 36 | + msg += fmt.Sprintf(" - %s: %s (value: %v)\n", fe.Field, fe.Message, fe.Value) |
| 37 | + } |
| 38 | + msg += fmt.Sprintf("\nFull API response:\n%s", string(responseJSON)) |
| 39 | + |
| 40 | + return msg |
| 41 | +} |
| 42 | + |
| 43 | +// ValidateResponse validates a struct using validator tags |
| 44 | +func ValidateResponse(response interface{}, resourceType string) error { |
| 45 | + err := validate.Struct(response) |
| 46 | + if err == nil { |
| 47 | + return nil |
| 48 | + } |
| 49 | + |
| 50 | + // Convert validation errors to our custom format |
| 51 | + validationErrs, ok := err.(validator.ValidationErrors) |
| 52 | + if !ok { |
| 53 | + // Not a validation error, return as is |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + fieldErrors := make([]FieldError, 0, len(validationErrs)) |
| 58 | + for _, e := range validationErrs { |
| 59 | + fieldErrors = append(fieldErrors, FieldError{ |
| 60 | + Field: e.Field(), |
| 61 | + Tag: e.Tag(), |
| 62 | + Value: e.Value(), |
| 63 | + Message: getErrorMessage(e), |
| 64 | + }) |
| 65 | + } |
| 66 | + |
| 67 | + return &ValidationError{ |
| 68 | + Message: fmt.Sprintf("Validation failed for %s", resourceType), |
| 69 | + FieldErrors: fieldErrors, |
| 70 | + Response: response, |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// getErrorMessage returns a human-readable error message for a validation error |
| 75 | +func getErrorMessage(e validator.FieldError) string { |
| 76 | + switch e.Tag() { |
| 77 | + case "required": |
| 78 | + return "field is required but was nil or empty" |
| 79 | + case "ne": |
| 80 | + return fmt.Sprintf("must not equal %s", e.Param()) |
| 81 | + default: |
| 82 | + return fmt.Sprintf("failed validation tag '%s'", e.Tag()) |
| 83 | + } |
| 84 | +} |
0 commit comments