Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add replace rule function #338

Merged
merged 1 commit into from
Dec 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@ type Rule struct {

var specifiedRules []Rule

// AddRule adds rule to the rule set.
// f is called once each time `Validate` is executed.
// AddRule adds a rule to the rule set.
// ruleFunc is called once each time `Validate` is executed.
func AddRule(name string, ruleFunc RuleFunc) {
specifiedRules = append(specifiedRules, Rule{Name: name, RuleFunc: ruleFunc})
}

// RemoveRule removes an existing rule from the rule set
// if one of the same name exists.
// The rule set is global, so it is not safe for concurrent changes
func RemoveRule(name string) {
var result []Rule // nolint:prealloc // using initialized with len(rules) produces a race condition
for _, r := range specifiedRules {
Expand All @@ -34,6 +37,28 @@ func RemoveRule(name string) {
specifiedRules = result
}

// ReplaceRule replaces an existing rule from the rule set
// if one of the same name exists.
// If no match is found, it will add a new rule to the rule set.
// The rule set is global, so it is not safe for concurrent changes
func ReplaceRule(name string, ruleFunc RuleFunc) {
var found bool
var result []Rule // nolint:prealloc // using initialized with len(rules) produces a race condition
for _, r := range specifiedRules {
if r.Name == name {
found = true
result = append(result, Rule{Name: name, RuleFunc: ruleFunc})
continue
}
result = append(result, r)
}
if !found {
specifiedRules = append(specifiedRules, Rule{Name: name, RuleFunc: ruleFunc})
return
}
specifiedRules = result
}

func Validate(schema *Schema, doc *QueryDocument, rules ...Rule) gqlerror.List {
if rules == nil {
rules = specifiedRules
Expand Down
Loading