Documentation chapters
ORM

Events

Events are a way to hook into Deepkit ORM and allow you to write powerful plugins. There are two categories of events: Query events and Unit of Work events. Plugin authors usually use both to support both ways to manipulate data.

Query events

Query events are triggered when the a query via Database.query() or Session.query() is executed.

Each event has its own additional properties like the ClassSchema of the entity, the query itself, and database session. You can overwrite the query by setting a new query on Event.query.

const database = new Database(...);

const subscription = database.queryEvents.onFetch.subscribe(async event => {
    //overwrite the query of the user, so something else is executed.
    event.query = event.query.addFilter(deletedAtName, undefined);
});

//to delete the hook call unsubscribe
subscription.unsubscribe();

To get a more complex example of a plugin using events, take a look at the SoftDelete plugin.

onFetch

onFetch is triggered for all query methods related to fetching data: find(), findOne(), count(), has(), and so on. It's triggered before the actual method implementation is called.

onDeletePre / onDeletePost

onDeletePre and onDeletePost are triggered before and after Query.deleteOne() or Query.deleteMany().

onPatchPre / onPatchPost

onPatchPre and onPatchPost are triggered before and after Query.patchOne() or Query.patchMany().

Unit of Work events

Unit of work events are triggered when a new Session has been created and is then committed.

For the unit of work there are a couple of events: onUpdatePre, onUpdatePost, onInsertPre, onInsertPost, onDeletePre, onDeletePost, onCommitPre. Each with its own event. Take a look at the event type to see what information you can extract with that hook.

const database = new Database(...);

const subscription = database.unitOfWorkEvents.onInsertPre.subscribe(event => {
    console.log(event.classSchema.getName(), 'added', events.items.length, 'new items'),
});

//to delete the hook call unsubscribe
subscription.unsubscribe();
Made in Germany