index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const pathToRegexp = require('path-to-regexp');
  3. module.exports = function(options) {
  4. options = options || {};
  5. if (options.match && options.ignore) throw new Error('options.match and options.ignore can not both present');
  6. if (!options.match && !options.ignore) return () => true;
  7. const matchFn = options.match ? toPathMatch(options.match) : toPathMatch(options.ignore);
  8. return function pathMatch(ctx) {
  9. const matched = matchFn(ctx);
  10. return options.match ? matched : !matched;
  11. };
  12. };
  13. function toPathMatch(pattern) {
  14. if (typeof pattern === 'string') {
  15. const reg = pathToRegexp(pattern, [], { end: false });
  16. if (reg.global) reg.lastIndex = 0;
  17. return ctx => reg.test(ctx.path);
  18. }
  19. if (pattern instanceof RegExp) {
  20. return ctx => {
  21. if (pattern.global) pattern.lastIndex = 0;
  22. return pattern.test(ctx.path);
  23. };
  24. }
  25. if (typeof pattern === 'function') return pattern;
  26. if (Array.isArray(pattern)) {
  27. const matchs = pattern.map(item => toPathMatch(item));
  28. return ctx => matchs.some(match => match(ctx));
  29. }
  30. throw new Error('match/ignore pattern must be RegExp, Array or String, but got ' + pattern);
  31. }