TypeORM Auditing: Create history tables and manage changes of entities automagically.
npm install @n4it/typeorm-auditTo install the latest version:
``shell`
npm install @n4it/typeorm-audit --save
Or using Yarn:
`shell`
$ yarn add @n4it/typeorm-audit
:
`typescript
import { Audit } from "@n4it/typeorm-audit";
import { Entity, Column } from "typeorm";@Audit() // Enable auditing for this entity
@Entity()
export class User {
@Column() firstName: string;
@Column() lastName: string;
@Column() age: number;
}
`Integrate with your
DataSource:`typescript
import { withAuditDataSource } from "@n4it/typeorm-audit";
import { DataSource } from "typeorm";const dataSource = await withAuditDataSource(
new DataSource({
type: 'sqlite',
database: ':memory:',
synchronize: true,
logging: 'all',
entities: [User],
})
);
await dataSource.initialize();
`Or using
getAuditOptions:`typescript
import { getAuditOptions } from "@n4it/typeorm-audit";
import { DataSource } from "typeorm";const dataSource = new DataSource(
await getAuditOptions({
type: 'sqlite',
database: ':memory:',
synchronize: true,
logging: 'all',
entities: [User],
})
);
await dataSource.initialize();
`Advanced Features
Specify Modified By:`typescript
@Audit({
getModifiedBy: async (connection, newEntity) => {
// Use the connection to query the database
return newEntity.lastModifiedBy ?? 1;
}
})
@Entity()
export class User {
@Column() firstName: string;
@Column() lastName: string;
@Column() age: number;
}
`Use a single
audit table:`typescript
@Audit({ tableName: "audit", saveEntityType: true })
@Entity()
export class User {
@Column() firstName: string;
@Column() lastName: string;
@Column() age: number;
}@Audit({ tableName: "audit", saveEntityType: true })
@Entity()
export class Company {
@Column() name: string;
}
`Migrations
Enhance your DataSource with auditing capabilities:`typescript
import { DataSource } from "typeorm";
import { join } from "path";
import { withAuditDataSource } from "@n4it/typeorm-audit";export default withAuditDataSource(
new DataSource({
type: "postgres",
useUTC: true,
host: process.env.host,
port: process.env.port,
username: process.env.user,
password: process.env.password,
database: process.env.name,
synchronize: false,
entities: [
${join(process.cwd(), "src", "entities")}/*],
migrations: [${join(__dirname, "migrations")}/*],
migrationsTableName: "migrations",
logging: true,
}),
);
``This project exists thanks to all the people who contribute.
#### Organizations
Currently this project is sponsored and maintained by N4IT. Get in touch if you want to become a sponsor.