platform/lib/src/route.dart

65 lines
1.7 KiB
Dart
Raw Normal View History

2016-11-22 03:31:09 +00:00
part of angel_route.src.router;
2016-10-11 18:53:32 +00:00
/// Represents a virtual location within an application.
2016-10-11 18:53:32 +00:00
class Route {
2017-11-27 02:21:19 +00:00
final String method;
final String path;
final List handlers;
final Map<String, Map<String, String>> _cache = {};
final _RouteDefinition _routeDefinition;
String name;
Parser<Map<String, String>> _parser;
2016-10-14 03:07:34 +00:00
2017-11-27 02:21:19 +00:00
Route(this.path, {@required this.method, @required this.handlers})
: _routeDefinition = _RouteGrammar.routeDefinition
.parse(new SpanScanner(path.replaceAll(_straySlashes, '')))
.value {
if (_routeDefinition.segments.isEmpty) _parser = match('').value((r) => {});
2016-10-14 03:07:34 +00:00
}
2017-11-27 02:21:19 +00:00
factory Route.join(Route a, Route b) {
var start = a.path.replaceAll(_straySlashes, '');
var end = b.path.replaceAll(_straySlashes, '');
return new Route('$start/$end'.replaceAll(_straySlashes, ''),
method: b.method, handlers: b.handlers);
2016-10-21 03:13:13 +00:00
}
2017-11-27 02:21:19 +00:00
Parser<Map<String, String>> get parser =>
_parser ??= _routeDefinition.compile();
2016-10-11 18:53:32 +00:00
2016-10-21 03:13:13 +00:00
2017-11-27 02:21:19 +00:00
@override
String toString() {
return '$method $path => $handlers';
2016-10-11 18:53:32 +00:00
}
2016-11-23 18:58:34 +00:00
Route clone() {
2017-11-27 02:21:19 +00:00
return new Route(path, method: method, handlers: handlers)
.._cache.addAll(_cache);
2016-11-23 18:58:34 +00:00
}
2017-11-27 02:21:19 +00:00
/// Use the setter instead.
@deprecated
void as(String n) {
name = n;
2016-10-12 17:58:32 +00:00
}
2017-11-27 02:21:19 +00:00
String makeUri(Map<String, dynamic> params) {
var b = new StringBuffer();
int i = 0;
2017-11-27 02:21:19 +00:00
for (var seg in _routeDefinition.segments) {
if (i++ > 0) b.write('/');
if (seg is _ConstantSegment)
b.write(seg.text);
else if (seg is _ParameterSegment) {
if (!params.containsKey(seg.name))
throw new ArgumentError('Missing parameter "${seg.name}".');
b.write(params[seg.name]);
2016-10-21 03:13:13 +00:00
}
}
2017-11-27 02:21:19 +00:00
return b.toString();
2016-10-11 18:53:32 +00:00
}
2017-10-08 22:44:11 +00:00
}