UNPKG

2.91 kBJavaScriptView Raw
1/**
2 * Created by Rodey on 2017/11/1
3 * match { proxy | url } context
4 */
5'use strict';
6
7const url = require('url');
8const util = require('./utils');
9const micromatch = require('micromatch');
10const isGlob = require('is-glob');
11const _ = require('lodash');
12
13const 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
20module.exports = (context, uri, req) =>{
21 // single path
22 if(isStringPath(context)){
23 return matchSingleStringPath(context, uri);
24 }
25
26 // RegExp context
27 if(util.isRegExp(context)){
28 return matchRegExpPath(context, uri);
29 }
30
31 // single glob path
32 if(isGlobPath(context)){
33 return matchSingleGlobPath(context, uri)
34 }
35
36 // multi path
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 // custom matching
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
57function matchSingleStringPath(context, uri){
58 let pathname = getUrlPathName(uri);
59 return pathname.indexOf(context) === 0;
60}
61
62function matchRegExpPath(context, uri){
63 let pathname = getUrlPathName(uri);
64 return context.test(pathname);
65}
66
67function matchSingleGlobPath(pattern, uri){
68 let pathname = getUrlPathName(uri);
69 let matches = micromatch(pathname, pattern);
70 return matches && (matches.length > 0)
71}
72
73function matchMultiGlobPath(patternList, uri){
74 return matchSingleGlobPath(patternList, uri)
75}
76
77/**
78 * @param {String} contextList ['/api', '/ajax']
79 * @param {String} uri 'http://example.org/api/b/c/d.html'
80 * @return {Boolean}
81 */
82function 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
92function getUrlPathName(uri){
93 return uri && url.parse(uri).pathname;
94}
95
96function isStringPath(context){
97 return _.isString(context) && !isGlob(context)
98}
99
100function isGlobPath(context){
101 return isGlob(context)
102}