router.js 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /*
  2. Copyright 2014 Google Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. 'use strict';
  14. var Route = require('./route');
  15. var helpers = require('./helpers');
  16. function regexEscape(s) {
  17. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18. }
  19. var keyMatch = function(map, string) {
  20. // This would be better written as a for..of loop, but that would break the
  21. // minifyify process in the build.
  22. var entriesIterator = map.entries();
  23. var item = entriesIterator.next();
  24. var matches = [];
  25. while (!item.done) {
  26. var pattern = new RegExp(item.value[0]);
  27. if (pattern.test(string)) {
  28. matches.push(item.value[1]);
  29. }
  30. item = entriesIterator.next();
  31. }
  32. return matches;
  33. };
  34. var Router = function() {
  35. this.routes = new Map();
  36. // Create the dummy origin for RegExp-based routes
  37. this.routes.set(RegExp, new Map());
  38. this.default = null;
  39. };
  40. ['get', 'post', 'put', 'delete', 'head', 'any'].forEach(function(method) {
  41. Router.prototype[method] = function(path, handler, options) {
  42. return this.add(method, path, handler, options);
  43. };
  44. });
  45. Router.prototype.add = function(method, path, handler, options) {
  46. options = options || {};
  47. var origin;
  48. if (path instanceof RegExp) {
  49. // We need a unique key to use in the Map to distinguish RegExp paths
  50. // from Express-style paths + origins. Since we can use any object as the
  51. // key in a Map, let's use the RegExp constructor!
  52. origin = RegExp;
  53. } else {
  54. origin = options.origin || self.location.origin;
  55. if (origin instanceof RegExp) {
  56. origin = origin.source;
  57. } else {
  58. origin = regexEscape(origin);
  59. }
  60. }
  61. method = method.toLowerCase();
  62. var route = new Route(method, path, handler, options);
  63. if (!this.routes.has(origin)) {
  64. this.routes.set(origin, new Map());
  65. }
  66. var methodMap = this.routes.get(origin);
  67. if (!methodMap.has(method)) {
  68. methodMap.set(method, new Map());
  69. }
  70. var routeMap = methodMap.get(method);
  71. var regExp = route.regexp || route.fullUrlRegExp;
  72. if (routeMap.has(regExp.source)) {
  73. helpers.debug('"' + path + '" resolves to same regex as existing route.');
  74. }
  75. routeMap.set(regExp.source, route);
  76. };
  77. Router.prototype.matchMethod = function(method, url) {
  78. var urlObject = new URL(url);
  79. var origin = urlObject.origin;
  80. var path = urlObject.pathname;
  81. // We want to first check to see if there's a match against any
  82. // "Express-style" routes (string for the path, RegExp for the origin).
  83. // Checking for Express-style matches first maintains the legacy behavior.
  84. // If there's no match, we next check for a match against any RegExp routes,
  85. // where the RegExp in question matches the full URL (both origin and path).
  86. return this._match(method, keyMatch(this.routes, origin), path) ||
  87. this._match(method, [this.routes.get(RegExp)], url);
  88. };
  89. Router.prototype._match = function(method, methodMaps, pathOrUrl) {
  90. if (methodMaps.length === 0) {
  91. return null;
  92. }
  93. for (var i = 0; i < methodMaps.length; i++) {
  94. var methodMap = methodMaps[i];
  95. var routeMap = methodMap && methodMap.get(method.toLowerCase());
  96. if (routeMap) {
  97. var routes = keyMatch(routeMap, pathOrUrl);
  98. if (routes.length > 0) {
  99. return routes[0].makeHandler(pathOrUrl);
  100. }
  101. }
  102. }
  103. return null;
  104. };
  105. Router.prototype.match = function(request) {
  106. return this.matchMethod(request.method, request.url) ||
  107. this.matchMethod('any', request.url);
  108. };
  109. module.exports = new Router();