@geekmidas/audit

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS构建来源已验证近 30 天下载 1.3万

Type-safe audit logging with database integration for tracking application events and user actions

原始使用文档
文档目录21 节
  1. Overview
  2. Features
  3. Installation
  4. Quick Start
  5. 1. Define Your Audit Actions
  6. 2. Set Up Storage
  7. 3. Create an Auditor
  8. 4. Record Audits
  9. Transactional Audits
  10. API Reference
  11. Core Types
  12. Auditor Interface
  13. AuditStorage Interface
  14. KyselyAuditStorage
  15. KnexAuditStorage
  16. InMemoryAuditStorage
  17. CacheAuditStorage
  18. Database Schema
  19. Integration with @geekmidas/constructs
  20. Best Practices
  21. License

@geekmidas/audit

Type-safe audit logging with database integration for tracking application events and user actions

Overview

@geekmidas/audit provides a comprehensive solution for recording and persisting audit trails in your application. It supports type-safe audit actions, transactional writes, and flexible storage backends.

Features

  • Type-safe Audit Actions: Define audit types with TypeScript for compile-time safety
  • Transactional Support: Flush audits atomically within database transactions
  • Flexible Storage: Pluggable storage interface (Kysely, Knex, in-memory, cache)
  • Actor Tracking: Record who performed each action (users, services, systems)
  • Rich Metadata: Attach request context, entity references, and custom data
  • Query Support: Query audit logs with filters, pagination, and sorting

Installation

npm install @geekmidas/audit
# or
pnpm add @geekmidas/audit

Quick Start

1. Define Your Audit Actions

import type { AuditableAction } from '@geekmidas/audit';

// Define type-safe audit actions
type AppAuditAction =
  | AuditableAction<'user.created', { userId: string; email: string }>
  | AuditableAction<'user.updated', { userId: string; changes: string[] }>
  | AuditableAction<'order.placed', { orderId: string; total: number }>;

2. Set Up Storage

For Development/Testing (InMemoryAuditStorage):

import { InMemoryAuditStorage } from '@geekmidas/audit/memory';

const storage = new InMemoryAuditStorage<AppAuditAction>();

// Query stored records
const records = await storage.query({ type: 'user.created' });

// Clear all records (useful in tests)
storage.clear();

For Production (KyselyAuditStorage):

import { KyselyAuditStorage } from '@geekmidas/audit/kysely';

// Define your database schema
interface Database {
  audit_logs: AuditLogTable;
  // ... other tables
}

const storage = new KyselyAuditStorage<Database>({
  db: kyselyDb,
  tableName: 'audit_logs',
});

For Production (KnexAuditStorage):

import { KnexAuditStorage } from '@geekmidas/audit/knex';

const storage = new KnexAuditStorage({
  db: knexDb,
  tableName: 'audit_logs',
});

3. Create an Auditor

import { DefaultAuditor } from '@geekmidas/audit';

const auditor = new DefaultAuditor<AppAuditAction>({
  actor: { id: 'user-123', type: 'user' },
  storage,
  metadata: {
    requestId: 'req-456',
    endpoint: '/api/users',
  },
});

4. Record Audits

// Type-safe audit calls - TypeScript enforces correct payload shapes
auditor.audit('user.created', {
  userId: '789',
  email: '[email protected]',
}); // OK

auditor.audit('user.created', {
  orderId: '123', // Type error - wrong payload shape
});

// Flush to storage
await auditor.flush();

Transactional Audits

Use withAuditableTransaction to ensure audits are atomic with your database operations:

import { withAuditableTransaction } from '@geekmidas/audit/kysely';

const result = await withAuditableTransaction(
  db,
  auditor,
  async (trx) => {
    // Database operations
    const user = await trx
      .insertInto('users')
      .values({ name: 'John', email: '[email protected]' })
      .returningAll()
      .executeTakeFirstOrThrow();

    // Audit is recorded
    auditor.audit('user.created', {
      userId: user.id,
      email: user.email,
    });

    return user;
  },
);
// Audits are automatically flushed before transaction commits
// If flush fails, the entire transaction rolls back

API Reference

Core Types

AuditableAction<TType, TPayload>

Defines an auditable action with a type and payload:

type UserAction = AuditableAction<'user.created', { userId: string }>;

