-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathInMemoryVirtualPackage.ts
50 lines (45 loc) · 1.49 KB
/
InMemoryVirtualPackage.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 { PackageJSON } from '../package/PackageJSON';
import { LogFunction } from '../utils/logger';
import { VirtualPackage, VirtualPackageOptions } from './VirtualPackage';
export class InMemoryVirtualPackage implements VirtualPackage {
private log: LogFunction;
private allowNonResources: boolean;
private registeredResources: Set<string>;
constructor(
private packageJSON: PackageJSON,
private resources: Map<string, any>,
options: VirtualPackageOptions = {}
) {
this.log = options.log ?? (() => {});
this.allowNonResources = options.allowNonResources ?? false;
this.registeredResources = new Set<string>();
}
async registerResources(
register: (key: string, resource: any, allowNonResources?: boolean) => void
): Promise<void> {
this.resources.forEach((resource, key) => {
try {
register(key, resource, this.allowNonResources);
this.registeredResources.add(key);
} catch (e) {
this.log('error', `Failed to register resource with key: ${key}`);
if (e.stack) {
this.log('debug', e.stack);
}
}
});
}
getPackageJSON(): PackageJSON {
return this.packageJSON;
}
getResourceByKey(key: string) {
if (this.registeredResources.has(key)) {
const resource = this.resources.get(key);
if (!resource) {
throw new Error(`Could not find in-memory resource with key: ${key}`);
}
return resource;
}
throw new Error(`Unregistered resource key: ${key}`);
}
}