-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a2cf7ae
commit 4a863c2
Showing
3 changed files
with
92 additions
and
0 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,75 @@ | ||
package match | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
|
||
"github.com/tidwall/gjson" | ||
"github.com/tidwall/sjson" | ||
) | ||
|
||
type typeMatcher[T any] struct { | ||
paths []string | ||
errOnMissingPath bool | ||
name string | ||
_type interface{} | ||
} | ||
|
||
func Type[T any](paths ...string) *typeMatcher[T] { | ||
return &typeMatcher[T]{ | ||
paths: paths, | ||
errOnMissingPath: true, | ||
name: "Type", | ||
_type: *new(T), | ||
} | ||
} | ||
|
||
// ErrOnMissingPath determines if matcher will fail in case of trying to access a json path | ||
// that doesn't exist | ||
func (t *typeMatcher[T]) ErrOnMissingPath(e bool) *typeMatcher[T] { | ||
t.errOnMissingPath = e | ||
return t | ||
} | ||
|
||
func (t typeMatcher[T]) JSON(s []byte) ([]byte, []MatcherError) { | ||
var errs []MatcherError | ||
json := s | ||
|
||
for _, path := range t.paths { | ||
r := gjson.GetBytes(json, path) | ||
if !r.Exists() { | ||
if t.errOnMissingPath { | ||
errs = append(errs, MatcherError{ | ||
Reason: errors.New("path does not exist"), | ||
Matcher: t.name, | ||
Path: path, | ||
}) | ||
} | ||
continue | ||
} | ||
|
||
_, ok := r.Value().(T) | ||
value := fmt.Sprintf("<Type:%T>", *new(T)) | ||
if !ok { | ||
value = fmt.Sprintf("<Type:%T>", r.Value()) | ||
} | ||
|
||
j, err := sjson.SetBytesOptions(json, path, value, &sjson.Options{ | ||
Optimistic: true, | ||
ReplaceInPlace: true, | ||
}) | ||
if err != nil { | ||
errs = append(errs, MatcherError{ | ||
Reason: err, | ||
Matcher: t.name, | ||
Path: path, | ||
}) | ||
|
||
continue | ||
} | ||
|
||
json = j | ||
} | ||
|
||
return json, errs | ||
} |