#How to implement a universal log system for entity changes using TypeORM & NestJS (with relations)

20 messages · Page 1 of 1 (latest)

wary nest
#

Hi everyone 👋

I’m building a universal logging system in NestJS using TypeORM. My goal is to track and log all changes made to entities, including nested properties and relations.

What I'm currently doing:
I use a TypeORM event subscriber (afterUpdate) to hook into update events.

I compare the old value vs new value using the diff npm library.

I store the changed paths, old values, and new values for auditing purposes.

The limitation:
TypeORM only provides the updated entity in event.entity, and not the full object with its relations or nested structure.

event.databaseEntity (the previous value) also lacks full nested relation data.

To work around this, I do the following:

Manually fetch the full object with nested relations before the update using .findOne({ relations: [...] }).

After the update, fetch the new version of the object.

Compare both versions using diff.

Manually exclude fields like id, createdAt, etc. which are irrelevant for audit logging.

What I'm asking:
Is there a better, cleaner or more efficient way to do this in NestJS with TypeORM?

Specifically to get both before and after states of an entity with all nested relations inside the subscriber or elsewhere in a universal/global context.

Bonus: any way to auto-ignore non-meaningful fields like id, timestamps, etc.

Would love to hear how others solved this or approached it differently 🙏

#

How to implement a universal log system for entity changes using TypeORM & NestJS (with relations)

robust scroll
#

What's the motivation for creating such log?

wary nest
robust scroll
#

I understand the purpose, I'm trying to understand the reason why you need such a detailed log?

#

I'm afraid there's no generic tool to do this. The closest thing I know of is Debezium, that monitors your database's transaction log and streams the changes to Kafka

wary nest
robust scroll
#

TypeORMs listeners don't use the same transaction, and you might lose the logs

wary nest
robust scroll
#

Audit logs are not a generic thing. They have business context, which is different for each application

#

You already said that you don't just need to log dumb data changes, but you need to attach meaning to them

#

Data change for different reasons, and only your business logic knows for which reason

#

Of course, you can build something generic for the scope of your project

wary nest
wary nest
#

@robust scroll Thanks a lot for your insight

shy coral
#

Doesn't your DB already have CDC?

shy coral
robust scroll