mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-17 04:46:05 +00:00
refactor registries to make registration more convenient
This commit is contained in:
@@ -1,25 +1,42 @@
|
||||
export type Constructor<T> = new (...args: any[]) => T;
|
||||
export class Registry<Item, Items extends Record<string, object> = Record<string, object>> {
|
||||
|
||||
export type RegisterFn<Item> = (unknown: any) => Item;
|
||||
|
||||
export class Registry<
|
||||
Item,
|
||||
Items extends Record<string, Item> = Record<string, Item>,
|
||||
Fn extends RegisterFn<Item> = RegisterFn<Item>
|
||||
> {
|
||||
private is_set: boolean = false;
|
||||
private items: Items = {} as Items;
|
||||
|
||||
set<Actual extends Record<string, object>>(items: Actual) {
|
||||
constructor(private registerFn?: Fn) {}
|
||||
|
||||
set<Actual extends Record<string, Item>>(items: Actual) {
|
||||
if (this.is_set) {
|
||||
throw new Error("Registry is already set");
|
||||
}
|
||||
// @ts-ignore
|
||||
this.items = items;
|
||||
this.items = items as unknown as Items;
|
||||
this.is_set = true;
|
||||
|
||||
return this as unknown as Registry<Item, Actual>;
|
||||
return this as unknown as Registry<Item, Actual, Fn>;
|
||||
}
|
||||
|
||||
add(name: string, item: Item) {
|
||||
// @ts-ignore
|
||||
this.items[name] = item;
|
||||
this.items[name as keyof Items] = item as Items[keyof Items];
|
||||
return this;
|
||||
}
|
||||
|
||||
register(name: string, specific: Parameters<Fn>[0]) {
|
||||
if (this.registerFn) {
|
||||
const item = this.registerFn(specific);
|
||||
this.items[name as keyof Items] = item as Items[keyof Items];
|
||||
return this;
|
||||
}
|
||||
|
||||
return this.add(name, specific);
|
||||
}
|
||||
|
||||
get<Name extends keyof Items>(name: Name): Items[Name] {
|
||||
return this.items[name];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user