1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | const url = require('url');
|
8 | const util = require('./utils');
|
9 | const micromatch = require('micromatch');
|
10 | const isGlob = require('is-glob');
|
11 | const _ = require('lodash');
|
12 |
|
13 | const ERRORS = {
|
14 | ERR_CONFIG_FACTORY_TARGET_MISSING: 'Missing "target" option. Example: {target: "http://www.example.org"}',
|
15 | ERR_CONTEXT_MATCHER_GENERIC: 'Invalid context. Expecting something like: "/api" or ["/api", "/ajax"]',
|
16 | ERR_CONTEXT_MATCHER_INVALID_ARRAY: 'Invalid context. Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"]',
|
17 | ERR_PATH_REWRITER_CONFIG: 'Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function'
|
18 | };
|
19 |
|
20 | module.exports = (context, uri, req) =>{
|
21 |
|
22 | if(isStringPath(context)){
|
23 | return matchSingleStringPath(context, uri);
|
24 | }
|
25 |
|
26 |
|
27 | if(util.isRegExp(context)){
|
28 | return matchRegExpPath(context, uri);
|
29 | }
|
30 |
|
31 |
|
32 | if(isGlobPath(context)){
|
33 | return matchSingleGlobPath(context, uri)
|
34 | }
|
35 |
|
36 |
|
37 | if(Array.isArray(context)){
|
38 | if(context.every(isStringPath)){
|
39 | return matchMultiPath(context, uri)
|
40 | }
|
41 | if(context.every(isGlobPath)){
|
42 | return matchMultiGlobPath(context, uri);
|
43 | }
|
44 |
|
45 | throw new Error(ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
|
46 | }
|
47 |
|
48 |
|
49 | if(_.isFunction(context)){
|
50 | let pathname = getUrlPathName(uri);
|
51 | return context(pathname, req);
|
52 | }
|
53 |
|
54 | throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC);
|
55 | };
|
56 |
|
57 | function matchSingleStringPath(context, uri){
|
58 | let pathname = getUrlPathName(uri);
|
59 | return pathname.indexOf(context) === 0;
|
60 | }
|
61 |
|
62 | function matchRegExpPath(context, uri){
|
63 | let pathname = getUrlPathName(uri);
|
64 | return context.test(pathname);
|
65 | }
|
66 |
|
67 | function matchSingleGlobPath(pattern, uri){
|
68 | let pathname = getUrlPathName(uri);
|
69 | let matches = micromatch(pathname, pattern);
|
70 | return matches && (matches.length > 0)
|
71 | }
|
72 |
|
73 | function matchMultiGlobPath(patternList, uri){
|
74 | return matchSingleGlobPath(patternList, uri)
|
75 | }
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | function matchMultiPath(contextList, uri){
|
83 | for(let i = 0; i < contextList.length; i++){
|
84 | let context = contextList[i];
|
85 | if(matchSingleStringPath(context, uri)){
|
86 | return true;
|
87 | }
|
88 | }
|
89 | return false
|
90 | }
|
91 |
|
92 | function getUrlPathName(uri){
|
93 | return uri && url.parse(uri).pathname;
|
94 | }
|
95 |
|
96 | function isStringPath(context){
|
97 | return _.isString(context) && !isGlob(context)
|
98 | }
|
99 |
|
100 | function isGlobPath(context){
|
101 | return isGlob(context)
|
102 | }
|