Informatiqal / qlik-repo-api

Package to interact with Qlik Sense Repository API (QSEoW)
https://informatiqal.com/qlik-repository-api/
MIT License
5 stars 0 forks source link

Extend base class? #271

Open countnazgul opened 1 year ago

countnazgul commented 1 year ago

Most of the classes are quite similar - the main difference is that the url is different. + some classes have extra methods. Is its possible to use a base class and just to extend it instead of implementing full class for each entity?

countnazgul commented 1 year ago

Probably will not add too much benefits but still will reduce the error possibilities.

Brief example:

// Base entity abstract class
export abstract class EntityBase<T> {
  #id: string;
  #repoClient: QlikRepositoryClient;
  #baseUrl: string;
  details: T;
  constructor(
    repoClient: QlikRepositoryClient,
    id: string,
    baseUrl: string,
    details?: T
  ) {
    if (!id) throw new Error(`tags.get: "id" parameter is required`);

    this.details = {} as T;
    this.#baseUrl = baseUrl;
    this.#id = id;
    this.#repoClient = repoClient;
    if (details) this.details = details;
  }

  async init(arg?: { force: true }) {
    if (Object.keys(this.details).length == 0 || arg?.force == true) {
      this.details = await this.#repoClient
        .Get<T>(`${this.#baseUrl}/${this.#id}`)
        .then((res) => res.data);
    }
  }

  public async remove() {
    return await this.#repoClient
      .Delete(`${this.#baseUrl}/${this.#id}`)
      .then((res) => res.status);
  }
}
// extend the abstract class
export class Tag extends EntityBase<ITag> {
  #repoClient: QlikRepositoryClient;
  #id: string;

  constructor(repoClient: QlikRepositoryClient, id: string, details?: ITag) {
    super(repoClient, id, "tag", details);
    this.#repoClient = repoClient;
    this.#id = id;
  }

  public async update(arg: { name: string }) {
    if (!arg.name) throw new Error(`tag.update: "name" parameter is required`);

    this.details.name = arg.name;

    return await this.#repoClient
      .Put<ITag>(`tag/${this.#id}`, this.details)
      .then(() => this.init({ force: true }))
      .then(() => this.details);
  }
}
// use the extended class
const a = new Tag({} as QlikRepositoryClient, "");