AuditRecord

Complete audit record with all metadata:

interface AuditRecord<TPayload = unknown> {
  id: string;
  type: string;
  operation: AuditOperation;
  table?: string;
  entityId?: string | Record<string, unknown>;
  oldValues?: Record<string, unknown>;
  newValues?: Record<string, unknown>;
  payload?: TPayload;
  timestamp: Date;
  actor?: AuditActor;
  metadata?: AuditMetadata;
}

AuditActor

Represents who performed the action:

interface AuditActor {
  id?: string;
  type?: string;
  [key: string]: unknown;
}

AuditMetadata

Request context and additional data:

interface AuditMetadata {
  requestId?: string;
  endpoint?: string;
  method?: string;
  ip?: string;
  userAgent?: string;
  [key: string]: unknown;
}

Auditor Interface

interface Auditor<TAuditAction, TTransaction> {
  readonly actor: AuditActor;

  // Type-safe audit recording
  audit<TType extends ExtractAuditType<TAuditAction>>(
    type: TType,
    payload: ExtractAuditPayload<TAuditAction, TType>,
    options?: AuditOptions,
  ): void;

  // Raw record insertion
  record(record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>): void;

  // Get collected records
  getRecords(): AuditRecord[];

  // Flush to storage
  flush(trx?: TTransaction): Promise<void>;

  // Clear without flushing
  clear(): void;

  // Add metadata to future records
  addMetadata(metadata: AuditMetadata): void;

  // Transaction management
  setTransaction(trx: TTransaction): void;
  getTransaction(): TTransaction | undefined;
}

AuditStorage Interface

Implement this interface for custom storage backends:

interface AuditStorage<TAuditAction> {
  // Required: Write records
  write(records: AuditRecord[], trx?: unknown): Promise<void>;

  // Optional: Query records
  query?(options: AuditQueryOptions): Promise<AuditRecord[]>;

