TypeORM - Entity Listener and Logging


Advertisements

Entity listener is used in entities which supports custom method and listen specific events. We can define any entity custom method using decorators. Let’s understand decorators in brief.

  • @AfterLoad − When the entity is loaded using QueryBuilder or repository/manager, this method will be called.
  • @BeforeInsert − This method will call before the entity is inserted using repository/manager.
  • @AfterInsert − This method will call after the entity is inserted using repository/manager.
  • @BeforeUpdate − This method will call it before an existing entity is updated using repository/manager.
  • @AfterUpdate − It will call after an entity is updated.
  • @BeforeRemove − It will call before an entity is removed.
  • @AfterRemove − It will call after an entity is removed.

Subscriber

Subscriber is used to listen specific entity events. It is implemented from EntitySubscriberInterface. Let’s understand a simple example for how to use entity listener in subscriber. Consider the Student entity is shown below −

Student.ts

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; 

@Entity() 
export class Student {     

   @PrimaryGeneratedColumn() 
   id: number; 
   
   @Column() 
   Name: string; 
   
   @Column() 
   age: number; 
}

Create student subscriber

Subscriber is created using the below command −

typeorm subscriber:create -n StudentSubscriber

The above command creates a subscriber directory inside your project src. Then, StudentSubscriber.ts file is created inside your subscriber. You could see the following response,

Subscriber /Users/workspace/TypeORM/FirstProject/src/subscriber/StudentSubscriber.ts has been created successfully.

Now move to file, you could see the below coding −

StudentSubscriber.ts

import {EventSubscriber, EntitySubscriberInterface} from "typeorm"; 

@EventSubscriber() 
export class StudentSubscriber implements EntitySubscriberInterface<any> { 
}

Now, add the following changes in the file,

import {EventSubscriber, EntitySubscriberInterface,InsertEvent} from "typeorm"; 
import {Student} from "../entity/Student"; 

@EventSubscriber() 
export class StudentSubscriber implements EntitySubscriberInterface<any> { 
   listenTo() 
   { 
      return Student; 
   } 
   
   afterInsert(event: InsertEvent<Student>) { 
      console.log(event); 
   } 
}

Here,

We have used afterInsert() method to call the entity event. Similarly, you can use other events as well. We have already configured ormconfig.json file. Now, add the below changes in index.ts file as follows −

index.ts

import "reflect-metadata"; import {createConnection} from "typeorm"; import {Student} from "./entity/Student"; 

createConnection().then(async connection => {

   console.log('connection established'); 
}).catch(error => console.log(error));

After executing the application, you could see the below output on your screen,

Application

Logging

Database logging is an important part of your highly available database solution design because database logs make it possible to recover from a failure, and they make it possible to synchronize primary and secondary databases.

All databases have logs associated with them. These logs keep records of database changes. If a database needs to be restored to a point beyond the last full, off-line backup, logs are required to roll the data forward to the point of failure.

Logging options

Logging is enabled by adding {logging: true} in database connection. Logging options are classified into different types. They are as follows −

query − return all log queries. It is defined as given below −

{ 
   host: "localhost",
   ... 
   logging: ["query"] 
}

error − return logs for all failed queries and errors. It is defined below −

{ 
   host: "localhost",
   ... 
   logging: ["error"] 
}

schema − return logs for the schema.

warn − return internal ORM warnings.

info − return logs internal ORM informative messages.

log − return internal ORM log messages.

Custom logger

Custom logging is simple and highly customizable logging option. We can create our own logger class using the below code −

import {Logger} from "typeorm"; 

export class MyCustomLogger implements Logger { 
   
   // implement all methods from logger class 
}

Connection option is specified in ormconfig.json as follows −

name: "mysql", 
type: "mysql", 
host: "localhost", 
port: 3306, 
username: "root", 
password: "root", 
database: "test", 
logger: new MyCustomLogger()
Advertisements