UNPKG

1.91 kBPlain TextView Raw
1import {matchInstance, matchType} from "./matcher";
2import {TYPE_ARRAY, TYPE_OBJECT, TYPE_STRING} from "../config/baseType";
3import {warnIf} from "./conditionCheck";
4import {ALL} from "../config/regexp";
5import Strategy from "../core/Strategy";
6
7/**
8 * @desc check url if has matched strategy rule, only the first rule is valid
9 * @param rules
10 * @param url
11 * */
12const findMatchStrategy = (rules: Array<Strategy> | Strategy, url: any) => {
13 let matchedRule = null
14
15 if (Array.isArray(rules)) {
16 // return the first matched rule
17 rules.some((rule: any) => {
18 const validStrategy = matchType(rule, TYPE_OBJECT)
19
20 // just warn without block request flow
21 warnIf(
22 !validStrategy,
23 `invalid param storeStrategy, expect [${TYPE_OBJECT}] | [${TYPE_ARRAY}] but got ${typeof rule}`
24 )
25
26 if (validStrategy && matchRule(rule, url)) {
27 matchedRule = rule
28 return true
29 }
30 })
31 } else {
32 const validStrategy = matchType(rules, TYPE_OBJECT)
33
34 // just warn without block request flow
35 warnIf(
36 !validStrategy,
37 `invalid param storeStrategy, expect [${TYPE_OBJECT}] | [${TYPE_ARRAY}] but got ${typeof rules}`
38 )
39
40 if (validStrategy && matchRule(rules, url)) matchedRule = rules
41 }
42
43 return matchedRule
44}
45
46const matchRule = (rule: Strategy, url: any) => {
47 return (
48 rule.urlExp === url || // rule.urlExp match url
49 rule.urlExp === ALL || // rule.urlExp is "*" (all contains)
50 ( // rule.urlExp is instance of RegExp, test url with it
51 matchInstance(rule.urlExp, RegExp) &&
52 rule.urlExp.test(url)
53 )
54 )
55}
56
57export default findMatchStrategy
\No newline at end of file