takahirox/tiny-web-metaverse

Remove boilerplate proxy code

takahirox opened this issue · 1 comments

There are many component proxy boilerplate code, like

export class FooProxy {
  private static instance: FooProxy = new FooProxy();
  private eid: number;
  private map: Map<number, Foo>;

  private constructor() {
    this.eid = NULL_EID;
    this.map = new Map();
  }

  static get(eid: number): FooProxy {
    FooProxy.instance.eid = eid;
    return FooProxy.instance;
  }

  allocate(foo: Foo): void {
    this.map.set(this.eid, foo);
  }

  free(): void {
    this.map.delete(this.eid);
  }

  get foo(): Foo {
    return this.map.get(this.eid)!;
  }
}

It's good if we can remove the duplicated code (by adding a base proxy class or a helper function?).

An idea

  1. Add annotations to component definitions
  2. Write a script that generates proxies from the annotations

Example:

Annotation

/**
 * @component
 * foo: Foo: readonly
 * bar: Bar
 */
export const FooBarComponent = defineComponent();

Output

export class FooBarProxy {
  private static instance: FooBarProxy = new FooBarProxy();
  private eid: number;
  private map: Map<number, { foo: Foo, bar: Bar }>;

  private constructor() {
    this.eid = NULL_EID;
    this.map = new Map();
  }

  static get(eid: number): FooBarProxy {
    FooBarProxy.instance.eid = eid;
    return FooBarProxy.instance;
  }

  allocate(foo: Foo, bar: Bar): void {
    this.map.set(this.eid, { foo, bar });
  }

  free(): void {
    this.map.delete(this.eid);
  }

  get foo(): Foo {
    return this.map.get(this.eid)!.foo;
  }

  get bar(): Bar {
    return this.map.get(this.eid)!.bar;
  }

  set bar(bar: Bar) {
    this.map.get(this.eid)!.bar = bar;
  }
}