Search code examples
postgresqlsequelize.jstypeorm

TypeORM: subscribe to two models


Hi I have been working with TypeORM and Im having trouble subscribing to two models, actions... I want to listen to changes on two models not just one

I have 2 models User and Post How can I listen to update on both of those models

import { EntitySubscriberInterface, EventSubscriber, InsertEvent, UpdateEvent } from 'typeorm';
import { User } from '../users/user.entity';

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

    listenTo() {
        return User; // here i would like to listen also to post Updates
    }


    /**
     * Called after User update.
     */
    async afterUpdate(event: UpdateEvent<User>) {
        const newValue = event.entity;

    }

}

Solution

  • A EntitySubscriberInterface can only listen to

    • exactly one entity or
    • to any (all) entities

    See the documentation for an example. If you look at the corresponding code line in TypeORM that evaluates listenTo(), it should also be possible to filter for a parent class of entity classes.

    subscriber.listenTo().isPrototypeOf(target);
    

    So if the User and Post entity class inherits from the same parent class, it should be possible to subscribe to both classes with one subscriber.