Chris Eikrem
Chris Eikrem

Reputation: 576

Typeorm listeners with parameters

Is it possible to use TypeORM listeners with parameters?

Example:

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

Upvotes: 3

Views: 1397

Answers (1)

Eranga Heshan
Eranga Heshan

Reputation: 5814

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 🍻 !!!

Upvotes: 2

Related Questions