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.
lib/src/util/support/global.ts

49 lines
1.2 KiB

import {Collection} from "../collection/Collection";
import {uuid_v4} 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', uuid_v4())
}
/**
* Store the given `value` associated by `key`.
* @param key
* @param value
*/
public setGlobal(key: string | symbol, value: any): 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()