javascript - 带有参数的 Typeorm 监听器

标签 javascript node.js typescript typeorm

是否可以使用带参数的 TypeORM 监听器?

例子:

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

最佳答案

@BeforeInsert文档,它不允许您向监听器添加任何参数。

但是,我相信您可以为您的实体创建一个构造函数,该构造函数将 myImportantParam 作为参数,并且您可以使用 this.myImportantParam 访问监听器中的值。

下面是一个示例代码(假设myImportantParam 是一个字符串)。

实体类:

@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 ...*/
}

希望这对您有所帮助。干杯🍻!!!

关于javascript - 带有参数的 Typeorm 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67334396/

相关文章:

javascript - 获得偏移然后使位置绝对

javascript - 使用 jQuery 连续交换两个内联跨度元素

javascript - 如何销毁javascript中的对象?

javascript - Nightmarejs,单击文本(如果存在)

node.js - 使用eosjs部署EOS智能合约时出现 'missing setcode.vmtype (type=uint8)'错误如何解决?

javascript - 如何使用 kotlin JS 测试 UI? (例如,页面上有一个元素)

android - 在 Node.js Hapi 上大文件上传失败

typescript - 如何在nestjs单元测试中模拟nest-winston记录器依赖项

javascript - 确保值环绕 360 度时正确插值

typescript - 如何在 JestJs 中对 TypeScript 类的构造函数中抛出的异常进行单元测试