index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var URL = require('url');
  2. module.exports = function (options) {
  3. var parent = this;
  4. var opts = typeof options === 'function' ? {custom: options} : options;
  5. opts.useOriginalUrl = (typeof opts.useOriginalUrl === 'undefined') ? true : opts.useOriginalUrl;
  6. return function (req, res, next) {
  7. var url = URL.parse((opts.useOriginalUrl ? req.originalUrl : req.url) || req.url || '', true);
  8. var skip = false;
  9. if (opts.custom) {
  10. skip = skip || opts.custom(req);
  11. }
  12. var paths = !opts.path || Array.isArray(opts.path) ?
  13. opts.path : [opts.path];
  14. if (paths) {
  15. skip = skip || paths.some(function (p) {
  16. return isUrlMatch(p, url.pathname) && isMethodMatch(p.methods, req.method);
  17. });
  18. }
  19. var exts = (!opts.ext || Array.isArray(opts.ext)) ?
  20. opts.ext : [opts.ext];
  21. if (exts) {
  22. skip = skip || exts.some(function (ext) {
  23. return url.pathname.substr(ext.length * -1) === ext;
  24. });
  25. }
  26. var methods = (!opts.method || Array.isArray(opts.method)) ?
  27. opts.method : [opts.method];
  28. if (methods) {
  29. skip = skip || !!~methods.indexOf(req.method);
  30. }
  31. if (skip) {
  32. return next();
  33. }
  34. parent(req, res, next);
  35. };
  36. };
  37. function isUrlMatch(p, url) {
  38. var ret = (typeof p === 'string' && p === url) || (p instanceof RegExp && !!p.exec(url));
  39. if (p instanceof RegExp) {
  40. p.lastIndex = 0;
  41. }
  42. if (p && p.url) {
  43. ret = isUrlMatch(p.url, url)
  44. }
  45. return ret;
  46. }
  47. function isMethodMatch(methods, m) {
  48. if (!methods) {
  49. return true;
  50. }
  51. methods = Array.isArray(methods) ? methods : [methods];
  52. return !!~methods.indexOf(m);
  53. }