source: trip-planner-front/node_modules/http-proxy-middleware/lib/context-matcher.js@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.1 KB
Line 
1var _ = require('lodash')
2var url = require('url')
3var isGlob = require('is-glob')
4var micromatch = require('micromatch')
5var ERRORS = require('./errors')
6
7module.exports = {
8 match: matchContext
9}
10
11function matchContext(context, uri, req) {
12 // single path
13 if (isStringPath(context)) {
14 return matchSingleStringPath(context, uri)
15 }
16
17 // single glob path
18 if (isGlobPath(context)) {
19 return matchSingleGlobPath(context, uri)
20 }
21
22 // multi path
23 if (Array.isArray(context)) {
24 if (context.every(isStringPath)) {
25 return matchMultiPath(context, uri)
26 }
27 if (context.every(isGlobPath)) {
28 return matchMultiGlobPath(context, uri)
29 }
30
31 throw new Error(ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY)
32 }
33
34 // custom matching
35 if (_.isFunction(context)) {
36 var pathname = getUrlPathName(uri)
37 return context(pathname, req)
38 }
39
40 throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC)
41}
42
43/**
44 * @param {String} context '/api'
45 * @param {String} uri 'http://example.org/api/b/c/d.html'
46 * @return {Boolean}
47 */
48function matchSingleStringPath(context, uri) {
49 var pathname = getUrlPathName(uri)
50 return pathname.indexOf(context) === 0
51}
52
53function matchSingleGlobPath(pattern, uri) {
54 var pathname = getUrlPathName(uri)
55 var matches = micromatch(pathname, pattern)
56 return matches && matches.length > 0
57}
58
59function matchMultiGlobPath(patternList, uri) {
60 return matchSingleGlobPath(patternList, uri)
61}
62
63/**
64 * @param {String} contextList ['/api', '/ajax']
65 * @param {String} uri 'http://example.org/api/b/c/d.html'
66 * @return {Boolean}
67 */
68function matchMultiPath(contextList, uri) {
69 for (var i = 0; i < contextList.length; i++) {
70 var context = contextList[i]
71 if (matchSingleStringPath(context, uri)) {
72 return true
73 }
74 }
75 return false
76}
77
78/**
79 * Parses URI and returns RFC 3986 path
80 *
81 * @param {String} uri from req.url
82 * @return {String} RFC 3986 path
83 */
84function getUrlPathName(uri) {
85 return uri && url.parse(uri).pathname
86}
87
88function isStringPath(context) {
89 return _.isString(context) && !isGlob(context)
90}
91
92function isGlobPath(context) {
93 return isGlob(context)
94}
Note: See TracBrowser for help on using the repository browser.