-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.ts
88 lines (74 loc) · 2.18 KB
/
utils.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import type { PumpIt } from './pumpit'
import { BindKey, ResolveCtx } from './types'
//detect transfom action function
export const TRANSFORM_DEPS = Symbol()
//detect injection function
const INJECTION_FN = Symbol()
export type ParsedInjectionData =
| { key: BindKey; options: { optional?: boolean; lazy?: boolean } } //get
| {
key: { key: BindKey; options: { optional?: boolean } }[]
options: {
optional?: boolean
removeUndefined?: boolean
setToUndefinedIfEmpty?: boolean
}
}
export type Injection = BindKey | ReturnType<typeof get>
export type InjectionData =
| Injection[]
| { action: symbol; fn: (...args: any) => any; deps: Injection[] }
/**
* get dependency by key
* @param key - dependency {@link BindKey | BindKey}
* @param options - options for the resove process
*/
export function get(
key: BindKey,
options?: {
/** if the dependency cannot be resolved *undefined* will be used */
optional?: boolean
}
) {
const getCall = () => {
return {
key,
options: { ...options }
}
}
getCall[INJECTION_FN] = INJECTION_FN
return getCall
}
function isInjectionFn(value: any): value is ReturnType<typeof get> {
return Boolean(value[INJECTION_FN])
}
export function parseInjectionData(key: Injection): ParsedInjectionData {
if (isInjectionFn(key)) {
const ex = key()
return {
key: ex.key,
options: ex.options || {}
}
}
return { key, options: { optional: false } }
}
/**
* Wrapper function for registering dependencies that can be manipulated before being injected
* It gets an array of dependencies in injection order, and it should return an array
* @param deps - array of dependencies that need to be satisfied see: {@link BindKey | BindKey} {@link get | get()}
* @param fn - function that will be called with the resolved dependencies
*/
export function transform(
deps: (BindKey | typeof get)[],
fn: (data: { container: PumpIt; ctx: ResolveCtx }, ...deps: any[]) => any[]
) {
return {
action: TRANSFORM_DEPS,
fn: fn,
deps
}
}
export function keyToString(key: BindKey) {
// @ts-expect-error name does not exist on string or symbol
return String(key.name || key)
}