Search code examples
javascriptnode.jstypescripttypeorm

Typeorm listeners with parameters


Is it possible to use TypeORM listeners with parameters?

Example:

@BeforeInsert()
public async doSomething(myImportantParam) {
    // using myImportantParam here
}

Solution

  • As in @BeforeInsert documentation, it does not allow you to add any parameters to the listener.

    However, I believe you can create a constructor for your entity that takes myImportantParam as an argument and you can use this.myImportantParam to access the value within the listener.

    Below here is an example code (assume myImportantParam is a string).

    Entity class:

    @Entity()
    export class Post {
        constructor(myImportantParam: string) {
            this.myImportantParam = myImportantParam;
        }
    
        myImportantParam: string;
    
        @BeforeInsert()
        updateDates() {
            // Now you can use `this.myImportantParam` to access your value
            foo(this.myImportantParam);
        }
        
        /*... more code here ...*/
    }
    

    Service Class:

    export class PostService {
        async addNewPost() {
            const myImportantParam = 'This is what I need!';
            const post = new Post(myImportantParam);
    
            // Add any other properties the post might have
            /*... more code here ...*/
    
            // Insert the updated post
            await getRepository(Post).insert(post);
        }
    
        /*... more code here ...*/
    }
    

    Hope this helps. Cheers 🍻 !!!