-
Notifications
You must be signed in to change notification settings - Fork 2
/
ParentResult.ts
50 lines (46 loc) · 1.48 KB
/
ParentResult.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
import InternalResult from './InternalResult'
/**
* Type of expected children in parent result.
*/
type ResultChildren = InternalResult<any>[] | { [key: string]: InternalResult<any> }
/**
* Create a proxy handler to return the appropriate result property instead of the result itself.
*
* @param resultProperty - The name of the property.
* @returns The correct handler.
*/
function handle(resultProperty: keyof InternalResult<any>): ProxyHandler<any> {
return {
get: (target, property) => {
const result = target[property]
return result instanceof InternalResult ? result[resultProperty] : result
},
set: () => {
throw new TypeError('Configuration result is immutable')
},
deleteProperty: () => {
throw new TypeError('Configuration result is immutable')
},
defineProperty: () => {
throw new TypeError('Configuration result is immutable')
},
}
}
/**
* A result based on children elements.
*/
export default class ParentResult<T> extends InternalResult<T> {
public readonly configuration: T
public readonly fileName: unknown
/**
* Create the result. Children may either be in an array or in an object literal.
*
* @param children - The children containing the result elements.
*/
public constructor(public readonly children: ResultChildren) {
super()
this.configuration = new Proxy(children, handle('configuration')) as any
this.fileName = new Proxy(children, handle('fileName'))
Object.freeze(this)
}
}