You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.3 KiB
52 lines
1.3 KiB
import {Collection} from '../collection/Collection'
|
|
import {uuid4} from './data'
|
|
|
|
/**
|
|
* Type structure for a single item in the global registry.
|
|
*/
|
|
export type GlobalRegistrant = { key: string | symbol, value: any }
|
|
|
|
/**
|
|
* A convenient class to manage global variables.
|
|
*/
|
|
export class GlobalRegistry extends Collection<GlobalRegistrant> {
|
|
constructor() {
|
|
super()
|
|
this.setGlobal('registry_uuid', uuid4())
|
|
}
|
|
|
|
/**
|
|
* Store the given `value` associated by `key`.
|
|
* @param key
|
|
* @param value
|
|
*/
|
|
public setGlobal(key: string | symbol, value: unknown): this {
|
|
const existing = this.firstWhere('key', '=', key)
|
|
if ( existing ) {
|
|
existing.value = value
|
|
} else {
|
|
this.push({
|
|
key,
|
|
value,
|
|
})
|
|
}
|
|
|
|
return this
|
|
}
|
|
|
|
/**
|
|
* Retrieve the value of the given `key`, if it exists in the store.
|
|
* @param key
|
|
*/
|
|
public getGlobal(key: string | symbol): any {
|
|
return this.firstWhere('key', '=', key)?.value
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Export a singleton global registry for all code to share.
|
|
*
|
|
* Exporting an instance here guarantees that all code that import it will get the same instance.
|
|
*/
|
|
export const globalRegistry = new GlobalRegistry()
|