registerPattern method
Register a request handler for any HTTP method with a Pattern.
This method is used if the caller already has a Pattern object. Usually, an application will have the pattern as a String, in which case it can use the register method instead, which simply converts that string into a Pattern object and then invokes this method.
Throws a DuplicateRule if there is a conflict with an existing rule. A conflict is if Pattern.matchesSamePaths is true for the two patterns.
Implementation
void registerPattern(String method, Pattern pattern, RequestHandler handler) {
if (method.isEmpty) {
throw ArgumentError.value(method, 'method', 'Empty string');
}
_logServer.config('register: $method $pattern');
// Get the list of rules for the HTTP method
var methodRules = _rulesByMethod[method];
if (methodRules == null) {
methodRules = []; // new List<ServerRule>();
_rulesByMethod[method] = methodRules;
}
// Check if another rule already exists with the "same" pattern.
// It is an error if one exists.
//
// It is not an error to have two rules that match a path. The order
// of those rules will determine which one matches, and there can be other
// paths that match one and not the other. So both have a purpose.
//
// But it is an error to have two rules with the "same" pattern. With them,
// the first rule will always match, and there are no paths which will
// not match one and match the other. So one of them is redundant. If it
// was allowed, one of them will never get used.
final newRule = ServerRule(pattern.toString(), handler);
try {
final existingRule = methodRules
.firstWhere((sr) => sr.pattern.matchesSamePaths(newRule.pattern));
// A rule with the "same" pattern already exists: cannot add it
throw DuplicateRule(method, pattern, handler, existingRule.handler);
// ignore: avoid_catching_errors
} on StateError {
// A rule with the "same" pattern does not exist: success: record the rule
methodRules.add(newRule);
}
}