Audit Trail Plugin Recipe
Record an audit row for every write to a resource, in the write's own transaction, with one use() call.
This recipe builds an audit trail plugin with definePlugin. It owns its log table and subscribes to the host resource's CRUD writes itself, so installing it is one line and there is nothing to wire by hand.
The plugin
import { definePlugin } from "@brickkit/core";
export const audit = definePlugin({
name: "@acme/brick-audit",
brick: "^0.11.0",
requires: ["@brickkit/crud"],
// Created in the host's database as <resource>_audit.
tables: ({ table, text, timestamp }) => ({
audit: table("audit", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
recordId: text("record_id").notNull(),
operation: text("operation").notNull(), // create | update | delete
userId: text("user_id"),
at: timestamp("at")
.notNull()
.$defaultFn(() => new Date()),
}),
}),
resource: ({ tables, hooks }) => {
const record =
(operation: "create" | "update" | "delete") =>
async ({
id,
row,
ctx,
tx,
}: {
id?: unknown;
row?: Record<string, unknown>;
ctx: any;
tx: any;
}) => {
await tx.insert(tables.audit).values({
recordId: String(row?.id ?? id),
operation,
userId: ctx.user?.id ?? null,
});
};
// Inside the write's transaction: the audit row commits or rolls back with it.
hooks.afterCreate(record("create"));
hooks.afterUpdate(record("update"));
hooks.afterDelete(record("delete"));
return { auditLog: tables.audit };
},
});Installing it
import { crud } from "@brickkit/crud";
import { audit } from "../plugins/audit";
export const account = accountsService
.resource({ name: "account", table: accountsTable, id: accountsTable.id })
.use(
crud({
access: { authorize: ({ ctx }) => !!ctx.user },
fields: {
id: { read: true },
name: { read: true, create: true, update: true },
},
}),
)
.use(audit());Every create, update and delete through account's CRUD routes, its bulk routes and in-process calls now writes a row to account_audit. account.auditLog is the table, for reading the trail. audit must come after crud(): requires refuses it otherwise.
To audit every resource of a service, give the plugin a service part with the same hooks and install it with service.use(audit()): hooks on a service see the writes of all its resources.
Schema
Table Name: account_audit
| Field | Type | Description |
|---|---|---|
id | text | Row identifier. PK Default: crypto.randomUUID() (application) |
record_id | text | Identifier of the written row. |
operation | text | create, update or delete. |
user_id | text | The signed-in user's id, or null. Optional |
at | integer (SQLite) / timestamptz (Postgres) | When the write happened. Default: new Date() (application) |
Considerations
- Atomic writes: the hooks run inside the write's transaction and write through
tx, so an audit row exists exactly when its write committed. A hook that throws rolls the write back. Side effects outside the database belong inhooks.afterCommit. - Masking: do not copy passwords, payment details or personal data into the audit table.
- Reading the trail: expose
auditLogthrough a separate resource with restricted access, not through the audited one.