refactor registries to make registration more convenient

This commit is contained in:
dswbx
2024-12-10 08:47:23 +01:00
parent 847b08b505
commit 290498de6e
7 changed files with 134 additions and 91 deletions

View File

@@ -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];
}