forked from vuelidate/vuelidate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparams.js
61 lines (53 loc) · 1.3 KB
/
params.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const stack = []
// exported for tests
export let target = null
export const _setTarget = x => { target = x }
export function pushParams () {
if (target !== null) {
stack.push(target)
}
target = {}
}
export function popParams () {
const lastTarget = target
const newTarget = target = stack.pop() || null
if (newTarget) {
if (!Array.isArray(newTarget.$sub)) {
newTarget.$sub = []
}
newTarget.$sub.push(lastTarget)
}
return lastTarget
}
function addParams (params) {
if (typeof params === 'object' && !Array.isArray(params)) {
target = {...target, ...params}
} else {
throw new Error('params must be an object')
}
}
function withParamsDirect (params, validator) {
return withParamsClosure(add => {
return function (...args) {
add(params)
return validator.apply(this, args)
}
})
}
function withParamsClosure (closure) {
const validator = closure(addParams)
return function (...args) {
pushParams()
try {
return validator.apply(this, args)
} finally {
popParams()
}
}
}
export function withParams (paramsOrClosure, maybeValidator) {
if (typeof paramsOrClosure === 'object' && maybeValidator !== undefined) {
return withParamsDirect(paramsOrClosure, maybeValidator)
}
return withParamsClosure(paramsOrClosure)
}