  // Optional: Count records
  count?(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;

  // Optional: Get database for transactions
  getDatabase?(): unknown;
}

KyselyAuditStorage

Built-in Kysely storage implementation:

const storage = new KyselyAuditStorage({
  db: kyselyDb,
  tableName: 'audit_logs',
  databaseServiceName: 'database', // Optional: for automatic transaction injection
  autoId: false, // Optional: let database generate IDs
});

// Query audits
const audits = await storage.query({
  type: 'user.created',
  actorId: 'user-123',
  from: new Date('2024-01-01'),
  limit: 100,
  orderBy: 'timestamp',
  orderDirection: 'desc',
});

// Count audits
const count = await storage.count({
  type: ['user.created', 'user.updated'],
  actorId: 'user-123',
});

KnexAuditStorage

Built-in Knex storage implementation. It mirrors KyselyAuditStorage — same config, same query()/count() filters, same transaction semantics:

import { KnexAuditStorage } from '@geekmidas/audit/knex';

const storage = new KnexAuditStorage({
  db: knexDb,
  tableName: 'audit_logs',
  databaseServiceName: 'database', // Optional: for automatic transaction injection
  autoId: false, // Optional: let database generate IDs
});

const audits = await storage.query({
  type: 'user.created',
  actorId: 'user-123',
  from: new Date('2024-01-01'),
  limit: 100,
  orderBy: 'timestamp',
  orderDirection: 'desc',
});

const count = await storage.count({
  type: ['user.created', 'user.updated'],
  actorId: 'user-123',
});

Column names are camelCase, matching the Kysely storage. If your database uses snake_case columns, configure Knex with a case mapper:

import { knexSnakeCaseMappers } from 'objection';

const knexDb = knex({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  ...knexSnakeCaseMappers(),
});

Transactions work the same way as the Kysely storage:

import { withAuditableTransaction } from '@geekmidas/audit/knex';

const user = await withAuditableTransaction(knexDb, auditor, async (trx) => {
  const [user] = await trx('users').insert(data).returning('*');

  auditor.audit('user.created', { userId: user.id, email: user.email });

  return user;
});
// Audits are flushed inside the transaction, before it commits

Passing a transaction as the first argument reuses it instead of opening a savepoint, so audits roll back with the outer transaction.

InMemoryAuditStorage

Convenience wrapper around CacheAuditStorage with InMemoryCache. Useful for testing and development:

import { InMemoryAuditStorage } from '@geekmidas/audit/memory';

const storage = new InMemoryAuditStorage<AppAuditAction>();

// Query audits (same API as other storages)
const audits = await storage.query({
  type: 'user.created',
  limit: 10,
});

// Get all records (for assertions in tests)
const allRecords = await storage.getRecords();

// Clear all records (reset for next test)
await storage.clear();

CacheAuditStorage

Cache-based storage using any @geekmidas/cache implementation:

import { CacheAuditStorage } from '@geekmidas/audit/cache';
import { InMemoryCache } from '@geekmidas/cache/memory';
import { UpstashCache } from '@geekmidas/cache/upstash';

// With in-memory cache (development/testing)
const storage = new CacheAuditStorage({
  cache: new InMemoryCache(),
  ttl: 86400, // 24 hours
});

// With Upstash Redis (production - distributed systems)
const storage = new CacheAuditStorage({
  cache: new UpstashCache({
    url: process.env.UPSTASH_REDIS_URL,
    token: process.env.UPSTASH_REDIS_TOKEN,
  }),
  prefix: 'audit', // Optional key prefix
  ttl: 604800, // 7 days
});

// Query and count work the same as other storages
const audits = await storage.query({ type: 'user.created' });
const count = await storage.count({ actorId: 'user-123' });

// Clear all records
await storage.clear();

Database Schema

Create an audit_logs table for KyselyAuditStorage or KnexAuditStorage:

CREATE TABLE audit_logs (
  id VARCHAR(21) PRIMARY KEY,  -- or use gen_random_uuid() with autoId: true
  type VARCHAR(255) NOT NULL,
  operation VARCHAR(20) NOT NULL,
  "table" VARCHAR(255),
  "entityId" VARCHAR(255),
  "oldValues" JSONB,
  "newValues" JSONB,
  payload JSONB,
  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  "actorId" VARCHAR(255),
  "actorType" VARCHAR(50),
  "actorData" JSONB,
  metadata JSONB
);

-- Recommended indexes
CREATE INDEX idx_audit_logs_type ON audit_logs(type);
CREATE INDEX idx_audit_logs_timestamp ON audit_logs(timestamp);
CREATE INDEX idx_audit_logs_actor_id ON audit_logs("actorId");
CREATE INDEX idx_audit_logs_entity_id ON audit_logs("entityId");

Integration with @geekmidas/constructs

The audit package integrates seamlessly with @geekmidas/constructs endpoints:

import { e } from '@geekmidas/constructs/endpoints';

const endpoint = e
  .post('/users')
  .body(UserSchema)
  .output(UserResponseSchema)
  .audit([
    {
      type: 'user.created',
      payload: (response) => ({
        userId: response.id,
        email: response.email,
      }),
    },
  ])
  .handle(async ({ body, auditor }) => {
    // Audits are automatically recorded and flushed
    return { id: '123', ...body };
  });

Best Practices

  1. Define all audit actions upfront: Create a union type of all possible audit actions for your application
  2. Use transactions: Wrap database operations and audits in transactions for consistency
  3. Include entity references: Use entityId and table options for easier querying
  4. Add request context: Include request IDs, endpoints, and IPs in metadata
  5. Use meaningful types: Name audit types with domain context (e.g., order.shipped not update)

License

MIT

版本与发布记录

@geekmidas/audit 共发布 210 个版本,首次发布于 2025/12/08;过去 12 个月发布了 210 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/audit 的常见问题

@geekmidas/audit 是什么?

Type-safe audit logging with database integration for tracking application events and user actions

如何安装 @geekmidas/audit?

在项目目录运行 npm install @geekmidas/audit,或使用 pnpm add / yarn add / bun add。

@geekmidas/audit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geekmidas/audit 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@geekmidas/audit 可以商用吗?

@geekmidas/audit 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@geekmidas/audit 的下载量有多少?

根据 npm 官方下载统计,@geekmidas/audit 在 2026/10/16 – 2026/11/14 这 30 天内被下载 13,398 次,日均约 447 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geekmidas/audit 还在维护吗?

最新版本 9.6.1 发布于 2026/11/16(今天);至今共发布 210 个版本,其中过去 12 个月发布了 210 个;首次发布于 2025/12/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。