Home > Blockchain >  How to create Generic Entity Subscriber
How to create Generic Entity Subscriber

Time:12-24

I am working with NestJs and typeorm with Postgres Database to develop a feature to save the json of what ever get updated in the entities (maintaing update and insert logs).

I am trying to use Entity Subscriber feature of typeorm, which is working fine for one entity, but I want to create a generic Subscriber that listens to all update and insert Entity Events

I am following this article

@EventSubscriber()
export class HistorySubscriber implements EntitySubscriberInterface<User> {

listenTo(): any {
    
    return User ;
}

afterUpdate(event: UpdateEvent<User>): Promise<any> | void {
    console.log(event.entity)
 }
}

This code can listen to the events of User entity only. Is their any genric way to design this class so that it listens to all the entities.

I alreay tied to work with Generic class in TS

export class HistorySubscriber<T> implements EntitySubscriberInterface<T> {

    listenTo(): any {
        
        return T ;
    }

    afterUpdate(event: UpdateEvent<T>): Promise<any> | void {
        console.log("event========================>",Object.keys(event),event.entity)
    }
}

but getting this error

'T' only refers to a type, but is being used as a value here.ts(2693)

Please suggest a solution or a better way to do this.

CodePudding user response:

T is just a type, User is both a type (the instance type) but also a value (a constructor function you can invoke at runtime using the new operator). Types are erased at compile time, so when you say return T there really is no information to return at runtime since T is just a type.

You can make a generic version of this, if you pass in the class to the constructor of HistorySubscriber

@EventSubscriber()
export class HistorySubscriber<T> implements EntitySubscriberInterface<T> {

  constructor(private cls: new (...a:any) => T) {

  }
  listenTo(): any {
    return this.cls;
  }

  afterUpdate(event: UpdateEvent<T>): Promise<any> | void {
    console.log(event.entity)
  }
}

class User { }
class Product{ }

new HistorySubscriber(User);
new HistorySubscriber(Product);

Playground Link

  • Related