@brownnrl/tcdc-audit-backend-lib
Version:
Backend library for managing audit trail data
190 lines (138 loc) • 5.74 kB
Markdown
# TCDC Audit Backend Library Schema Documentation
## Overview
The **TCDC Audit Backend Library** provides a robust schema and utility functions to track changes to data records with detailed granularity. The library is designed to ensure auditability, transparency, and flexibility, enabling systems to log, monitor, and retrieve changes effectively.
### Purpose of the Functions
The `track*` functions (`trackCreation`, `trackUpdate`, `trackDeletion`) are key utilities that generate structured audit records for different types of data changes. These functions:
- **Simplify Audit Trail Creation**: Automatically generate audit records based on input data and user/system metadata.
- **Ensure Consistency**: Centralize the logic for tracking changes, reducing redundancy and potential errors.
- **Enable Extensibility**: Designed to support future enhancements, such as additional customization rules.
## Schema Structure
The audit trail schema is designed with the following main elements:
### High-Level Fields
1. `changeType`: The type of change (e.g., `created`, `updated`, `deleted`).
2. `notes`: Record-level notes providing context for the change event.
3. `changes`: Array of field-level changes, detailing what was modified.
4. `changedBy`: Metadata about the user or system that made the change.
5. `timestamp`: A timestamp indicating when the change occurred.
### Field-Level Changes
Each field-level change contains:
- `field`: Name of the field that was changed.
- `oldValue`: Value of the field before the change.
- `newValue`: Value of the field after the change.
- `oldValueType`: Data type of the `oldValue`.
- `newValueType`: Data type of the `newValue` (only if it differs from `oldValueType`).
- `notes`: Notes or context specific to the field change (optional).
## `track*` Functions: Detailed Overview
### `trackCreation`
**Purpose**:
Tracks the initial state of a record when it is first created. Logs all fields in the data object as "created."
**Key Features**:
- Marks the `changeType` as `created`.
- Captures the initial values of all fields in the `data` object.
- Supports field-level and record-level notes.
**Example Usage**:
```typescript
import { trackCreation } from './src/functions/audit-track-changes';
const auditRecord = trackCreation({
data: { name: 'John Doe', age: 30 },
changedBy: { profileId: 'admin123', name: 'Admin User' },
notes: ['Initial record creation'],
});
console.log(auditRecord);
```
### `trackUpdate`
**Purpose**:
Identifies and logs field-level differences between an old state and a new state, capturing only the changed fields.
**Key Features**:
- Marks the `changeType` as `updated`.
- Logs each field-level change with its old and new values.
- Excludes fields specified in the `ignoreKeys` list.
- Supports field-specific notes via the `fieldNotes` parameter.
**Example Usage**:
```typescript
import { trackUpdate } from './src/functions/audit-track-changes';
const auditRecord = trackUpdate({
oldState: { name: 'John Doe', age: 30 },
newState: { name: 'Jane Doe', age: 30 },
changedBy: { profileId: 'user456', name: 'Editor User' },
notes: ['Name correction'],
ignoreKeys: ['age'],
});
console.log(auditRecord);
```
### `trackDeletion`
**Purpose**:
Logs metadata for a record deletion event. Since no field-level changes are tracked for deletions, this function focuses on high-level metadata.
**Key Features**:
- Marks the `changeType` as `deleted`.
- Supports record-level notes to describe the deletion context.
- Includes `changedBy` metadata and timestamps.
**Example Usage**:
```typescript
import { trackDeletion } from './src/functions/audit-track-changes';
const auditRecord = trackDeletion({
changedBy: { profileId: 'admin123', name: 'Admin User' },
notes: ['Record deleted for compliance'],
});
console.log(auditRecord);
```
## Converting `IRawAuditEvent` to `AuditEvent` for MongoDB
The `IRawAuditEvent` format generated by the `track*` functions can be easily converted to a Mongoose `AuditEvent` instance for saving in MongoDB. Use the following pattern:
**Example Usage**:
```typescript
import { AuditEvent } from './src/models/audit-trail-events';
import { trackUpdate } from './src/functions/audit-track-changes';
// Generate an IRawAuditEvent
const auditRecord = trackUpdate({
oldState: { name: 'John Doe', age: 30 },
newState: { name: 'Jane Doe', age: 30 },
changedBy: { profileId: 'user456', name: 'Editor User' },
});
// Convert to a MongoDB-compatible AuditEvent document
const mongoRecord = new AuditEvent(auditRecord);
// Save the document to MongoDB
await mongoRecord.save();
```
## Example: Audit Trail Record (JSON Format)
This example demonstrates a full audit trail record with field-level changes and metadata.
```json
{
"changeType": "updated",
"notes": ["Adjusted contact information"],
"changes": [
{
"field": "email",
"oldValue": "john.doe@example.com",
"newValue": "jane.doe@example.com",
"oldValueType": "string",
"newValueType": "string",
"notes": "Email corrected"
},
{
"field": "phoneNumber",
"oldValue": "123-456-7890",
"newValue": "987-654-3210",
"oldValueType": "string",
"newValueType": "string",
"notes": "Phone number updated"
}
],
"changedBy": {
"profileId": "user123",
"name": "Admin User",
"isSystem": false
},
"timestamp": "2024-01-01T12:00:00Z"
}
```
# Custom Notes
- Use the `notes` parameter for high-level notes.
- Use the `fieldNotes` parameter to add context to specific fields during updates.
For additional details, refer to the `README.md` at the root level or contact the repository maintainers.