Reputation: 576
Is it possible to use TypeORM listeners with parameters?
Example:
@BeforeInsert()
public async doSomething(myImportantParam) {
// using myImportantParam here
}
Upvotes: 3
Views: 1397
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()
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 ...*/
}
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