In TypeORM, you can use an `EventSubscriber` to listen for various database events, including events that occur after a transaction commit. To get the updated columns after a transaction commit, you can utilize the `afterTransactionCommit` event. Here's how you can achieve this:
1. **Create an EventSubscriber**:
First, create an `EventSubscriber` class that listens for the `afterTransactionCommit` event.
```typescript
import { EventSubscriber, EntitySubscriberInterface, EventSubscriberInterface, InsertEvent, UpdateEvent, RemoveEvent, Entity, EntityManager } from 'typeorm';
@EventSubscriber()
export class YourEventSubscriber implements EntitySubscriberInterface<Entity> {
constructor(
private readonly entityManager: EntityManager,
) {
this.entityManager = entityManager;
this.entityManager.registerSubscriber(this);
}
listenTo() {
return Entity; // Replace 'Entity' with the entity class you want to monitor.
}
afterTransactionCommit(event: InsertEvent<any> | UpdateEvent<any> | RemoveEvent<any>) {
// Check the event type (InsertEvent, UpdateEvent, or RemoveEvent)
if (event instanceof UpdateEvent) {
const updatedColumns = event.updatedColumns.map(column => column.propertyName);
console.log('Updated Columns:', updatedColumns);
}
}
}
```
In this example, we listen for the `afterTransactionCommit` event and handle it for the specified entity class (replace `'Entity'` with the entity you want to monitor). We specifically look for `UpdateEvent` to retrieve information about the updated columns.
2. **Register the Event Subscriber**:
You need to register the `EventSubscriber` in your application to ensure it's active. You can do this when configuring your TypeORM connection.
```typescript
import { createConnection } from 'typeorm';
createConnection({
type: 'your_database_type',
host: 'your_database_host',
port: 5432, // Your database port
username: 'your_database_username',
password: 'your_database_password',
database: 'your_database_name',
subscribers: [YourEventSubscriber],
// ...
}).then(async (connection) => {
// Your application logic
}).catch(error => console.log(error));
```
3. **Usage and Testing**:
With your `EventSubscriber` in place, you can now observe and log the updated columns of the specified entity every time a transaction is committed.
Keep in mind that the example provided above listens for the `UpdateEvent` within the `afterTransactionCommit` event. You can extend this logic to handle other events (inserts and deletes) and more complex use cases based on your application's needs. Additionally, ensure that you replace `'Entity'` with the actual entity class you want to monitor.