Refactoring a generic abstract base class with static methods

Viewed 20

I'm trying to refactor the following firebase interaction code with custom classes using a single base class:


interface A {
    /** */
}

interface B {
    /** */
}

class ModelA {
  readonly docRef: DocumentReference<ModelA>;

  constructor(public data: A, id?: string) {
    this.docRef = id
      ? doc(ModelA.collection, id)
      : doc(ModelA.collection);
  }

  get id() {
    return this.docRef.id;
  }

  // ---------------------------
  // Firestore interaction
  static firestoreConverter: FirestoreDataConverter<ModelA> = {
    toFirestore(modelObj) {
      return modelObj.data || {};
    },
    fromFirestore(snapshot, options?) {
      const data = snapshot.data(options) as A;
      return new ModelA(data, snapshot.id);
    },
  };
  static collection = collection(db, "ModelA").withConverter(
    ModelA.firestoreConverter
  );
  // ---------------------------
  // Class functions
}

class ModelB {
  readonly docRef: DocumentReference<ModelB>;

  constructor(public data: A, id?: string) {
    this.docRef = id
      ? doc(ModelB.collection, id)
      : doc(ModelB.collection);
  }

  get id() {
    return this.docRef.id;
  }

  // ---------------------------
  // Firestore interaction
  static firestoreConverter: FirestoreDataConverter<ModelB> = {
    toFirestore(modelObj) {
      return modelObj.data || {};
    },
    fromFirestore(snapshot, options?) {
      const data = snapshot.data(options) as B;
      return new ModelB(data, snapshot.id);
    },
  };
  static collection = collection(db, "ModelB").withConverter(
    ModelB.firestoreConverter
  );
  // ---------------------------
  // Class functions
}

ModelA and ModelB share the core interaction with firebase. Is there a way to refactor these two classes into a single base class in a type safe way?

0 Answers
Related