我正在使用帶有 Postgres 資料庫的 NestJs 和 typeorm 來開發一項功能,以保存物體中更新內容的 json(維護更新和插入日志)。
我正在嘗試使用 typeorm 的物體訂閱者功能,它對一個物體作業正常,但我想創建一個通用訂閱者來監聽所有更新并插入物體事件
我正在關注這篇文章
@EventSubscriber()
export class HistorySubscriber implements EntitySubscriberInterface<User> {
listenTo(): any {
return User ;
}
afterUpdate(event: UpdateEvent<User>): Promise<any> | void {
console.log(event.entity)
}
}
此代碼只能偵聽 User 物體的事件。他們是否有任何通用方式來設計這個類,以便它偵聽所有物體。
我已經與 TS 中的 Generic 類有關
export class HistorySubscriber<T> implements EntitySubscriberInterface<T> {
listenTo(): any {
return T ;
}
afterUpdate(event: UpdateEvent<T>): Promise<any> | void {
console.log("event========================>",Object.keys(event),event.entity)
}
}
但收到此錯誤
'T' 僅指一種型別,但在此處用作值。ts(2693)
請提出解決方案或更好的方法來做到這一點。
uj5u.com熱心網友回復:
T只是一個型別,User既是一個型別(實體型別),也是一個值(一個可以在運行時使用new運算子呼叫的建構式)。型別在編譯時被擦除,所以當你說return T在運行時真的沒有資訊要回傳時,因為T它只是一個型別。
如果您將類傳遞給建構式,則可以制作此通用版本 HistorySubscriber
@EventSubscriber()
export class HistorySubscriber<T> implements EntitySubscriberInterface<T> {
constructor(private cls: new (...a:any) => T) {
}
listenTo(): any {
return this.cls;
}
afterUpdate(event: UpdateEvent<T>): Promise<any> | void {
console.log(event.entity)
}
}
class User { }
class Product{ }
new HistorySubscriber(User);
new HistorySubscriber(Product);
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392704.html
標籤:打字稿 PostgreSQL的 嵌套 打字机 nestjs-配置
