UI for Zipcoin Blue

context-matcher.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var _ = require('lodash');
  2. var url = require('url');
  3. var isGlob = require('is-glob');
  4. var micromatch = require('micromatch');
  5. module.exports = {
  6. match: matchContext
  7. };
  8. function matchContext(context, uri, req) {
  9. // single path
  10. if (isStringPath(context)) {
  11. return matchSingleStringPath(context, uri);
  12. }
  13. // single glob path
  14. if (isGlobPath(context)) {
  15. return matchSingleGlobPath(context, uri);
  16. }
  17. // multi path
  18. if (Array.isArray(context)) {
  19. if (context.every(isStringPath)) {
  20. return matchMultiPath(context, uri);
  21. }
  22. if (context.every(isGlobPath)) {
  23. return matchMultiGlobPath(context, uri);
  24. }
  25. throw new Error('[HPM] Invalid context. Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"]');
  26. }
  27. // custom matching
  28. if (_.isFunction(context)) {
  29. var pathname = getUrlPathName(uri);
  30. return context(pathname, req);
  31. }
  32. throw new Error('[HPM] Invalid context. Expecting something like: "/api" or ["/api", "/ajax"]');
  33. }
  34. /**
  35. * @param {String} context '/api'
  36. * @param {String} uri 'http://example.org/api/b/c/d.html'
  37. * @return {Boolean}
  38. */
  39. function matchSingleStringPath(context, uri) {
  40. var pathname = getUrlPathName(uri);
  41. return pathname.indexOf(context) === 0;
  42. }
  43. function matchSingleGlobPath(pattern, uri) {
  44. var pathname = getUrlPathName(uri);
  45. var matches = micromatch(pathname, pattern);
  46. return matches && (matches.length > 0);
  47. }
  48. function matchMultiGlobPath(patternList, uri) {
  49. return matchSingleGlobPath(patternList, uri);
  50. }
  51. /**
  52. * @param {String} context ['/api', '/ajax']
  53. * @param {String} uri 'http://example.org/api/b/c/d.html'
  54. * @return {Boolean}
  55. */
  56. function matchMultiPath(contextList, uri) {
  57. for (var i = 0; i < contextList.length; i++) {
  58. var context = contextList[i];
  59. if (matchSingleStringPath(context, uri)) {
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. /**
  66. * Parses URI and returns RFC 3986 path
  67. *
  68. * @param {String} uri from req.url
  69. * @return {String} RFC 3986 path
  70. */
  71. function getUrlPathName(uri) {
  72. return uri && url.parse(uri).pathname;
  73. }
  74. function isStringPath(context) {
  75. return _.isString(context) && !isGlob(context);
  76. }
  77. function isGlobPath(context) {
  78. return isGlob(context);
  79. }