45 lines
982 B
Go
45 lines
982 B
Go
package router
|
|
|
|
import (
|
|
"context"
|
|
"regexp"
|
|
"sort"
|
|
|
|
"github.com/paramah/gw_telegram/internal/domain/apperror"
|
|
"github.com/paramah/gw_telegram/internal/domain/entity"
|
|
)
|
|
|
|
type Rule struct {
|
|
Pattern *regexp.Regexp
|
|
IntentName string
|
|
Target entity.RouteTarget
|
|
Priority int
|
|
}
|
|
|
|
type RuleBasedRouter struct {
|
|
rules []Rule
|
|
}
|
|
|
|
func NewRuleBasedRouter(rules []Rule) *RuleBasedRouter {
|
|
sorted := make([]Rule, len(rules))
|
|
copy(sorted, rules)
|
|
sort.Slice(sorted, func(i, j int) bool {
|
|
return sorted[i].Priority > sorted[j].Priority
|
|
})
|
|
return &RuleBasedRouter{rules: sorted}
|
|
}
|
|
|
|
func (r *RuleBasedRouter) Route(_ context.Context, msg entity.Message) (entity.Route, error) {
|
|
for _, rule := range r.rules {
|
|
if rule.Pattern.MatchString(msg.Text) {
|
|
return entity.Route{
|
|
Pattern: rule.Pattern.String(),
|
|
IntentName: rule.IntentName,
|
|
Target: rule.Target,
|
|
Priority: rule.Priority,
|
|
}, nil
|
|
}
|
|
}
|
|
return entity.Route{}, apperror.ErrRouteNotFound
|
|
}
|