-
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(hass): ✨ add validation of sensor requests
- support requests providing a validation function that is run before request is sent to HA - add basic validation to sensor registration and update requests
- Loading branch information
Showing
3 changed files
with
73 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// Copyright (c) 2024 Joshua Rich <joshua.rich@gmail.com> | ||
// | ||
// This software is released under the MIT License. | ||
// https://opensource.org/licenses/MIT | ||
|
||
package sensor | ||
|
||
import ( | ||
"errors" | ||
"strings" | ||
|
||
"github.com/go-playground/validator/v10" | ||
) | ||
|
||
var validate *validator.Validate | ||
|
||
var ErrValidationFailed = errors.New("validation failed") | ||
|
||
func init() { | ||
validate = validator.New(validator.WithRequiredStructEnabled()) | ||
} | ||
|
||
//nolint:errorlint | ||
//revive:disable:unhandled-error | ||
func parseValidationErrors(validation error) string { | ||
validationErrs, ok := validation.(validator.ValidationErrors) | ||
if !ok { | ||
return "internal validation error" | ||
} | ||
|
||
var message strings.Builder | ||
|
||
for _, err := range validationErrs { | ||
switch err.Tag() { | ||
case "required": | ||
message.WriteString(err.Field() + " is required") | ||
default: | ||
message.WriteString(err.Field() + " should match " + err.Tag()) | ||
} | ||
|
||
message.WriteRune(' ') | ||
} | ||
|
||
return message.String() | ||
} |