/
optionalLoader.ts
52 lines (47 loc) · 1.4 KB
/
optionalLoader.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
import { BasicDataContainer } from '../dataContainers/basicDataContainer'
import type { Loader } from './loader'
import type { DataContainer } from '../dataContainers/dataContainer'
import type { Reference } from '../dataContainers/reference'
/**
* Optional loader.
* Decorates the given loader and ignores errors thrown by it.
*/
export class OptionalLoader<T> implements Loader<Partial<T>> {
constructor(
private readonly loader: Loader<T>,
) {
}
/**
* Load the configuration asynchronously and return it,
* or return `undefined` if the inner loader fails.
*/
async load(): Promise<DataContainer<Partial<T>>> {
try {
return await this.loader.load()
} catch {
return new BasicDataContainer(this.loader, <T>{})
}
}
/**
* Load the configuration synchronously and return it,
* or return `undefined` if the inner loader fails.
*/
loadSync(): DataContainer<Partial<T>> {
if (!this.loader.loadSync) {
throw new TypeError(`Loader '${this.loader.constructor.name}' does not support synchronous mode`)
}
try {
return this.loader.loadSync()
} catch {
return new BasicDataContainer(this.loader, <T>{})
}
}
/**
* Returns supported source references for given configuration object path.
*
* @param path Object path parts.
*/
getReferences(path: string[]): Reference[] {
return this.loader.getReferences(path)
}
}